PHP Refresh button onclick - php

I have this while loop that echoes entries from a SQL database. I have an "Add to Cart" button which is supposed to remove the entry from the list and add it somewhere else. This part works, but once I click on the "Add to Cart" button, the entry is not removed right away, I have to manually refresh the page or visit another page and come back in order to see that the item is removed. I tried using the following (and few similar) lines on the onclick propery of the button, but it didn't work.
echo "<br /><center><input type='submit' name='submitAdd' value='Add to Cart' onclick='window.location.reload();'></center>";
Any suggestions are appreciated.
Thank you.
EDIT: This is the while loop that I use to generate the table. It is within a tag which is within the .
while ($row = mysql_fetch_array($song_query)) {
foreach ($_SESSION['selected_items'] as $key => $value) {
if ($value == $row['Item_ID']) {
$rowID = $row['Item_ID'];
echo "<tr style='background-color: #66FFFF;'>";
echo "<td><input type='checkbox' name='removeFromCart[]' value='$rowID'></td>";
echo "<td>" . $row['Item_ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Artist'] . "</td>";
echo "<td>" . $row['Album'] . "</td>";
echo "<td>" . $row['Time'] . "</td>";
echo "<td>" . $row['Year'] . "</td>";
echo "<td>" . $row['Bit_Rate'] . "</td>";
echo "<td>" . $row['Sample_Rate'] . "</td>";
echo "</tr>";
}
}
}

PHP is a server-side language, so any "actions" will be executed on the server, before the results are displayed to the user. In order to modify the page after it has been loaded on the user's browser, you have to use a client-side language, such as JavaScript. If you want to show an update to your cart without having to reload the page, then using an AJAX request is your best option. Check out the tutorial at http://www.w3schools.com/ajax/ and let me know if you have any questions about how to implement one :)
Update: Force Reload
If you want to just stick with reloading the page as is, try onclick='window.location.reload(true);' instead of onclick='window.location.reload();'. The true parameter forces a get request to the server. http://www.w3schools.com/jsref/met_loc_reload.asp

I use a link that references to the same page
Recargar

If the only feature you are looking for is to reload the page on the button's click, the way I typically do that is onclick="history.go(0)"
But if the form button is what's submitting a form and already reloads the page then I don't see why you couldn't put the while loop after your other code like this,
CHECK FOR FORM() {
UPDATE SQL DB
}
WHILE () {
OUTPUT DB DATA
}

not a button but a simple link, but maybe still useful for some:
<?php
$page = $_SERVER['PHP_SELF'];
print "Reload this page";
?>

Use header() function to refresh a web page in PHP. The PHP header() function sends an HTTP header to a client or browser in raw form.
Before HTML, XML, JSON or other output has been sent to a browser or client, a raw data is sent with the request (especially HTTP Request) made by the server as header information.
Syntax:
header ("header:url of the page")
I hope that this can place you on the right way.

Related

Trying to pass variable in url

I'm echoing this form:
echo "<form action='/leaguemaster/fichaTorneio.php?id=" . $_GET['torneioid'] . "'>";
When I submit the form and it links to the page from the action, the variable I'm passing doesn't reach the page...
/leaguemaster/fichaTorneio.php?
I've done this in other pages and it worked, I don't know what's going on here. I've tried having the same form outside a PHP echo and I get the same result.
-EDIT-
This is the full form:
echo "<form method='GET' action='/leaguemaster/fichaTorneio.php?id= " . $_GET['torneioid'] . "'>";
echo "<input type='submit' value='Voltar'>";
echo "</form>";
Use hidden type form's element named id:
echo "<form action=\"/leaguemaster/fichaTorneio.php\">";
echo "<input type=\"hidden\" name=\"id\" value=\"$_GET[torneioid]\" />"
Notice: I did not set the method attribute to the form because the GET method is the default method for HTML forms and it makes the form submits its values through the URL query string.
Please try
// check $_GET['torneioid'] value
echo 'torneioid = ' . $_GET['torneioid'] . '<br />';
echo '<form action="/leaguemaster/fichaTorneio.php?id=' . $_GET['torneioid'] . '">';
And make sure the URL contains "http:// yourdomain.com/?torneioid=something"
There are several things that you should check:
$_GET['torneioid']
This indicates that you are attempting to resolve form or other variables through GET. Make sure that you are passing information through GET and not POST.
Also make sure there is something that is actually stored in torneioid, and that the form or database that you are 'GETting' from, actually holds a value.

The best way to convert the name of a PHP array to a string [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I have an HTML table, linked to PHP $_SESSION data, to which I wish to add a Delete button to every row that deletes not only that row from the HTML table, but also from the $_SESSION variable.
This is the code that populates my table:
tableData.php
// echo the table headings
echo <<<HERE
<tr>
<th>CityID</th>
<th>State</th>
<th>City</th>
<th></th>
</tr>
HERE;
if (isset($_SESSION['cityData']))
{
foreach($_SESSION['cityData'] as $city)
{
echo "<tr>";
// print each row of data
foreach($city as $data)
{
echo "<td>" . $data . "</td>";
}
//echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
echo "</tr>";
}
}
The line that I commented out,
echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
is the line that creates the button that I am trying to create, to do what I am wanting it to do. I am trying to figure out the best way to name the array that I want gone.
P.S. I know, I should have it invoke some other function that does both tasks, it is just, if I pass the array in like I did, it will complain of " Array to string conversion ". Is there a way to do what I am trying to do, cleanly?
It's just not that simple. You need to get your buttons to submit to a link, and then have the PHP unset the content.
foreach($_SESSION['cityData'] as $index => $city) //added $index =>
{
echo "<tr>";
// print each row of data
foreach($city as $data)
{
echo "<td>" . $data . "</td>";
}
echo '<td><form method="post" action=""><input type="hidden" name="delete" value="' . $index . '"><input type="submit" value="Delete Row"></form></td>';
echo "</tr>";
}
So I added a form that a button that will submit to data that indicates the row number, so when your client clicks on the button, it will submit them and the row number will be passed as a POST variable.
At the top of tableData.php, you can then have logic handling the delete. Simply check if the delete is set, and then attempt to unset from there.
if (isset($_POST['delete']))
unset($_SESSION['cityData'][$_POST['delete']]);
You will want to have further validation that checks if POST delete within the bounds of $_SESSION['cityData'], but the basic idea is there.
You're mixing client-side and server-side code the wrong way here :(
The "client" is something like a user's browser. When a user clicks that button on their browser, it will run client-side code (i.e. JavaScript) - your PHP won't exist anymore at that stage so you don't have access to that array.
PHP is executed when a page has been requested from your server. That's when you can perform whatever computation you need and then deliver a textual response (via echo for example) back to the user's browser or whatever the client may be.
That button should make another request to your server so you can use PHP to delete the row. Then your PHP server should echo a response back to the requesting browser so users can know if it worked or not.
The link on the button will need to be provided some additional details, like the index of the row that the user wants to delete, so the PHP script doesn't delete the wrong one. See Dave Chen's answer below for some example code.

PHP echo button onclick function

For a little "webshop project" I create a table with PHP and echo"..." function. The table displays some values and in the last cells, there shall be a button which enables the user to delete the corresponding row (or better said, purchase). The data is held in a database and read out while the page loads and than displayed in the table.
I use a "purchase id" to find out which rows have to be deleted, and it works fine if I just implement the function itself. The problem is that I can't get the function working as "onclick" event for the button.
So, some code:
function delete_purchase($purchase_id){
mysql_query("DELETE FROM purchase WHERE purch_id = '$purchase_id'");};
That's the PHP function which deletes the rows, easy enough.
$result = mysql_query("SELECT purchase.purch_id, item.name, purchase.amount, purchase.purch_date, delivery.meaning, item.weight FROM purchase, item, delivery WHERE purchase.cust_id='$cust_id' AND delivery.del_id = purchase.delivered AND purchase.item_id = item.item_id");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "<td>" . $row['weight'] * $row['amount'] . "</td>";
echo "<td>" . $row['purch_date'] . "</td>";
echo "<td>" . $row['meaning'] . "</td>";
echo "<td><button onclick=\"delete_purchase('" . $row['purch_id'] . "')\">Kill</button></td>";
echo "</tr>";
}
And this is the part which doesn't seem to work. I get the variable and some other values from the database and insert them into my table as long as there are values. Everything is displayed, even the buttons; but clicking on them doesn't do anything.
Source code of the website seems fine:
<td><button onclick="delete_purchase('138')">Kill</button></td>
Hope everything's clear, and you guys have some ideas what's wrong. If you need to know additional stuff, just ask and I'll see what I can do.
onclick="delete_purchase('138')"
calls a Javascript function called delete_purchase, which doesn't seem to exist in your code. You only have a PHP function with that name.
Since all PHP is executed on the server side, the HTML will be built long before the client ever sees the code and therefore you will never be able to call the delete_purchase PHP function from the client side.
The only two ways to get around this are:
- Create a delete_purchase JS function that then calls a PHP file through the use of AJAX.
- Don't call the onclick JS function at all and make the button a regular form submit that you then catch on the server side to delete the purchase. This however would involve a complete page refresh.
Your delete_purchase() function is defined in server-side which is not available in client side. You need to send a request to server and send the id, for example:
?action=delete&id=1
Then you can validate it on server side and call the function
<?php
if(isset($_GET['action']) && $_GET['action'] == 'delete'){
//do some staff
}
?>
you try to call a PHP-function directly from HTML (from browser)
this is impossible!
you may call it using 2 ways:
1) AJAX-call of php-script which will delete the purchase
2) redirect browser to php-script which will delete the purchase and then redirects you back

Update / SET to MySQL with PHP/AJAX within a loop

I need a small hint. Let's say there's a code like:
<?php
$test = mysql_query("SELECT * FROM test WHERE id='1'");
while($row = mysql_fetch_array($test))
{
echo "<tr>";
echo "<td>" . $row['platform_name'] . "</td>";
echo "<td>" . $row['scan_frequency'] . "</td>";
echo "<td><input id='freq' type='text' /></td>";
echo "<td><input id='date1' class='datepicker' type='text' /></td>";
echo "<td><input id='date2' class='datepicker' type='text' /></td>";
echo "<td><button id='save'>Save</button></td>";
echo "</tr>";
}
?>
The logic is that when I run a page, I get platform name and scan frequency fetched from table test as supposed to. Then I need to fill out three inputs (new frequency and dates, which are in format yy-mm-dd) and send it back (update/set) using 'save' button to table test. How can I do it with AJAX/PHP?
Thanks in advice!
Here's a small hint. ;-)
You link the button attribute onclick to a javascript function (e.g. fetch_new_data). Then you define the function fetch_new_data, which sends an ajax request to the server. The server processes the ajax request, selects the new data, packages it as xml or json and sends it back to the client. On return of the data, you lookup the position of the table, where you want to insert the new data and extend the table with a few new rows.
You can look for jquery, which simplifies several of these tasks on the client side. At the server side, for PHP and JSON, see PHP - JavaScript Object Notation and any tutorial or example covering PHP+JSON and/or PHP+AJAX.

Simple PHP button to send to next page

I have this:
echo "<form method='post' action='{$_SERVER['PHP_SELF']}?pagenum=$pagenum'>";
echo "<input type='hidden' value='";
echo htmlspecialchars($pesquisa);
echo "' name='pesquisa'><INPUT TYPE='submit' VALUE='Proxima pagina'></form>";
But I need only a button that when clicked for the first time, sends to page two. When it's clicked again on that page two, send do page three and so on. How do I do this in a simple way?
You should just use a link instead of a form. if it must look like a button, you can use an image.
echo "<img src=\"button.jpg\" />";
Assuming $pagenum starts at 0.
if($_POST['pesquisa'])
{
$pagenum++;
}
else
{
$pagenum = 0;
}
That way your first page view you wont have a $_POST['pagenum'] so it sets to 0. After that you will have one as your passing it along and then you increment the value for the next button press.
Here the button:
$pesquisa = 'label';
$pagenum = 100500;
echo "<input type='button' onclick='location.href=\"{$_SERVER['PHP_SELF']}?pagenum={$pagenum}\"'";
echo " value='" . htmlspecialchars($pesquisa) . "'/>";
All logic to change current page to next one showed in previous answers.

Categories