ZubairAhmed ZubairAhmed - 2 years ago 104
Ajax Question

How to pass variable from php file to ajax using json?

I can't seem to get the variable to ajax success function. (there is only one variable and nothing more)


var last_msg_id = $(this).attr("id");

$.ajax({//Make the Ajax Request
type: "POST",
url: "moredivid.php",
datatype: 'json',
data: "lastmsg="+ last_msg_id,
success: function(data){//html = the server response html code
$('a.load_more').attr('id',data.msg_id);//Loading id during the Ajax Request


$msg_id=array("msg_id" => $msg_id);
echo json_encode($msg_id);

when I output(alert) only 'data' instead of 'data.msg_id' I get {"msg_id":"blah"} and the div id becomes


with the space in front.
Output of data.msg_id gives undefined.

Answer Source

You have just type the wrong properties. Just change from

url: "moredivid.php",
datatype: 'json',
data: "lastmsg="+ last_msg_id, 


url: "moredivid.php",
dataType: 'json',
data: "lastmsg="+ last_msg_id, 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download