Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax function returns an error

Tags:

jquery

ajax

post

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.

like image 634
nXu Avatar asked May 07 '12 12:05

nXu


People also ask

What triggers AJAX error?

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.

What is AJAX error function?

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.

How do you handle errors in AJAX call?

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.

How can a function return a value in AJAX?

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'); } });


1 Answers

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!

like image 74
nXu Avatar answered Nov 15 '22 00:11

nXu