I have a webpage that generates a table from mysql. I have a button at the beginning of each row. I would like it so if the user decides to press on the button, the contents of that individual row are written to a new table in MySQL.
Currently I am thinking of just having the button be an href to another php script that connects to mysql and inserts the row into a table; however, I think that will redirect my current page.
I would like the button to run the script, without redirecting my current page. That way, the user can continue analyzing the table without having the page have to reload every time.
This is what my current table looks like. This is just a snippet, and the table can be very large (hundreds of rows)
We will use ajax to execute a PHP code and get a response from it without reloading the page (like in a live search). Let's go to the code! Here, we call the example. php file and we save its response on a variable that we called response.
Can I use onclick in PHP? Wrong Interpretation of Onclick Event in PHP In addition to that, PHP handles server-side client requests and database connections. PHP has nothing to relate to the user side, on-screen interaction. So, we can not set an on click event of client-side javascript with a PHP function.
Of course it is possible to add a cron job and then delete it after the job has been executed once, but it is not a very good method. To run a PHP script at a given time only once, use the Linux's at command. at schedules a job to be executed only once.
In order to do this client side, there are a couple of ways I can think of off hand to do this:
Javascript
You can include a Javascript library (like the ever popular JQuery library), or code it yourself, but you could implement this as an XMLHTTPRequest, issued from a click handler on the button. Using a library is going to be the easiest way.
An iframe
Create a hidden iframe:
<iframe style="display:none;" name="target"></iframe>
Then just set the target of your tag to be the iframe:
<a href="your_script.php" target="target">...</a>
Whenever someone clicks on the link, the page will be loaded in the hidden iframe. The user won't see a thing change, but your PHP script will be processed.
Of the two options, I'd recommend the Javascript library unless you can't do that for some reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With