ZubairAhmed ZubairAhmed - 6 months ago 22
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)

JAVASCRIPT

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
}
});


PHP

if(isset($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$msg_id="blah";
$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

id="{"msg_id":"blah"}".


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

Answer

You have just type the wrong properties. Just change from

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

to

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