Search code examples
jqueryajaxcallbackjquery-callback

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?


Solution

  • 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.