Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button that runs a php script without changing current page

Tags:

html

php

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) enter image description here

like image 942
Ray J Tong Avatar asked Aug 14 '12 18:08

Ray J Tong


People also ask

How do I run a PHP file without reloading?

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 you use PHP with onclick?

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.

How do I run a PHP script only once?

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.


1 Answers

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.

like image 186
Telgin Avatar answered Sep 30 '22 00:09

Telgin