简体   繁体   中英

Pass JS variable to PHP using ajax

I know this has been asked on here but none of the answers I found answered my question.

I have a PHP/HTML file that the users view. When they click on a button, it creates a JS variable which I would like translated into a PHP variable. Using that variable, I would like to update the contents of a div box by calling a PHP function which populates the box with info from the server.

My questions: Can this be done with only 1 php file? Do I have to have the user reload the page after I refresh the content? What is the best way to do this?

You can avoid the user reloading the page, but that would require AJAX. That raises the question - Does this need to work without JavaScript?

If you are happy for this to be dependant on JavaScript you could use an AJAX post, such as this using JQuery:

$.post( "example.php", { variableName: "example" })
  .done(function( response ) {
    $('.example-output').html( response );
  });

example.php would be a different .php file, in example.php you would process the value of variableName and produce the required markup, which would be displayed in the original page. If you need this to work without JavaScript then I would suggest reloading the page.

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