PHP echo button onclick function - php

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

Related

Python Post - PHP Request

I'm trying to create a php page which takes data from my python code and show them as a table.
r = requests.post('http://localhost/index.php', data={"iv":a,"ven":b,"hem":c,"card":d,"ecg":e})
print(r.text)
In above code, I post data then print it to check if everything is okay. My r.text output
<table><tr><th>IV Pump</th><th>Ventilator</th> <th>Heart Monitor</th><th>Cardiac Machine</th><th>Echocardiogram</th></tr><tr><td>off</td><td>on</td><td>off</td><td>off</td><td>off</td></tr></table>
which seems fine because I can get a,b,c,d,e (on/off basically). However when I open my index.php I cannot see those "on"s and "off"s. I am newbie on server things, PHP, etc. My mistake is probably very dummy. Should I store post data in somewhere? My index.php:
<?php
$iv=$_REQUEST['iv'];
$ven=$_REQUEST['ven'];
$hem=$_REQUEST['hem'];
$card=$_REQUEST['card'];
$ecg=$_REQUEST['ecg'];
echo '<table>';
echo '<tr>';
echo '<th>IV Pump</th>';
echo '<th>Ventilator</th> ';
echo '<th>Heart Monitor</th>';
echo '<th>Cardiac Machine</th>';
echo '<th>Echocardiogram</th>';
echo '</tr>';
echo '<tr>';
echo '<td>';
echo $iv;
echo '</td>';
echo '<td>';
echo $ven;
echo '</td>';
echo '<td>';
echo $hem;
echo '</td>';
echo '<td>';
echo $card;
echo '</td>';
echo '<td>';
echo $ecg;
echo '</td>';
echo '</tr>';
echo '</table>';
?>
My r.text is ok, but in web page I cannot see request data, the table cells are empty. What is the difference? As I know r.text returns the page content, so index.php must be wrong, I guess it is about storing the data.
When you make a HTTP request to a server, that server will return the rendered webpage to that user. This means requests will get back the correct response.
However when you open a web page in a browser, you are making a new request to that server which will render the page again. Since you aren't passing the $_REQUEST['iv'] etc. values this time, the table will appear blank.
You have a few options depending on what you want to do:
Store the information in a database
You can store that information in a database. Some databases for example are SQLite3 or MySQL. I've omitted the exact database insertion/reading implementation since it differs between which database you pick.
A simple method might be:
<?php
$iv=$_REQUEST['iv'];
// insert other variables etc.
// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] === "POST") {
// INSERT DATA INTO YOUR DATABASE AS APPROPRIATE
// You can also echo back the table if you want
// Else it might be a GET request
} elseif ($_SERVER['REQUEST_METHOD'] === "GET") {
// READ DATA FROM DATABASE
// echo table with the data from the database
}
?>
Use URL parameters
Alternatively you can use URL parameters to encode your data like so:
# In your Python code
# Notice that requests.post changed to requests.get and data changed to params
r = requests.get('http://localhost/index.php', params={"iv":a,"ven":b,"hem":c,"card":d,"ecg":e})
# You can now access this specific URL to see the populated table
# The URL will look something like http://localhost/index.php?iv=a&ven=b/
print(r.url)
Note that this requires you to visit that specific URL and doesn't work if you visit the base URL (i.e. https://localhost/index.php) without the parameters.

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 Refresh button onclick

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.

HTML Numerical Input Bug: infinite loop when jquery.change event called

I created an HTML table with PHP as follows:
$i = 1;
while($row = mysql_fetch_array($result)){
Print "<tr>";
Print "<td><input id='prEff[$i]' type='number' step='0.01' min='0.01' max='0.99' value='.85' </td>";
Print "<td>".$row['ErdEfficiency'] . "</td>";
Print "<td>".$row['TheoreticalSEC'] . "</td></tr>";
$i++;
}
The input cell has a jquery.change function that is called when the number is changed within the range. During debugging, clicking the up or down button once (in chrome) causes the input to run through all values until the upper or lower limit is reached. So the function is called, but only after the whole range of values is run through.
If the page is refreshed without debugging, the jquery is called, but the button sticks since it is experiencing the bug as described.
Here is the simple jquery function:
$('[id^="prEff["]').change(function (){
var test = this;
alert("hi");
});
Its been a difficult bug to track, and I'm not sure what is causing it. It has occurred with an onchange attribute in the input, as well as a javascript eventListener, and jquery change. It may be the way the PHP is printing the input but I've tried a couple different ways without success.
It seems like you have an unclosed <input> tag in your code. Make sure you close it and you should be fine:
Print "<td><input id='prEff[$i]' type='number' step='0.01' min='0.01' max='0.99' value='.85' /> </td>";

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.

Categories