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

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.

Related

Php - echoing an html textbox, setting the textbox's value to a variable: returns only up to the first space of the string

So within my php code: I'm trying to auto generate and populate a form that will edit a database.
$aName = "Wayne Gretzky";
echo "<form>";
echo "<input type='text' value=".$aName.">";
echo "<input type='Submit'>";
echo "</form>";
But when the code executes it shows a textbox with the value of "Wayne" rather than "Wayne Gretzky"
Because i want the form to be auto generated, so it can adapt to whatever data I may pull form the database; How do i call the variable or the result of a query so that the full string will be displayed in the textbox?
You need to put quotes on the value attribute as well, otherwise the browser does it for you and then you get what you got.
echo "<input type='text' value='" . $aName . "'>";
You are going wrong with the quotes.
If you are using double quotes outside, use single quotes inside for the html tags.
The correct code is
<?php
$aName = "Wayne Gretzky";
echo "<form>";
echo "<input type='text' value='$aName'>";
echo "<input type='Submit'>";
echo "</form>";
?>

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.

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

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>";

How to parse all data from 1 table to another page?

I have printed the table get from database like below
And my code
print "<form id='form1' name='form1' method='post' action='http://localhost/live/index.php?m=sync&a=update'>";
while($db_field = mysql_fetch_assoc($result))
{
print "<table border=1 width=100%>";
print "<tr><td width=5%><input name='taskid' type='text' value=".$db_field['task_id']." readonly=readonly></td>";
/*print "<td width=10%>".$db_field['task_name']."</td>";*/
print "<td width=5%><input name='percent' type='text' value=".$db_field['task_percent_complete']." readonly=readonly></td>";
print "</table>";
}
print "<input name='Sync' type='submit' value='Sync' id='Sync' />";
print "</form>";
mysql_close($db_handle); /*.$db_handle */ /*<---to check the resource link and id*/
}
else{
print"Failed" ;//.$db_handle;
So what i want to know how to parsing all the datas from the database to another page like the action i want to send, because now i just can parsing 1 data in 1 table when i click the sync button like below is my parsing code in another page
The image below is the parsing code
I have no idea how to display all the data in new page...it is need to use loop? im newbie, big thanks
Edit based on comments below:
For starters, in the first code, move the print "<table border=1 width=100%>"; and print "</table>"; parts outside the while loop because the table is getting generated twice as two separate tables.
What's happening with the current code is that the second pair of fields taskid and percent are overwriting the first because the names are the same, so you only see the second pair of values in your screenshot. You need to make the input field names an array: put square brackets [] in the name so that taskid and percent are automatically arrays in $_POST. This is what the HTML source should look like in the form:
<input name='taskid[]' type='text' ...>
<input name='percent[]' type='text' ...>
(Or manually subscript them like taskid_0, percent_0 and taskid_1, percent_1; but then you have to decide when to stop looping or use variable variables.)
After that, in the target page where you are processing $_POST["taskid"], it will be an array which you can access as $_POST["taskid"][0], $_POST["percent"][0] and $_POST["taskid"][1], $_POST["percent"][1]. So loop through that when updating the database and generating your 2nd html:
print_r($_POST["taskid"]); // verify that this is an array
print_r($_POST["percent"]); // also an array
$i=0;
foreach ($_POST["taskid"] as $t) {
// not using $t, that's just for looping convenience
// do sql insert/update here, i'm just showing how you'd loop the array
print "<td><input type='text' name='".$_POST["taskid"][$i]."' readonly=readonly></td>";
print "<td><input type='text' name='".$_POST["percent"][$i]."' readonly=readonly></td>";
$i++;
}
Hope that helps.
Some pointers: 1. Don't put images of your code, just paste the code. 2. The generated HTML copy-pasted (browser -> view source) is more useful than an image of the page.
version 1:
1. If I understand it correctly, you want to show the form on one page and when the user clicks Sync (sumbit) you want it to go to another page which will process the form?
Use the target attribute of the <form> element (link). Like:
<form action="form_action.php" method="post">
Or,
2. If you want to process the form first (same page) and send the user to another page:
send an HTTP 302 re-direct + Location header.
You can also set the redirect in your HTML after processing the page using:
<meta http-equiv="Refresh" content="0; url=http://www.example.com/" />

Categories