santa
santa

Reputation: 12512

jQuery / PHP mix up

I have the following jQuery function in my PHP:

echo ' 
function myFunction() {
    return $.ajax({
        type: "POST",
        url: "mypage.php",
        data: "name=John&location=Boston"
    });
}

$.when(myFunction()).then(function(data) {
     // handle data return
     someOtherFunction(data);

     // need to set "data" var into PHP SESSION


}, function(error) { 
     // handle ajax error.
});
';

After my AJAX does the majic it returns a value (data), which I pass into another function. In addition I need to be able to set that value into a PHP session: $_SESSION['project'][data] = data;

How do I do that? The switching between PHP and JS confuses me for some reason...

Upvotes: 0

Views: 559

Answers (3)

Joshua - Pendo
Joshua - Pendo

Reputation: 4371

First of all you must be aware the javascript is a clientside language and PHP is serverside. Everything PHP does, it does when the page loaded and it stops after the page is loaded. Javascript takes over then.

What you could do is create mypage in a way that it also creates $_SESSION['project']['data'] as an associative array that you can use with PHP. What you're not trying to do is setting a javascript array into a PHP variable. Not that this is wrong by default, but since you're trying to SET the data using PHP my guess is you will also GET the data using PHP, thus a javascript array in that session would be useless.

So in mypage.php you've probably have something like:

echo json_encode($result);

Where $result is the array of data returned by the script. You could simply add one line above saying:

$_SESSION['project']['data'] = $result;

and have the data stored in the session to use on other pages.

Upvotes: 1

umbrae
umbrae

Reputation: 1129

That's impossible since the JS is now on the client side. You can't set PHP variables directly.

What you could do is set a cookie in JS using document.cookie, and then on the next page request PHP can get at it via $_COOKIE.

You could also just set the $_SESSION variable inside mypage.php - that may be significantly easier, if they both share the same session.

Upvotes: 2

DarthJDG
DarthJDG

Reputation: 16591

It's confusing because you're mixing the two, try to keep a distinct separation in your code. Instead of echoing your jQuery script, just close the php tag, that would also make syntax highlighting work.

As for setting session variables, you need to do it on the server side in your mypage.php, before writing the data to the output. That will happen before passing the data to the client side jQuery script for processing.

Upvotes: 1

Related Questions