I have a form with two different submit buttons. One is to delete the corresponding row in the MySQL, which is done on the same page, the other is to save the row to another database, which is done on a separate page. The delete action works fine, but I cannot figure out how to send the save form data to the other page without putting it in the "action" value. I've tried JavaScript, but haven't had much luck. It's a bit of a lengthy post, but I figure the more information I give, the easier it will be for a solution to be found.
Here's just the save submit button:
echo "<td><input type=\"submit\" name=\"save\" value=\"Save\" onclick=\"this.form.action='publishmod.php'\"></td>";
Here's the form code (main page):
echo "<form name=\"editmod\" method=\"post\">";
echo "<tr class='modlist'>";
echo "<td>".$row['id']."</td>";
echo "<td><div class=\"edit\" id=\"div_1\">".$row['title']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_2\">".$row['mod_url']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_3\">".$row['developer']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_4\">".$row['type']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_5\">".$v162."$nbsp".$v164."$nbsp".$v172."</div></td>";
echo "<td><div class=\"edit\" id=\"div_6\">".$row['title'].",$nbsp".$row['developer']."</div></td>";
echo "<td><input type=\"submit\" name=\"save\" value=\"Save\" onclick=\"this.form.action='publishmod.php'\"></td>";
echo "<td><input type=\"submit\" name=\"delete\" value=\"Delete\"></td>";
echo "</tr>";
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['mod_url'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['developer'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['type'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'), '" />';
echo "</form>";
}
Publish code (page that the save action is supposed to redirect to):
Variable sanitation omitted for Stack Overflow purposes.
$name = $_GET['title'];
$desc = "Installation tutorial for '.$name.'";
$url = ereg("^[A-Za-z_\-]+$", $name) + ".php";
$keywords = "'.$name.', '.$dev.'";
$type = $_GET['type'];
$link = $_GET['mod_url'];
$dev = $_GET['developer'];
$id = $_GET['id'];
// Query
$savequery = "INSERT INTO search (title, description, url, keywords, type, mod_url, developer, v162, v164, v172)
VALUES ('$name', '$desc', '$url', '$keywords', '$type', '$link', '$dev', '$v162', '$v164', '$v172')";
// Mod file creation
$file = ereg("^[A-Za-z_\-]+$", $name) + ".php";
$handle = fopen($file, 'w');
$data = '<?php
$title = "'. $name. '";
$keywords = "'. $name. ','. $developer. '";
$description = "How to install '. $name. ' for PC and Mac.";
include("templates/modheader.php");
include("templates/modfooter.php");
?>';
$save = $dbsave->query($savequery) or die(mysqli_error($dbsave));
// Run creation
echo $save;
fwrite($handle, $data);
print " mod file created!";
fclose($handle);
?>
Don't send it to another page. Use one page and branch with an if (or switch or whatever) statement.
e.g.
if (isset($_POST['save'])) {
include('save.php');
} elseif (isset($_POST['delete'])) {
include('delete.php');
} else {
# logic for when the page is arrived at without the form being submitted with a submit button
}
As an aside. A <form> may not be the parent element of a <tr>, and no element that may have a <td> as a child element may also have an <input> as a child element, you will find some browsers will move elements around to make them acceptable in a way that is going to break your form. Write valid HTML.
I Think you should change type of submit to button for both delete and save and the use following jquery code:
$("#savebutton_id").onclick(function(){
$("#formid").attr('action','Your save Page');
$("#formid").submit();
});
$("#deletebutton_id").onclick(function(){
$("#formid").attr('action','Your delete Page');
$("#formid").submit();
});
you can send data to other pages using hyperlink
eg:Shoes
we can get the category variable in the next page by using
$_GET['category'];
Related
[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples
I need to pass a javascript array, via POST, to a PHP file.
I've tried to semplify my original business trying to explain my troubles ...
This is my first PHP file, in which I declare a javascript array and I set each element to 1 value (not a great business I know, but it doesn't matter, it's only to explain ....)
<?php
echo '<form action="testPhp-2.php" method="POST" target="testPhp-2">';
echo '<script type="text/javascript">';
echo 'var arr_selections = [];';
echo 'for(i=0; i < 10; i++)';
echo ' {';
echo ' arr_selections[i] = 1';
echo ' }';
echo 'arr_selections_json = JSON.stringify(arr_selections);';
echo 'alert (arr_selections[2]);';
echo 'document.write("<br/>");';
echo ' ';
// echo 'document.write("<input type="hidden" />");';
echo 'document.write("<input type=\"hidden\" name=\"arr_selections_json\" value=\"arr_selections_json\" />");';
echo ' ';
echo '</script>';
echo ' <input type="submit" value="Controlla">';
echo ' </form>';
?>
.... and here you are the code of testPhp-2 file ...
<?php
if(isset($_POST['arr_selections_json']))
{
echo "OK, array exist !! ";
echo '</br>';
echo '</br>';
$arr_selections = json_decode($_POST['arr_selections_json'], true);
echo $arr_selections[0];
}
else {
echo "NO; array does not exist !! ";
echo '</br>';
echo '</br>';
}
?>
Now, if you try to execute the code you'll see the OK, array exist !! message but no array value is printed about the echo $arr_selections[0]; line of code in testPhp-2.php file.
Any suggestion will be appreciated! Thank you in advance!
Cesare
Problem is that you're setting the value of the input to the litteral string "arr_selections_json" instead of to the contents of that variable.
Change
echo 'document.write("... value=\"arr_selections_json\" />");';
To
echo 'document.write("... value=\""+arr_selections_json+"\" />");';
Testing out Wordpress on WAMP by creating a basic plugin.
Scenario:
Created an Admin panel with a form that just contains a text area and button. The form will be used to insert JavaScript code and this code will be placed in the header of all pages. I'm having issues trying to access the text area value within function post_tag. Code below:
<?php
add_action('admin_menu', 'setup_menu');
function setup_menu(){
add_menu_page( 'Tag Menu', 'Tag Menu', 'manage_options', 'tag-menu', 'html_form' );
}
function html_form(){
echo '<h1>JavaScript Tag</h1>';
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<p>';
echo 'Paste your code below: <br/>';
echo '<br/>';
echo '<textarea rows="10" cols="150" name="tag"></textarea>';
echo '</p>';
echo '<p><input type="submit" name="tag-submit" value="Submit"></p>';
echo '</form>';
if(isset($_POST['tag-submit'])){
$tag = esc_textarea(stripslashes($_POST["tag"]));
echo '<p>Your tag has been placed on all pages!</p>';
return $tag;
}
}
$value = html_form();
add_action('wp_head', 'post_tag');
function post_tag(){
global $value;
$output = $value;
echo $output;
}
?>
Can't seem to output the value in $tag to the header pages.Any help would be much appreciated.
If you don't have any reason to structure it the way you did, try this, which is cleaner
add_action('wp_head', 'post_tag');
function post_tag(){
$output = html_form();
echo $output;
}
I am trying to update records by php code. but having trouble in my code.
code is running without using functions (get40(),show()) but i want to use buttons to call these functions.
code is give below:
this is main code file:
<?php
$data;
$count=0;
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
$result;
$query;
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
function get40($off='0', $rcd='2')
{
global $db,$result,$query;
$query="SELECT sword, tword, reviewed from TempDictionary LIMIT $off,$rcd";
$result = $db->query($query)or trigger_error($db->error);
}
function show()
{
global $db,$result,$query;
echo "<form action='testSave.php' method='POST'>";
echo "<table border=1 >";
while($row = mysqli_fetch_array($result))
{
global $count;
$count+=1;
echo "<tr>";
echo "<td><input type='text' name='s[]' value=" . $row['sword'] . "></td>";
echo "<td><input type='text' name='t[]' value=" . $row['tword'] . "></td>";
echo "<td><input type='text' name='r[]' size='1' value=" .$row['reviewed'] . "></td>";
echo "</tr>";
}
echo "</table>";
echo "<input type='text' name='no' size='2' value=" .$count. ">";
echo "<input type='submit' value='Save'>";
echo "</form>";
}
//get40(1,2);
//show();
mysqli_close($db);
?>
<script type="text/javascript">
function get()
{
<?php
get40(0,3);
show();
?>
}
</script>
<form action="" method="POST">
<input type=button name=btnGet value=Get onclick="get()">
</form>
and savetest.php file is:
<?php
$no=$_POST['no'];
$i=0;
$s=$_POST['s'];
$t=$_POST['t'];
$r=$_POST['r'];
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
// display
foreach ($s as $key=>$value)
{
print "$key = $value $t[$key] $r[$key]";
echo '<br>';
}
// save to DB
foreach ($s as $key=>$value)
{
// $query="UPDATE TempDictionary set sword=".$value.",tword=".$t[$key].",reviewed=".$r[$key]."
// WHERE sword=".$value;
$query="UPDATE TempDictionary set sword='$value',tword='$t[$key]',reviewed='$r[$key]'
WHERE sword='$value'";
$result = $db->query($query)or trigger_error($db->error);
}
mysqli_close($db);
?>
the problem is while i click button it does not works.
AFAIK you are trying to run PHP code with Javascript code.
Use Jquery/Ajax to solve your problem. You can Google for that or look at stackoverflow.
Step 1: Learn how a click on a button can run PHP
Run php function inside jQuery click
Step 2: Learn how to use data from a database and populate a form with it:
ajax call to populate form fields from database query when select value changes
That's the first step in solving your problem. (sorry it's no copy/paste solution, just a pointer in the right direction)
How can I collect the data on the row from the table that I select and use it in the result?
Here is the javascript I am using to show the data entry screen, once the function has been called by selecting the row. Now I just need to design a form in PHP that will include (1) some of the data from the row selected and (2) some new data that will be collected.
Here is the Javascript to select the row and call the data entry form
$(document).ready(function () {
$("tr").live('click',function(){
$.post('data_entry_form.php', function(data) {
$('#section2').html(data);
});
});
});
Here is the PHP Script
<?php
require_once "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$result = $dbh->query("SELECT aif_id, fee_source_id, company_name_per_sedar, document_filing_date FROM a_aif ORDER BY aif_id DESC");
$result->setFetchMode(PDO::FETCH_ASSOC);
echo "<table id=\"all_aifs\">";
echo "<tr>";
echo "<th><b>Document ID</b></th>";
echo "<th><b>Pubco Name</b></th>";
echo "<th><b>Filing Date</b></th>";
echo "<th><b>PDF</b></th>";
echo "</tr>";
foreach($result as $index => $row) {
echo "<tr>";
echo "<td>$row[fee_source_id]</td>";
echo "<td>$row[company_name_per_sedar]</td>";
echo "<td>$row[document_filing_date]</td>";
echo "<td>Placeholder</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
$dbh = NULL;
?>
The "Correct" answer to this problem is NOT to read from the DOM. Never a good idea. I suggest you pass the record id to the ajax call and have the ajax call return an already-populated form.
//PHP
//place the data attribute in the tr
echo "<tr data-recordId='".$row['id']."'>";
//JS
$(document).ready(function () {
$("tr").live('click',function(){
//Get the ID from the row clicked
var id = $(this).data('recordId');
//short-hand
$('#section2').load('data_entry_form.php?id='+id);
});
});
Then your ajax page would just read $_REQUEST['id'] to get the id of the form being edited.
//Ajax side PHP
$id = (int)$_REQUEST['id'];
//Fetch data and use it to pre-populate form item
You would pre-populate your inputs like this
<input type="text" value="<?php echo $row['value']; ?>" />
or
echo '<input type="text" value="'.$row['value'].'" />';
NOTE: If your values contain quotes, you will want to replace them with the code "
echo '<input type="text" value="'.str_replace('"', '"', $row['value']).'" />';
Within the event handler, this and $(this) refer to your selected row:
$("tr").live('click',function(){
// this.cells[1] is the cell that contains Pubco Name
// You can also use $(this).children("td")[1]
...
});