Using AJAX and PHP, created form submits wrong the wrong value - php

***UPDATE
I've done away with table elements as suggested and am using CSS. I've also seen that there's a "form" attribute, I've tried that, too. When I submit, it is still acting as it did before - sending the wrong value because it was sending the whole table. I've updated the below with the updated HTML output and the PHP code. It looks correct, this is my latest attempt. What am I missing?
I am using PHP to create a form for each row of data. I call to PHP via AJAX. The form builds correctly. Each row correctly lists its values and is in its own form. In this example, there are three rows, thus three forms. When I submit a username on the first row, the ID being sent is from the third row. Not sure what is going on.
AJAX call to PHP FORM - Home Page
<script>
window.onload = function signupForm() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupForm").innerHTML = this.responseText;
}
}
xmlHttp.open("GET", "ajaxInput.php", true);
xmlHttp.send();
}
</script>
PHP FORM - signupForm.php
<?php
$con=mysqli_connect("localhost","xxxxxx","xxxxxxx","xxxxxxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT id, DATE_FORMAT(startTime, '%b-%d-%Y') as eventDate, endTime FROM events
WHERE now() < endTime");
echo "
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class='table'>
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>";
while($row = mysqli_fetch_array($result))
{
//echo "<form action='ajaxSignup.php' method='post'>";
echo "<div>";
echo "<div>" . $row['id'] . "</div>";
echo "<div>" . $row['eventDate'] . "</div>";
echo "<div><form id='form" .$row['id']. "' method='post'><input class='formSignup' type='text' name='pi_username' id='pi_username' maxlength='20' placeholder='#username' form='form" .$row['id']. "'></div>";
echo "<div><input class='formSignup' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
<input name='submit". $row['id'] . "' type='submit' value='Sign up!' onclick='signup(); return false;'></form></div>";
echo "</div>";
}
//echo "</div>";
echo "</div>";
mysqli_close($con);
?>
The table draws correctly. I've put form tag in various places as well. Below, I'm using the form attribute in the input tags. The table is being drawn with CSS instead of the table elements.
<html>
<head></head>
<body>
<p>Something here</p>
<div id="signupForm">
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class="table">
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>
<div>
<div>11</div>
<div>Feb-25-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form11"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="11" form="form11">
<form id="form11" method="post"><input name="submit11" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>12</div>
<div>Feb-26-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form12"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="12" form="form12">
<form id="form12" method="post"><input name="submit12" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>13</div>
<div>Feb-27-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form13"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="13" form="form13">
<form id="form13" method="post"><input name="submit13" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
</div>
</div>
As can be seen in the PHP, each row is its own form. But looking at the Elements in developer tools, the form is closing early. I think this is related to the issue.
Elements
When I enter a username on row one (top row), the username doesn't seem to make it and the ID that does make it is 13 instead of 11.
AJAX Script to process Submit button onclick (Home page)...
<script>
function signup() {
var elements = document.getElementsByClassName("formSignup");
var formData = new FormData();
for(var i=0; i<elements.length; i++) {
formData.append(elements[i].name, elements[i].value);
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupSuccess").innerHTML = this.responseText;
}
}
xmlHttp.open("post", "ajaxSignup.php");
xmlHttp.send(formData);
}
</script>
PHP code on signup page. I have some echos early on that show the id is 13, not 11 and no username is present.
<?php
$pi_username = $high_score = $attempts = $event_id = "";
echo $event_id;
echo $pi_username;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$pi_username = test_input($_POST["pi_username"]);
$event_id = test_input($_POST["event_id"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo $event_id;
echo $pi_username;
if($_SERVER["REQUEST_METHOD"] == "POST") {
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "xxxxxxx", "xxxxxxx", "xxxxxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//check if user has already signed up for event
$alreadySignedUp = mysqli_query($link, "SELECT count(*) AS total FROM signup WHERE event_id = $event_id AND pi_username = '$pi_username'");
while ($worm = mysqli_fetch_array($alreadySignedUp)){
//echo $bird['total'];
if($worm['total'] >= 1 ){
echo "You have already signed up for this event.";
echo $event_id;
echo $pi_username;
echo $worm['total'];
mysqli_close($link);
return;
}
}
// Attempt insert query execution
$sql = "INSERT INTO signup (event_id, pi_username) VALUES ('$event_id', '$pi_username')";
if(mysqli_query($link, $sql)){
echo "You have been successfully added to event ".$event_id."!";
mysqli_close($link);
return;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
else {
echo "Don't forget to submit your high scores before you leave!";
}
?>
Where am I going wrong?

The signup() function was looking for elements with the same class (formSignup). All input fields had the same class name and were all being sent to the signup() function. I've updated the class name to be unique for each row. Now only a single row is being sent. The signup() function was updated to:
window.onload = function signupForm(getClass) {
var xmlHttp = new XMLHttpRequest(getClass);
Example of an input field with a unique class name:
<input class='formSignup" .$row['id']. "' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
Removed table elements and created a CSS-styled 'table' as suggested. All working now. Question updated with CSS-Styled table.

Related

Insert value of single form called multiple times using ajax call to mysql in php

I am trying to insert single form value called multiple times using ajax call to mysql in php with submit all button . I have store all the forms data to localStorage. But when I am trying to insert all the values to mysql one form value is inserting and other form values is taking null value.
**loadquestions1.php**
<form method="post">
<table>
<tr>
<td>
<?php echo "<h5>Question: ".$question_no ."</h5><h5> ".$question_title ."</h5>"; ?>
</td>
</tr>
</table>
<div class="center">
<textarea placeholder="Write your answer here..." class="outer persisted-text" name="pt<?php echo $question_no; ?>" id="persisted-text" onchange="changeBack();" rows="10" cols="100"></textarea>
<span><input type="hidden" name="question_no<?php echo $question_no; ?>" value="<?php echo $question_no; ?>" /></span>
<span><input type="hidden" name="question_title<?php echo $question_no; ?>" value="<?php echo $question_title; ?>" /></span>
</div>
<button class="btn btn-success" name="save">Save</button>
<?php } ?>
</form>
function load_questions1(questionno)
{
document.getElementById("current_que").innerHTML=questionno;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText=="over")
{
window.location="result.php";
alert("hello");
}
else
{
document.getElementById("load_questions1").innerHTML=xmlhttp.responseText;
load_total_que();
var supported = '',
unsupported = 'Oh no! Your browser does not support localStorage.';
if (window.localStorage) {
$('.persisted-text').keyup(function () {
localStorage.setItem(this.name+questionno, this.value);
}).val(function () {
return localStorage.getItem(this.name+questionno) || supported
})
} else {
$('.persisted-text').val(unsupported);
}
}
}
};
xmlhttp.open("GET", "forajax/load_questions1.php?questionno="+ questionno, true);
xmlhttp.send(null);
}
**config.php**
if (isset($_POST['save'])) {
$size = sizeof($_POST);
$number = $size/3;
$query = "SELECT * FROM add_question where online_exam_title='$_SESSION[add_exam]'";
$data = mysqli_query($conn, $query);
$count=mysqli_num_rows($data);
for($i=1;$i<$count;$i++) {
$index1 = 'pt'.$i;
$pt[$i] = $_POST[$index1];
$index2 = 'question_no'.$i;
$question_no[$i] = $_POST[$index2];
$index3 = 'question_title'.$i;
$question_title[$i] = $_POST[$index3];
//$question_no = $_POST['question_no'];
$sql="INSERT INTO subjective_answer (placeholder, exam_type, username, question_no, question_title) VALUES ('$pt[$i]', '$_SESSION[add_exam]', '$_SESSION[username]', '$question_no[$i]', '$question_title[$i]')";
$result=mysqli_query($conn,$sql);
}
if($result)
{
echo "record inserted";
}
}

Post Javascript Form into mysql

I'm working on an invoicing system. I'm using javascript to add line items as needed however the added line items are not posting when I click submit. I'm thinking it is probably an issue with div somewhere but I cannot seem to find it or get it to work. I'm posting my code for help. Thanks.
Here is my form.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
$result = mysql_query("SELECT company, first, last FROM customer") or die (mysql_error());
?>
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement('div');
newdiv.innerHTML = " Entry " + (++counter) + " <br /><table><tr><td>Item: <select name='item[]'>" + xmlhttp.responseText + "</select></td><td>Qty: <input name='quantity[]' type='text' size='5' /></td></tr></table><br />";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "dropdownquery.php", false);
xmlhttp.send();
}
</script>
<form id="createInvoice" method="post" action="docreateinvoice.php">
<table>
<tr><td>Customer</td><td><select name="company">
<?php while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['company']."\">".$row['company']." (".$row['first']." ".$row['last'].")</option>";
}
?>
</select></td></tr>
</table>
</div>
</div>
<div id="container">
<div class="content">
<div id="dynamicInput">
Entry 1<br /><table><tr><td>Item: <select name="item[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select></td><td>Qty: <input name="quantity[]" type="text" size="5" /></td></tr></table><br />
</div>
<br /><input type="button" value="Add Line Item" onClick="addInput('dynamicInput');">
</div>
</div>
<div id="container">
<div class="content">
<input type="submit" name="submit" value="Create Invoice" />
</form>
<?php
include $_SERVER['DOCUMENT_ROOT']."/includes/footer.php";
?>
This next piece of code is dropdownquery.php. This is what gets the dropdown box data in the javascript. Big thanks to #NickSlash for figuring this out in the javascript.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
And finally, this is my docreateinvoice.php which I post to.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$company = mysql_real_escape_string($_POST['company']);
foreach($_POST['item'] as $i => $item)
{
$item = mysql_real_escape_string($item);
$quantity = mysql_real_escape_string($_POST['quantity'][$i]);
//mysql_query("INSERT INTO invoice (company, item, quantity) VALUES ('$company', '".$item."', '".$quantity."') ") or die(mysql_error());
print_r ($company);
print_r ($item);
print_r ($quantity);
}
//echo "<br><font color=\"green\"><b>Invoice added</b></font>";
?>
You might notice in the form that the first entry is not javascript. This does indeed post, just not any additional line items generated from the javascript function.
Thanks for any help.
As I had said in the comments, it seems having divs for display formatting purposes has a negative effect when used within forms utilizing javascript.

Php Ajax form submit in colorbox

I have a form with some php to validate and insert in the database on submit and the form opens in colorbox.
So far so good. What I'm trying to do is to close colorbox and refresh a div on success.
I guess I need to pass a response to ajax from php if everything OK, close the colorbox with something like setTimeout($.fn.colorbox.close,1000); and refresh the div, but I'm stuck because I'm new in ajax.
I'll appreciate any help here.
Here is my ajax:
jQuery(function(){
jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
cbox_submit();
}});
});
function cbox_submit()
{
jQuery("#pre-process").submit(function(){
jQuery.post(
jQuery(this).attr('action'),
jQuery(this).serialize(),
function(data){
jQuery().colorbox({html: data, onComplete: function(){
cbox_submit();
}});
}
);
return false;
});
}
form php code:
<?php
error_reporting(-1);
include "conf/config.php";
if(isset($_REQUEST['rid'])){$rid=safe($_REQUEST['rid']);}
if(isset($_REQUEST['pid'])){$pid=safe($_REQUEST['pid']);}
$msg = '';
if (!$_SESSION['rest_id']) $_SESSION['rest_id']=$rid; //change to redirect
$session_id=session_id();
if(isset($_REQUEST['submit'])){
if(isset($_POST['opta'])){
$opta=safe($_POST['opta']);
$extraso = implode(',',array_values( array_filter($_POST['opta']) ));
}
if (array_search("", $_POST['opt']) !== false)
{
$msg = "Please select all accessories!";
}else{
$extrasm = implode(',',array_values( array_filter($_POST['opt']) ));
if ($_POST['opt'] && isset($_POST['opta'])) {$extras= $extrasm .",". $extraso;}
if ($_POST['opt'] && !isset($_POST['opta'])) {$extras= $extrasm;}
if (!$_POST['opt'] && isset($_POST['opta'])) {$extras= $extraso;}
$sql['session_id'] = $session_id;
$sql['rest_id'] = $_POST['rid'];
$sql['prod_id'] = $_POST['pid'];
$sql['extras'] = $extras;
$sql['added_date'] = Date("Y-m-d H:i:s");
$newId=insert_sql("cart",$sql);
}
}
?>
<form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div style="background-color:#FFF; padding:20px;">
<?=$msg;?>
<?php
$name = getSqlField("SELECT name FROM products WHERE resid=".$_SESSION['rest_id']." and id=".$pid."","name");
echo "<div style='color:#fff; background-color:#F00;padding:10px;' align='center'><h2>".$name."</h2></div><div style='background-color:#FFF; padding: 20px 70px 30px 70px; '>Please select accessories.<br><br>";
$getRss = mysql_query("SELECT * FROM optional_groups_product where prodid=".$pid." order by id asc");
while ($rsrw = #mysql_fetch_array($getRss)) {
$goptionals = getSqlField("SELECT goptionals FROM optionals_groups WHERE resid=".$_SESSION['rest_id']." and id=".$rsrw['goptid']."","goptionals");
$goptionals=explode(', ',($goptionals));
echo "<select name='opt[]' id='opt[]' style='width:220px;'>";
echo "<option value='' >Select Options</option>";
foreach($goptionals as $v)
{
$vname = mysql_query("SELECT * FROM optionals where id=".$v." LIMIT 0,1");
while ($rsgb = #mysql_fetch_array($vname)) {
$aa=$rsgb['optional'];
}
echo "<option value=".$v." >".$aa."</option>";
}
echo "</select>(required)<br>";
//}
}
$getRss = mysql_query("SELECT * FROM optional_product where prodid=".$pid."");
?>
<br><br>
<table border="0" cellpadding="0" cellspacing="0" >
<tr>
<td bgcolor="#EAFFEC">
<div style="width:440px; ">
<?php
while ($rssp = #mysql_fetch_array($getRss)) {
$optional=getSqlField("SELECT optional FROM optionals WHERE id=".$rssp['optid']."","optional");
$price=getSqlField("SELECT price FROM optionals WHERE id=".$rssp['optid']."","price");
?>
<div style="width:180px;background-color:#EAFFEC; float:left;padding:10px;""><input type="checkbox" name="opta[]" id="opta[]" value="<?=$rssp['optid']?>" /> <i><?=$optional?> [<?=CURRENCY?><?=$price?> ]</i> </div>
<?php } ?>
</div>
</td>
</tr></table>
<input type="hidden" name="rid" value="<?=$rid?>" />
<input type="hidden" name="pid" value="<?=$pid?>"/>
</div><input type="hidden" name="submit" /><input id='submit' class="CSSButton" style="width:120px; float:right;" name='submit' type='submit' value=' Continue ' /><br />
<br /><br />
</div>
</form>
I don't know colobox, but if I understand well what you are trying to do,
I would say your javascript should more look like this
function cbox_submit()
{
jQuery("#pre-process").submit(function(e) {
e.preventDefault(); // prevents the form to reload the page
jQuery.post(
jQuery(this).attr('action')
, jQuery(this).serialize()
, function(data) {
if (data['ok']) { // ok variable received in json
jQuery('#my_colorbox').colorbox.close(); // close the box
}
}
);
return false;
});
}
jQuery(function() {
jQuery('#my_colorbox').colorbox({
maxWidth: '75%'
, onComplete: cbox_submit // Bind the submit event when colorbox is loaded
});
});
You should separate at least your php script that does the post part.
And this php (called with jQuery(this).attr('action')) should return a json ok variable if successfull. Example:
<?php
# ... post part ...
# if success
ob_clean();
header('Content-type: application/json');
echo json_encode(array('ok' => true));
?>

Table with multiple rows and deletions

Ok, so I have an input function that allows me to add items to a database, and displays this as a table. As part of the table, I am trying to add delete and edit buttons.
I am trying to figure out the best way to add delete and edit functionality. I'm thinking for editing, I will have to use Javascript. However, for deletions, I am not sure if I should use PHP, Javascript, or some combination therein.
So far, here's my code:
<html>
<header><title>Generic Web App</title></header>
<body>
<form action="addculture.php" method="POST">
<span><input type="text" size="3" name="id" />
<input type="text" name="culture" />
<input type="submit" value="add" /></span>
</form>
<?php
/* VARIABLE NAMES
*
* $con = MySQL Connection
* $rescult = MySQL Culture Query
* $cultrow = MySQL Culture Query Rows
*/
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("generic");
$rescult = mysql_query("SELECT * FROM culture order by cult_id");
if (!$rescult) {
die('Invalid query: ' . mysql());
}
echo "<table><tbody><tr><th>ID</th><th>Culture Name</th>";
while ($cultrow = mysql_fetch_array($rescult)) {
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '<td><button type="button">Del</button></td>' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
echo "</tbody></table>";
?>
</body>
</html>
Currently I have del and edit set as buttons, just for visible reference. What's the best way to deal with a situation where you have multiple buttons like this?
I apologize if my answer is too broad but so is your question.
Both, Editing and Deleting should use a combination of JavaScript and PHP code; for example when the user clicks on the delete button you can send an Ajax request to the server, have the record deleted from the DB and upon successful return from the server-side call, use JavaScript to visually delete the record from the markup. The same would apply to the Edit functionality.
Here's a nice intro on how to perform ajax requests using JQuery:
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
The first think I would do is add a value and name to the buttons:
<button type="button" value="$cultrow[0]" name="Delete">Delete</button>
<button type="button" value="$cultrow[0]" name="Edit">Edit</button>
The value of the button is going to be the id of the row, and the name is going to be the action that button will do. The next thing I would do is bind those buttons to actions with jquery.
$('button').click(function(){
//determine whether is delete or edit
//Once you determine what action use the id to make the request
//if delete prompt to verify if yes, ajax the server with a delete request
//if edit redirect user to a page that will handle editing of the row edit.php?id=5
});
For deleting row
1 - Make new page name it del_culture.php
session_start();
$id = base64_decode($_GET['id']);
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$q = mysql_query("DELETE FROM culture WHERE cult_id = '".$id."' ");
if($q):
echo "Done";
else:
echo "ERROR";
endif;
2 - in your page add the following code
while ($cultrow = mysql_fetch_array($rescult))
{
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '
<td>Delete' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
For Editing a row add link for edit like i did to page name it edit_cult.php
and do the same as you input put the values from database and then update it
This is your javascript
function performAction(action) {
// ASSIGN THE ACTION
var action = action;
// UPDATE THE HIDDEN FIELD
document.getElementById("action").value = action;
switch(action) {
case "delete":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 0) {
if(confirm("Are you sure you want to delete the selected records?")) {
// SUBMIT THE FORM
document.adminform.submit();
}
}
else {
alert("You didn't select any records");
}
break;
case "edit":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 1) {
alert("You can only edit one record at a time");
}
else if(total == 0) {
alert("You didn't select a record");
}
else {
document.adminform.submit();
}
break;
default:
}
}
and in your form you need something like this
<form id="adminform" name="adminform" action="<?php $_SERVER['REQUEST_URI'] ?>" method="post">
<img src="/admin/images/news.png" alt="news" title="news" />
<input type="button" class="back" id="backbutton" title="go back" onclick="performAction('back');" />
<input type="button" class="delete" id="deletebutton" title="delete" onclick="performAction('delete');" />
<input type="button" class="archive" id="archivebutton" title="archive" onclick="performAction('archive');" />
<input type="button" class="edit" id="editbutton" title="edit" onclick="performAction('edit');" />
<input type="button" class="add" id="addbutton" title="add" onclick="performAction('add');" />
<table id="admintable">
<tr><th class='tdleft'>
<?php
if($err !=0) {
echo"<input type='checkbox' name='all' onclick='checkAll(adminform);' />";
}
echo "</th><th class='tdright'>Title</th></tr>";
$z = 0;
// Iterate through the results
while ($row = $result->fetch()) {
if($z % 2==0) {
//this means if there is a remainder
echo "<tr class='yellow'>\n";
$z++;
} else {
//if there isn't a remainder we will do the else
echo "<tr class='white'>\n";
$z++;
}
echo "<td class='tdleft'><input type='checkbox' name='id[]' value='{$row['id']}' /></td><td class='tdright'><a href='/admin/news/edit-news-".$row['id']."'>{$row['title']}</a></td></tr>";
}
?>
</table>
<input type="hidden" id="action" name="action" value="" />
and at the top of your page before the html put
if($_POST && array_key_exists("action", $_POST)){
// CARRY OUT RELAVANT ACTION
switch($_POST['action']) {
case "edit":
foreach($_POST['id'] as $value) {
$id = $value;
}
header('Location: /admin/blogs/edit-blog-'.$id);
break;
case "delete":
if(!empty($_POST['id'])) {
//do your delete here
}
break;
}
}
}

Using PHP to query db, fetch results via AJAX as variable, query db again using values of initial variable

It's all in the question really :)
It's clearer when I put it in bullet points what I want to do, so here it goes:
I have two forms on a page, a search form, and an 'edit profile' form. Both are in working order, individually.
The edit profile form paginates through the rows of my MySQL tbl, allowing my to edit the values for each column. Currently set up to include all rows (i.e. all stored profiles).
the search form takes any of 17 different search variables and searches that same table to find a profile, or a group of profiles.
I want to be able to enter a search term (e.g. Name: 'Bob'), query the tbl as I am doing, but use AJAX to return the unique ID's of the results as an an array stored within a variable. I then want to be able to asynchronously feed that variable to my edit profile form query (the search form would have a submit button...) so I can now page through all the rows in my table (e.g. where the Name includes 'Bob'), and only those rows.
Is the above possible with the languages in question? Can anyone help me piece them together?
I'm at an intermediate-ish stage with PHP and MySQL, but am an absolute novice with AJAX. I've only ever used it to display a text string in a defined area - as seen in demos everywhere :) Therefore, treating me like a five-year-old is greatly appreciated!
Here are my current search query, and the edit-profile form, if they help at all:
The Edit Profile form:
//pagination base
if (isset($_GET['page'])) { $page = $_GET['page']; }
else { $page = 1; }
$max_results = 1;
$from = (($page * $max_results) - $max_results);
$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM profiles"),0);
$total_pages = ceil($total_results / $max_results);
echo '<span id="pagination">' . 'Record ' . $page . ' of ' . $total_results . ' Records Returned. ';
if($total_results > $max_results)
{
if($page > 1)
{ $prev = ($page - 1);
echo "<input type='submit' value='<<' />";
}
if($page == 1)
{ echo "<input type='submit' value='<<' />"; }
if($page < $total_pages)
{ $next = ($page + 1);
echo "<input type='submit' value='>>' />";
}
if($page == $total_pages)
{ echo "<input type='submit' value='>>' />";
}
}
echo '</span></p>';
?>
// the query, currently selecting all but which I would have include a WHERE clause (WHERE ProfileID = $profileid...)
<?php
$sql = ("SELECT * FROM profiles
ORDER BY ProfileID
LIMIT $from, $max_results");
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
$profile = $row['ProfileID'];
?>
<form id="profile-form" action="profile-engine.php" method="post">
<input type="hidden" name="formid" value="edit-profile">
<input type="hidden" name="thisprofile" value="<?php echo $profile; ?>">
<table id="profile-detail" class="profile-form">
<tr>
<td>
<label for="profile-name">Name:</label>
<?php
$nameresult = mysql_query("SELECT ProfileName
FROM profiles
WHERE ProfileID = '$profile'");
$row = mysql_fetch_array($nameresult);
?>
<input type="text" class="text" name="profile-name" id="profile-name" value="<?php echo $row['ProfileName']; ?>" />
</td>
//goes on in this vein for another 16 inputs :)
The Search Query:
//connection established
$query = "SELECT * FROM profiles";
$postParameters = array("name","height","gender","class","death","appro","born","tobiano","modifier","adult","birth","sire","dam","breeder","owner","breed","location");
$whereClause = " WHERE 1 = 1";
foreach ($postParameters as $param) {
if (isset($_POST[$param]) && !empty($_POST[$param])) {
switch ($param) {
case "name":
$whereClause .= " AND ProfileName LIKE '%".$_POST[$param]."%' ";
break;
case "height":
$whereClause .= " AND ProfileHeight='".$_POST[$param]."' ";
break;
case "gender":
$whereClause .= " AND ProfileGenderID='".$_POST[$param]."' ";
break;
//more cases....
}
}
}
$query .= $whereClause;
$result = mysql_query("$query");
$values = array();
while ($row = mysql_fetch_array($result)) {
$values[] = $row['ProfileID'];
}
/*
//just me checking that it worked...
foreach( $values as $value => $id){
echo "$id <br />";
}
*/
mysql_close($con);
So, there you have it! Thanks in advance for any help!
what about:
search copies search term to local variable, service returns an array of results that you hold, and then pagination uses JS to drop in the values into the appropriate fields. If you change one and save, it submits the edits, including the original search term, which is used to re-query the service, and returns the updated array...repeat as necessary
here's some sample code (here there's just two search fields, I know you need more):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var query = new Object();
var resp;
var i;
function next(on){
i=on+1;
if(i==resp.results.length){i--;}
fillForm(i);
}
function prior(on){
i=on-1;
if(i<0){i++;}
fillForm(i);
}
function fillForm(i){
document.getElementById("paginate").innerHTML='<button onclick="prior('+i+')"><</button>'+(i+1)+' of '+resp.results.length+'<button onclick="next('+i+')">></button>';
document.getElementById("name").value=resp.results[i].name;
document.getElementById("height").value=resp.results[i].height;
document.getElementById("gender").value=resp.results[i].gender;
document.getElementById("class").value=resp.results[i].class;
document.getElementById("death").value=resp.results[i].death;
document.getElementById("appro").value=resp.results[i].appro;
document.getElementById("born").value=resp.results[i].born;
document.getElementById("tobiano").value=resp.results[i].tobiano;
document.getElementById("modifier").value=resp.results[i].modifier;
document.getElementById("adult").value=resp.results[i].adult;
document.getElementById("birth").value=resp.results[i].birth;
document.getElementById("sire").value=resp.results[i].sire;
document.getElementById("dam").value=resp.results[i].dam;
document.getElementById("breeder").value=resp.results[i].breeder;
document.getElementById("owner").value=resp.results[i].owner;
document.getElementById("breed").value=resp.results[i].breed;
document.getElementById("location").value=resp.results[i].location;
document.getElementById("id").value=resp.results[i].id;
document.getElementById("saveButton").innerHTML='<button onclick="save()">Save</button>';
}
function getData(){
query.name=document.getElementById('query_name').value;
query.gender=document.getElementById('query_gender').value;
var variables='';
variables+='name='+query.name;
variables+='&gender='+query.gender;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
resp = JSON.parse(xmlhttp.responseText);
fillForm(0);
}
}
xmlhttp.open("GET","searchNav.php?"+variables,true);
xmlhttp.send();
}
function save(){
var saving="";
saving+='?q='+query;
saving+='&name='+document.getElementById('name').value;
saving+='&height='+document.getElementById('height').value;
saving+='&gender='+document.getElementById('gender').value;
saving+='&class='+document.getElementById('class').value;
saving+='&death='+document.getElementById('death').value;
saving+='&appro='+document.getElementById('appro').value;
saving+='&born='+document.getElementById('born').value;
saving+='&tobiano='+document.getElementById('tobiano').value;
saving+='&modifier='+document.getElementById('modifier').value;
saving+='&adult='+document.getElementById('adult').value;
saving+='&birth='+document.getElementById('birth').value;
saving+='&sire='+document.getElementById('sire').value;
saving+='&dam='+document.getElementById('dam').value;
saving+='&owner='+document.getElementById('owner').value;
saving+='&breed='+document.getElementById('breed').value;
saving+='&breeder='+document.getElementById('breeder').value;
saving+='&location='+document.getElementById('location').value;
saving+='&id='+document.getElementById('id').value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
resp = JSON.parse(xmlhttp.responseText);
fillForm(0);
}
}
xmlhttp.open("GET","saveEdits.php"+saving,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="search">
<table>
<tr><td>Name:</td><td><input type="text" id="query_name" /></td></tr>
<tr><td>Gender:</td><td><input type="text" id="query_gender" /></td></tr></table>
<button onclick="getData()">Search</button>
</div>
<div id="results">
<div id="paginate"></div>
<input type="hidden" id="id" />
<table>
<tr><td>Name:</td><td><input type="text" id="name" /></td></tr>
<tr><td>Height:</td><td><input type="text" id="height" /></td></tr>
<tr><td>Gender:</td><td><input type="text" id="gender" /></td></tr>
<tr><td>Class:</td><td><input type="text" id="class" /></td></tr>
<tr><td>Death:</td><td><input type="text" id="death" /></td></tr>
<tr><td>Appro:</td><td><input type="text" id="appro" /></td></tr>
<tr><td>Born:</td><td><input type="text" id="born" /></td></tr>
<tr><td>Tobiano:</td><td><input type="text" id="tobiano" /></td></tr>
<tr><td>Modifier:</td><td><input type="text" id="modifier" /></td></tr>
<tr><td>Adult:</td><td><input type="text" id="adult" /></td></tr>
<tr><td>Birth:</td><td><input type="text" id="birth" /></td></tr>
<tr><td>Sire:</td><td><input type="text" id="sire" /></td></tr>
<tr><td>Dam:</td><td><input type="text" id="dam" /></td></tr>
<tr><td>Breeder:</td><td><input type="text" id="breeder" /></td></tr>
<tr><td>Owner:</td><td><input type="text" id="owner" /></td></tr>
<tr><td>Breed:</td><td><input type="text" id="breed" /></td></tr>
<tr><td>Location:</td><td><input type="text" id="location" /></td></tr>
</table>
<div id="saveButton"></div>
</div>
</body>
</html>
and the search:
<?php
//connection established
$query = "SELECT * FROM profiles";
$postParameters = array("name","height","gender","class","death","appro","born","tobiano","modifier","adult","birth","sire","dam","breeder","owner","breed","location");
$whereClause = " WHERE 1 = 1";
foreach ($postParameters as $param) {
if (isset($_POST[$param]) && !empty($_POST[$param])) {
$whereClause .= " AND ".$param."='".$_POST[$param]."'";
}
}
$query .= $whereClause;
$result = mysql_query("$query");
echo "{\"results\":";
if($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "[";
echo "{\"name\":\"".$row["name"]."\",";
echo "\"height\":\"".$row["height"]."\",";
echo "\"gender\":\"".$row["gender"]."\",";
echo "\"class\":\"".$row["class"]."\",";
echo "\"death\":\"".$row["death"]."\",";
echo "\"appro\":\"".$row["appro"]."\",";
echo "\"born\":\"".$row["born"]."\"";
echo "\"tobiano\":\"".$row["tobiano"]."\"";
echo "\"modifier\":\"".$row["modifier"]."\"";
echo "\"adult\":\"".$row["adult"]."\"";
echo "\"birth\":\"".$row["birth"]."\"";
echo "\"sire\":\"".$row["sire"]."\"";
echo "\"dam\":\"".$row["dam"]."\"";
echo "\"breeder\":\"".$row["breeder"]."\"";
echo "\"owner\":\"".$row["owner"]."\"";
echo "\"breed\":\"".$row["breed"]."\"";
echo "\"location\":\"".$row["location"]."\"";
//echo "\"id\":\"".$row["id"]."\"";
echo "}";
}
else{
echo "\"no\"}";
exit;
}
while($row = mysql_fetch_array($data,MYSQL_ASSOC)){
echo ",{\"name\":\"".$row["name"]."\",";
echo "\"height\":\"".$row["height"]."\",";
echo "\"gender\":\"".$row["gender"]."\",";
echo "\"class\":\"".$row["class"]."\",";
echo "\"death\":\"".$row["death"]."\",";
echo "\"appro\":\"".$row["appro"]."\",";
echo "\"born\":\"".$row["born"]."\"";
echo "\"tobiano\":\"".$row["tobiano"]."\"";
echo "\"modifier\":\"".$row["modifier"]."\"";
echo "\"adult\":\"".$row["adult"]."\"";
echo "\"birth\":\"".$row["birth"]."\"";
echo "\"sire\":\"".$row["sire"]."\"";
echo "\"dam\":\"".$row["dam"]."\"";
echo "\"breeder\":\"".$row["breeder"]."\"";
echo "\"owner\":\"".$row["owner"]."\"";
echo "\"breed\":\"".$row["breed"]."\"";
echo "\"location\":\"".$row["location"]."\"";
//echo "\"id\":\"".$row["id"]."\"";
echo "}";
}
echo "]}";
?>

Categories