2

I am getting data from my database without reloading the page by posting to a php page.

function getdata() {
  $.post( "somepath/getdata.php", function(o) {
    var texts = o.split('&;');
    // o is respond from php script
  });
}

The php looks like this:

<?php
$var1 = 'bar';
$var2 = 'foo';
//vars come from database

echo $var1."&;".$var2;
?>

My problem is that I want to pass multiple variables from php without putting them into a string and seperate them by some kind of separator ( in this case &; ). Is it possible to pass such variables directly to jquery without echoing them ?

1
  • insert all value to an array Commented Jul 20, 2016 at 8:22

1 Answer 1

1

In PHP you can push your return variables to an array and json_encode it:

$result = array();
$result["var1"] = 'bar';
$result["var2"] = 'foo';

echo json_encode($result);

This returns a string that looks like:

{"var1":"bar","var2":"foo"}

And then in JavaScript:

function getdata() {
    $.post( "somepath/getdata.php", function(o) {
        var data = JSON.parse(o);
        console.log(data.var1); // logs "bar"
        console.log(data.var2); // logs "foo"
    });
}

The result is returned as a string, so first we need to parse it into a JSON object using JSON.parse. You can then access the values using the key name as set in PHP

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.