简体   繁体   中英

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 ?

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

          }

        ?>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM