Arjel
Arjel

Reputation: 469

How to store a value from jquery into a php variable?

Is there a way to store a value that is retrieved from Jquery into a php variable? The jquery value that I want to store in a php variable is this:

$(this).attr("title");

How can I store this into a php variable ? Is there a way ?

Upvotes: 1

Views: 5963

Answers (3)

richardgirges
richardgirges

Reputation: 1532

Your question is a little vague but the short answer is no. However, you can use jQuery to make an AJAX server request to PHP and transfer your data to the server-side that way, of course.

Example:

JQUERY:

        var theTitle = $(this).attr("title");

        $.ajax({
            url: '/URL/TO/PHP/FILE.php',
            type: 'POST',
            data: {
                title: theTitle
            },
            success: function( data )
            {
              //data is whatever your PHP script returns
            },
            error: function(xhr) {
              // if your PHP script return an erroneous header, you'll land here
            }
        });

and PHP:

        <?php

          if ( $_POST ) {

            echo $_POST[ 'title' ];  // this is what you passed from jQuery

          }

        ?>

Upvotes: 2

Marc B
Marc B

Reputation: 360582

You've got 2 options:

  1. use an AJAX request to send the variable's value back to the server
  2. use a form to submit the value

Remember that PHP runs on a server, and its execution has terminated LONG before the javascript code ever starts running on the client.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

No, of course that it's not possible. Not only that it is not possible but it doesn't make any sense. PHP runs on the server, jQuery on the client much later after the PHP script has finished executing. So there are no any PHP variables by the time jQuery script runs on the client.

So you could either send the value back using a form, link or AJAX call to the server.

Upvotes: 0

Related Questions