Reputation: 1111
How do I access the individual php variables after an ajax call? I have two variables returned from message.php $id and $messageid and I need to access these from ajax.
In my php I have:
if($array1){
$id = "1";
$messageid = $messageid;
}
ajax:
$(document).ready(function(){
$('#newmessage').on('submit',function(e) {
$.ajax({
url:'message.php',
data:$(this).serialize(),
type:'POST',
dataType: 'HTML',
success:function(data){
if($.trim(data) == "1") { <-- this needs to be data.id
$("#message").modal("hide"); <-- this needs to be #message.data.messageid
}
else{
alert("error");
}
Upvotes: 3
Views: 2337
Reputation: 22711
Try this,
In php, you need to return the responses as json format:
if ($array1) {
$id = "1";
$messageid = $messageid;
}
echo json_encode(array('id' => $id, 'messageid' => $messageid));
In Javascript: You need to retrieve the response and parse it as your way.
You should change the dataType: 'HTML',
into dataType: 'json',
Upvotes: 4
Reputation: 981
Another way of doing this apart from json:
In your php file:
echo $id."#".$messageid;
Now in your ajax success function:
$.ajax({
url:'message.php',
data:$(this).serialize(),
type:'POST',
dataType: 'HTML',
success:function(data){
var result=data.split('#');//for splitting id and message
//result[0] will contain id
// result[1] will contain msg
//use result accordingly
}
hope it helps...
Upvotes: 0
Reputation: 11693
use like in php
$arr['id'] = "1";
$arr['messageid'] = $messageid;
echo json_encode($arr);
In js ajax , use dataType: 'json'
In js in success,
Use data.id OR data.messageid.
Upvotes: 0