I have a problem in posting data via ajax to php.
First of all, my ajax can pass the data to my php script, and my php also can save it correctly.
But, after that, the 'error: function ( ) ’ of ajax always be fired.
To avoid this problem I rewrote my ajax as below.
function SetAdvisePrice(){
var AdvisePrice = $("#AdvisePrice").find("option:selected").val();
if ($("#AdvisePrice").find("option:selected").val()) {
$.ajax({
url: WebsitePath + '/settings',
data: {
AdvisePrice: $("#AdvisePrice").find("option:selected").val()
},
type: 'POST',
dataType: 'json',
success: function (Result) {
if (Result.Status == 1) {
console.log('OK');
}
else {
console.log('Failed');
}
},
error: function (jqXHR, exception) {
if(jqXHR.statusText== 'OK'){
alert('Success!');
}
else {
console.log('Failed!');
}
}
});
}
}
But, Is it safe? If it isn’t safe. How to improve my code?
Well this means that there is always an error happening that you should fix. What are the status and response headers of such a request? You might also log the 2nd and 3rd error() parameters (textStatus and errorThrown).
$.ajax({
url: WebsitePath + '/settings',
type: "post",
data: {
AdvisePrice: $("#AdvisePrice").find("option:selected").val()
},
success: function (Result) {
console.log(Result.Status);
// You will get response from your PHP page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
The above problem seems to be resolved,
But, another problem is I can’t exactly print out the result of ajax.
My php script sent back to me a response of {“Status”:“1”},
When I tried to print out the response with ‘console.log(Result.Status);’.
My chrome console gave me an ‘undefined’.
In addition, I can print out the entire result with ‘console.log(Result);’.
Ah that explains why you’re always getting an error; after echoing the JSON, you’re also appending the entire page to the response, which is then of course not valid JSON any more and result in a parse error. This has to be fixed in your PHP script; for instance, send an Accept: application/json header with your AJAX request and omit the markup when set, or simply provide a dedicated endpoint for your JSON.