John Davidson

javascript - Set PHP varibles on button press without using POST or GET

0 comments
Message:


I need to set 3 PHP variables on a button press, but the problem is I can't use POST or GET to do it due to it refreshing the page which breaks my JavaScript code as it includes an onClick event listener.


What I want my code to do exactly is, on a button press set 3 variables, $title, $description and $button_value. When the button is pressed it also sets off the JavaScript code to display a box with some information that is the 3 PHP variables.


Is there anyway to get around this issue or would I just have to rewrite my JavaScript code to work with POST/GET? I'm new to PHP and JavaScript so apologies for my incompetence.



My Answer:
You can achieve this by using AJAX to send a request to a PHP script that sets the variables without refreshing the page. Here's an example of how you can do this:

1. Create a PHP script (e.g. set_variables.php) that sets the variables when called:

php
$title = "New Title";
$description = "New Description";
$button_value = "New Button Value";
?>


2. In your HTML file, include jQuery library and write a JavaScript function that sends an AJAX request to the set_variables.php script:

html















3. When the button is clicked, the AJAX request will be sent to the set_variables.php script, which will set the PHP variables. The success function in the AJAX request will then display a box with the information using the PHP variables.

This way, you can set the PHP variables on a button press without using POST or GET requests that refresh the page.

Rate this post

4 of 5 based on 2349 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us