0

When I pass the results from getJSON to parseInfo() function just like the one below, is it possible to get results back into a php variable so that I could put the latter through another php function.

$.getJSON('getinfo.php', { id:id }, parseInfo);

function parseInfo(data) {
   <?php 
      $some_var = json_decode(data);
      function some_function($some_var) {
         // rest of the script here...
      } 
   ?>
}

Can anyone please help me out with this? I would really appreciate it.
Cheers!

DGT
  • 2,604
  • 13
  • 41
  • 60

1 Answers1

3

PHP runs BEFORE the page is sent. Javascript runs AFTER the page is sent. Therefore the only way to can run PHP is to request a page.

So, if you wanted to pass data to PHP, you would have to call another page like ajax.php:

<?php

$data = $_POST['data'];
// ... do stuff ...

?>

From your script:

$.post('ajax.php', data);

See this question.

Community
  • 1
  • 1
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
  • Wow. Thanks a lot for the quick reply. I will give it a shot. Best, – DGT Feb 21 '10 at 22:35
  • I'm sorry but may be I wasn't so clear earlier. I can't seem to achieve the thing that I want to with the way you've suggested. Firstly, because the post function (below) doesn't seem to do anything. Secondly, the whole purpose of doing this is just so a php function can format the content of one of the array element (data.desc) returned from the line: json_encode($ref[$id]) within the 'getinfo.php' script. So, the idea is to print the formated data.desc inside the same #div, like so: $('div#info').html(data.desc); // i tried function parseInfo(data) { $.post("ajax.php",data); } Thanks – DGT Feb 22 '10 at 00:14
  • Oh, I plum forgot. The `$.post()` thing is part of jQuery, a very popular Javascript framework. Given you might already use it, you have to get the data the page outputs via a function passed in the called. `$.post('ajax.php', data, function(data){ alert(data); });` – Tyler Carter Feb 22 '10 at 00:40