Search code examples
jquerypythonajaxweb-servicesjquery-callback

JQuery Success/Failure Callback is not called


I am new at jQuery. What i need to achieve in jQuery is call a web service which is written in Python and show appropriate message according to the message i receive in return. Below is the jQuery code i have written so far.

$(document).ready(function(){
$("#loginForm").submit( function () { 
    data = $(this).serialize()
    var serviceUrl = MyServiceUrl;
    $.ajax({
              type: "POST",
              url: serviceUrl,
              data: data,
              success:loginSuccess,
              failure: loginFailure
    });   
    return false;   
});
});

function loginSuccess(data){
    alert(data.status);
}
function loginFailure(data){
    alert(data.status);
}

On my HTML form when i submit the form my call goes to my web service. But after recieving the response it does not go to my success or failure callback function as specified above. Below is the python code of the web service which is returning the status. It can either return case 1 or case 2

Case 1:

to_json = {"status": "success"}
return HttpResponse(simplejson.dumps(to_json), mimetype="application/json")

Case 2:

to_json = {"status": "error","message": str(e)}
return HttpResponseBadRequest(simplejson.dumps(to_json), mimetype="application/json")  

Solution

  • This issue was due to Cross-Origin XMLHttpRequest

    Below is my solution.

    When returning from python i added the following headers

    to_json = {"status": "success"}
    response = HttpResponse(simplejson.dumps(to_json), mimetype="application/json")
    response['Access-Control-Allow-Origin'] = "*"
    return response
    

    The same was with HttpResponseBadRequest. So the final jQuery code is as below.

    $(document).ready(function(){
    $("#loginForm").submit( function () { 
        data = $(this).serialize()
        var serviceUrl = MyServiceUrl;
        $.ajax({
              type: "POST",
              url: serviceUrl,
              data: data,
              success:loginSuccess,
              error: loginFailure
        });   
        return false;   
     });
    });
    
    function loginSuccess(data){
        alert(data.status);
    }
    function loginFailure(data){
        alert(data.status);
    }
    

    I hope it really helps someone..Cheers