Here’s my jQuery script:
$.ajax({
type: 'POST',
url: 'zipCodes.php',
data: searchZipCode,
cache: false,
success: function(response) {
alert ('response from db search: ' + response);
},
error: function(response) {
console.log(response);
alert('Query failed, php script returned this response: ' + response);
}
});
The above script is in the head tag of the html file the form is in. The php script is in the same folder as the html file.
Here’s the form:
<form id="frmZipCodeSearch" action="">
<label for="txtZipCodeSearch">Enter a zip code</label>
<input type="text" id="txtZipCodeSearch" length="10" maxlength="5" />
<input type="submit" id="btnSubmitZipCodeSearch" />
</form>
I also have verified that “searchZipCode” has a value.
Every time I run the search I get the alert from the error part of the ajax call, which says
Query failed, php script returned this response: [object Object]
and this shows in the console:
Object {readyState: 0, setRequestHeader: function, getAllResponseHeaders: function, getResponseHeader: function, overrideMimeType: function…}
I’ve tried stripping the php script down to just an echo. I’m not getting any php error logs generated in the folder with the script on the server. Nothing I change seems to give me a different result. With one exception:
The only time I got a different result was when I stripped out the ajax and moved the php script to the file with the form and did a “regular” html form POST method. That worked. But I don’t think the path is wrong when the php is a different file because I’m not getting a “file not found” in the console.
What the heck am I missing here?
[Additional Info]
In response to hek2mgl’s answer, I added xhr to the error response and did get some more info in the console:
Uncaught ReferenceError: xhr is not defined zipCodeSearch.html:57
$.ajax.error zipCodeSearch.html:57
l jquery-1.8.3.min.js:2
c.fireWith jquery-1.8.3.min.js:2
T jquery-1.8.3.min.js:2
r jquery-1.8.3.min.js:2
All other jQuery I’m using is working fine, but this is the first time I’ve used v1.8.3 myself.
[Answer – credit hek2mgl]
As hek2mgl explained in our crazy-long discussion, I was submitting the form twice, because the ajax call was within the click event of the form’s button.
The fix for this was to move the ajax call out of the click event into its own function, and after my client-side validation, call the ajax function and add “return false;” after the function call.
The $.ajax error callback is defined as follows:
You’ve dumped the whole jqXHR object. Unlike the success function, the respone text itself is not a param of the error callback. To retrieve the response text (if any) use this: