Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax: Send PHP variable to JS without echo?

I'm fairly new to both PHP and Ajax, so this might seem trivial, although I couldn't seem to find a clear answer to this.

I'm sending a query to a process.php using ajax, and then display the result on the page. What I've got works fine and everything's ok:

$.ajax({
   type: "POST",
   url: "process.php",
   data: { 'data1': yada, 'data2': yadayada},
   beforeSend: function(html) {
      $("#some-div").html('<p>loading</p>');
   },
   success: function(html){
      $("#some-div").html(html);
   }
});

Now, this works because I'm basically echoing the result of the query at the end of process.php, which then gets displayed in #some-div. The thing is, I'd also like to retrieve some of the data that was processed in the PHP to use it in my JS. However, I don't want to echo this data at the end of the PHP, as I don't want to display it in #some-div.

In other words, say my process.php looks like this:

$var1 = "hello world";
$var2 = "It's sunny outside";
$var3 = ["key1"=>"one", "key2"=>"two", "key3"=>"three"];

$result = $var1 . $var3["key2"];
echo $result;

The $result gets displayed in #some-div, that's fine. But what if I'd like to make a wonderful alert(); in JS with the content of the $var3["key3"] without displaying it in #some-div?

Should I make another query to do so (which seems inconvenient and inefficient), or is there a way to pass data from process.php to the JS without echoing it?

Thanks!

like image 791
Robert S. Avatar asked Oct 01 '22 02:10

Robert S.


1 Answers

Output the data as JSON so that you can have separate parts or variables:

$response = array('result' => $result, 'otherData' => $var3);
echo json_encode($response);

Javascript:

$.ajax({
   type: "POST",
   url: "process.php",
   data: { 'data1': yada, 'data2': yadayada},
   dataType : 'json', // <-- tell jQuery to parse the JSON
   beforeSend: function(html) {
      $("#some-div").html('<p>loading</p>');
   },
   success: function(response){
      alert( response.otherData.key3 );
      $("#some-div").html(response.result);
   }
});
like image 160
MrCode Avatar answered Oct 03 '22 16:10

MrCode