to be honest, I'm a total beginner with jQuery and now I'm stuck. I want to send data from my HTML form to a php, it adds the data to a database and returns some value that I'd like to display on my original HTML. Here's my code:
$.ajax({
type: "POST",
url: "http://mysite.com/process.php",
data: { data: mydata },
cache: false,
dataType: "text",
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
alert(jqXHR.statusText);
alert(jqXHR.responseText);
},
success: function(data){
getContentBox().innerHTML = data;
}
});
It returns a jqXHR object with status
=0, statusText
="error" and empty responseText
. However, my php seems to work, I see my data inserted in my DB. What am I doing wrong?
Any help would be appreciated. Thanks in advance!
EDIT: Chrome console says XMLHttpRequest cannot load http://mysite.com/data.php. Origin http://www.mysite.com is not allowed by Access-Control-Allow-Origin.
Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the . ajaxError() method are executed at this time. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
The ajaxError() method in jQuery is used to specify function to be run when an AJAX request fails. Syntax: $(document).ajaxError( function(event, xhr, options, exc) ) Parameter:: This method accepts single parameter function which is mandatory.
Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests. The fail() callback takes 3 parameters where the first parameter is a JSON error object, the second parameter is given a reason in text format and the last parameter is for the error thrown by the HTTP request.
ajax({ async: true, contentType: 'application/json; charset=utf-8', type: "POST", dataType: 'json', data: JSON. stringify(arrays), url: "MyHandler. ashx", success: function (result) { b = true; }, error: function () { alert('Error occurred'); } });
ShelbyZ's comment led me to the solution:
The browser refused to execute the request when I tried using an absolute URL, i had to write it as relative.
$.ajax({
type: "POST",
url: "process.php",
data: { data: mydata },
cache: false,
dataType: "text",
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
alert(jqXHR.statusText);
alert(jqXHR.responseText);
},
success: function(data){
getContentBox().innerHTML = data;
}
});
Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With