3

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

3 Answers 3

4

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',

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.