user951042
user951042

Reputation:

Sending data back to AJAX function

I have a simple AJAX request which sends data to a PHP and the PHP sends some sucess data back to the AJAX as usual. For example

var firstvalue = xxx;
var secondvalue = xxx2;

AJAX

$.post("some.php",{value1 : firstvalue, value2 : secondvalue}, function(data){
    if(data) {
        alert(data);
    } else {
        alert("An error occurred.");
    }
});

PHP (some.php)

$id = S_GET['someid'];
$impdata = $_GET['somegettabledata']
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];

if (value1 === value2) {
    /* 
    This is my problem I want to echo id and impdata 
    but I don't know how to pass both of them
    */
    echo "...";
} else {
    echo "Error.";
}

So how can I have both the id and impdata in that data sent back from PHP? Sorry if this comes across as stupid.

Many Thanks

Upvotes: 1

Views: 2205

Answers (2)

lauhub
lauhub

Reputation: 920

In PHP:

echo json_encode( array(
    'id' => $id,
    'impdata' => $impdata
));

In javascript you will need to parse the json string:

function(data){
    var myData = JSON.parse(data);
    alert(myData.id); //other notation: myData['id']
    alert(myData.impdata); //other notation: myData['impdata']
}

JSON parser can be found at the bottom of the following page: http://www.json.org/js.html

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382666

You can return json response and read it back with JS:

PHP:

echo json_encode(array('id' => $id, 'impdata' => $impdata));

JS:

alert(data['id']);
alert(data['impdata']);

Upvotes: 1

Related Questions