1
votes

In a jQuery ajax statement I want to receive a payload from the server and process it in another function. I am just having trouble with the syntax of the function.

    $.ajax({
    url: 'mypgm.pgm',
    type:'POST', 
    dataType: 'json',
    data:   'action=add' +
             '&techno=' + techno +
             '&activity=' + activity, 
    success: ajax_callback(msg),
    error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                    alert(thrownError);
        }       
    });
}

    function ajax_callback(msg) { 

        alert(msg);
    }
    

Response

{"response": {
    "success": "0",
    "message": "The Activity has been added."
    }
}
3
It looks like mypgm.php is responding, per the response you have here - what exactly is the problem?Jimmy Sawczuk

3 Answers

3
votes

A success callback handler for $.ajax() can take in the following values:

success(data, textStatus, jqXHR)

Source: http://api.jquery.com/jQuery.ajax/

So your function callback would be something like this:

function ajax_callback(data, textStatus, jqXHR)     
{
  alert(data.response)
}

Note how I created a named function this way, instead of assigning it to a var. If you only care about the data, you can just leave the last 2 parameters off:

function ajax_callback(data)     
{
  alert(data.response)
}
0
votes

Try this:

$.ajax({
    url: 'mypgm.php',
    type: 'POST',
    dataType: 'json',
    data: 'action=add' + '&techno=' + techno + '&activity=' + activity,
    success: function(data) {
        alert(data)
    }
});
0
votes

You callback should be defined before the ajax call and change the signature of the function to:

var ajax_callback = function(data, textStatus, xhr) {
    // parse the data.responseText to json
}

You could alternatively just use $.getJSON()