Rakesh K
Rakesh K

Reputation: 1320

How can i receive more than one responses in ajax in the same function

here is my simple code

  $.ajax({
            url:'action.php',
            method: 'POST',
            data:{getcart:1},
            success:function(response){
                $('#getcart').html(response);//want to display $return_value (from action page)
                $('#getcart2').html(response);//want to display $return_value2 (from action page)
            }
        });

Here i am sending request to action.php

and if in action.php i have echo two variables separately for example.

$return_value = " //Some html here ";  echo $return_value;
$return_value2= "//some other html";  echo $return_value2;

So the question is in ajax i have function with argument response . how i will be able to receive these both variables from php and display it in different divs. i hope you guys help me. thanks.

Upvotes: 0

Views: 210

Answers (4)

vellip
vellip

Reputation: 78

You can use json_encode to create an object like:

$array = [
    "return_value" => " //Some html here ",
    "return_value2" => "//some other html",
];
echo json_encode($array)

Then add dataType: 'json' to your ajax options. The response then will be an object like:

{
    "return_value" => " //Some html here ",
    "return_value2" => "//some other html",
}

Where you can access the specific values with e.g. response.return_value2 and thus separate them.

Upvotes: 0

Noman
Noman

Reputation: 4116

You need to use json_encode in order to get multiple records or data.

action.php

<?php 
header('Content-Type: application/json');

$array = array(
               'var1'=> 'var value 1',
               'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>

and then read your variables in JS

dataType: 'json',
success:function(response){
    console.log(response.var1);
    console.log(response.var2);
    $('#getcart').html(response.var1);
    $('#getcart2').html(response.var2);
}

Upvotes: 0

okante
okante

Reputation: 151

your could return a json from action

echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));

then in your js,

       $.ajax({
            url:'action.php',
            method: 'POST',
            data:{getcart:1},
            dataType: 'json',
            success:function(response){
                $('#getcart').html(response.cart1);//want to display $return_value (from action page)
                $('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
            }
        });

Upvotes: 1

spaceman
spaceman

Reputation: 833

Send the responses as JSON.

In PHP

$return = array( $return_value, $return_value2 );
echo json_encode($return);

In Javascript

var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);

Upvotes: 4

Related Questions