Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jquery ajax callback function not work?

I am having a problem with a simple callback function in jQuery ajax. Google won't help and stack overflow wouldn't either, so I guess this might not be something specific but rather something I am too ignorant to see. To me the code looks exactly like it should.

So, here's the code:

function sendMessage(message)
{
//Establish connection to php script
$.ajax({
    type: 'POST',
    url: 'action/chat/test.php',
    success: function(feedback){

        alert(feedback);

    }
}).error(function(){
    //Do some error handling here
});
}

In test.php it simply says

<?php
    echo "called";
?>

As far as I am concerned "called" should be alerted - but it isn't. I have checked already that the function sendMessage() is called (and the parameter message doesn't matter for now).

Does anyone have any idea?

like image 242
weltschmerz Avatar asked May 02 '12 21:05

weltschmerz


3 Answers

Update: One thing to note also, make sure you use some kind of debugger like firebug. Then you can go to the network tab and look at the request url and response manually to see if its getting a 200 response or internal server error, etc.

Try adding a console.log(data); in your success function to see if anything is being returned.

You could also use .always(data):

function sendMessage(message)
{
  //Establish connection to php script
  $.ajax({
      type: 'POST',
      url: 'action/chat/test.php'   
  }).done(function(data) { console.log(data); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });
}

From the docs:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

like image 172
Fostah Avatar answered Oct 03 '22 19:10

Fostah


Just for the reference, there is a behavior that may end up like this (ie done() not called).

Here it is:

  1. Suppose you expect a JSON object (you asked for it with the "Accept" mime type).
  2. Suppose the Json string is not valid.

In this case done() is never called, but always() will be. And in always() you will get the "badly" formatted answer as pure text.

like image 28
Nadir Avatar answered Oct 03 '22 21:10

Nadir


It's probably the error handling. If you want to handle errors, there's another attribute you can give the object you pass in to ajax, it's "error", and also "timeout" for handling page timeouts. Look up the $.ajax function and you'll find these attributes.

like image 38
DanRedux Avatar answered Oct 03 '22 21:10

DanRedux