nxu
nxu

Reputation: 2272

jQuery ajax function returns an error

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.

Upvotes: 7

Views: 8564

Answers (4)

Nick Dekhtiarenko
Nick Dekhtiarenko

Reputation: 1

I had the same problem. Ajax function was bound to the button(type="submit") inside of the <form>, so always when I pressed this button my page reloaded and error function worked instead of success. I really don't know how is this related but when I add event.preventDefault() to button's action listener and it's become working fine.

Upvotes: 0

nxu
nxu

Reputation: 2272

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!

Upvotes: 1

Clark T.
Clark T.

Reputation: 1470

Why not use the built in post function of jquery to simplify this i.e.

            $.post('http://mysite.com/process.php', mydata, function(data) {
                if (data.status == 1) {
                    getContentBox().html() = data;
                } else {
                    alert(data.status);
                    alert(data.statusText);
                    alert(data.responseText);
                }
            });

im not sure what your status responses are so you may have to edit that but this will work if you put it inside of a $('form here').submit(function() {POSTCODEHERE});

Upvotes: 0

Olivier G
Olivier G

Reputation: 125

Try this (you forgot to close a bracket) :

$.ajax({
  ...
  success: function(data){
    getContentBox().innerHTML = data;
  }
});

Upvotes: 0

Related Questions