user447752
user447752

Reputation:

Jquery variables in JSON to PHP

I'm using Jquery and PHP together to make some Ajax calls. This is similar to something I'm doing:

 $.ajax({
        type: "POST",
        dataType: 'json',
        url: "http://example/ajax",
        data: { test: test },
        cache: false,
        async: true,
        success: function( json ){

            $.each( json.rows, function( i, object ){
                //Example: object.date            
                <?php date('g:ia', $objectDate ) ?>;
            });
        }
    });

What I need is to pass some JSON objects to PHP, for example object.date to $objectDate and then do something with them. Is this possible?

Upvotes: 0

Views: 2078

Answers (2)

brianreavis
brianreavis

Reputation: 11546

Here's a basic rundown of going from JS to PHP, and PHP to JS:

To transfer an object from Javascript to PHP (and perserve it), you need to encode your data using JSON.stringify:

var data = { message: "Hello" };
$.ajax({
    data: { data: JSON.stringify(data) },
    // ...
});

Then, in PHP, you can use json_decode to convert the the posted JSON string into a PHP array that's really easy to work with:

$data = json_decode($_POST['data'], true);
echo $data['message'];
// prints "Hello"

To send JSON back as the response to the browser (for your success callback), use json_encode like so:

header('Content-type: application/json');
echo json_encode(array(
   'message' => 'Hello, back'
));

Upvotes: 1

nico
nico

Reputation: 51640

PHP is executed on the server, JS on the client. Once the server has processed the AJAX call that's it, it doesn't know anything anymore about what happens on the client.

You are already passing data from JS to PHP with your AJAX call. If you need to process that data in PHP do it before you return the call, it makes no sense to return a JSON object only to re-process it in PHP.

In summary what you should do is:

  1. Pass some data from client to server with an AJAX call
  2. PHP processes these data and returns a JSON object
  3. JS processes the JSON object and, for instance, modifies the HTML of the page.
  4. If you need to further process newly generated data with PHP do other AJAX calls.

Also, if you need JS to use any variable generated in point 2, just return it in the JSON object, that is what it is for.

Upvotes: 0

Related Questions