Unable to click input after checking for form changes - javascript

This is my first post here so please, be gentle.
I am attempting to perform an autosave on a form when the user navigates away from the page that they're on. Mainly, it's for when a user has been working with a record, then goes on to navigate to a new record without first saving their work. So far, I've been able to successfully detect if the form contents have been changed, but I'm hung up on how to perform the save.
Here's the code that I thought would work:
var $formContents = $(document.getElementById("allData"));
origForm = $formContents.serialize();
window.onunload = function() {
var $formContents = $(document.getElementById("allData"));
nowForm = $formContents.serialize();
if (nowForm !== origForm) {
console.log('Changes detected.');
document.getElementById('saveBut').click();
}
else {
console.log('No changes detected');
}
}
Now, the data comparison is working. If I've changed anything in the form, I get the "Changes detected" note in the console. If I haven't, I get the "No changes detected."
However, the "document.getElementById('saveBut').click();" is not running, and the console shows no errors. The 'saveBut' input is contained in a post-method form, and it triggers php code to save the form data to my SQL server.
FWIW, here's the html on the input:
<form method="post" id="save">
<input type="submit" form="allData" value="Save Changes" id="saveBut" name="saveBut"/>
</form>
<form method="post" id="allData">
<input type="hidden" name="formData[]" value="<?php echo $row['ID']; ?>">
<div class="info">
Sermon Date: <input type="date" name="formData[]" value="<?php echo $row['sermon_date']; ?>">
Sermon Location: <input type="text" name="formData[]" value="<?php echo $row['sermon_location']; ?>">
Call to Worship: <input type="text" name="formData[]" value="<?php echo $row['call_to_worship']; ?>">
Hymn of Response: <input type= "text" name="formData[]" value="<?php echo $row['hymn_of_response']; ?>">
</div>
<br><hr style="width:90%"><br>
<div class="top">
Pericope:
<input type="text" size="40" name="formData[]" value="<?php echo htmlspecialchars($row['pericope'], ENT_QUOTES); ?>">
//and on and on...
</form>
I have also tried calling the php code directly by replacing
document.getElementById('saveBut').click();
with:
$.get('saverec.php', function(data) {
eval(data);
});
And then I tried:
$.ajax({
type: "GET",
url: "saverec.php"
});
But neither worked, and I still wound up with the same result being "Changes detected" in my console log, but no errors. I'm sure I'm missing something really basic, but I can't figure out what that might be.
Is there a way to make my saverec.php code run in this manner, or do I need to abandon this mess and come up with a different way?
Edit:
I'm adding the code from my saverec.php file. FYI, there aren't any problems with this code as it runs fine when the user clicks on the 'saveBut' input.
<?php
$location = "i.p.add.ress";
$username = "my_username";
$password = "my_password";
$dbname = "my_database_name";
$tableName = "my_table_name";
$conn = new mysqli($location, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$allData = $_POST['formData'];
$currentID = $allData[0];
//write the form data to the new record
class updateRecord {
public function __construct ($colName, $data, $currentID) {
$this->colName = $colName;
$this->data = $data;
$this->currentID = $currentID;
}
public function writeDataText() {
global $conn;
$ID = strval($this->currentID);
$tableName = "sermon_prep_database";
$sql = "UPDATE " . $tableName . " SET " . $this->colName . "='" . mysqli_real_escape_string($conn, $this->data) . "' WHERE ID=" . $this->currentID;
mysqli_query($conn, $sql);
}
}
//write all the data to the proper columns
$row = new updateRecord('sermon_date', $allData[1], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_location', $allData[2], $currentID);
$row->writeDataText();
$row = new updateRecord('call_to_worship', $allData[3], $currentID);
$row->writeDataText();
$row = new updateRecord('hymn_of_response', $allData[4], $currentID);
$row->writeDataText();
$row = new updateRecord('pericope', $allData[5], $currentID);
$row->writeDataText();
$row = new updateRecord('pericope_texts', $allData[6], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_text', $allData[7], $currentID);
$row->writeDataText();
$row = new updateRecord('fcft', $allData[8], $currentID);
$row->writeDataText();
$row = new updateRecord('gat', $allData[9], $currentID);
$row->writeDataText();
$row = new updateRecord('cpt', $allData[10], $currentID);
$row->writeDataText();
$row = new updateRecord('purpose_bridge', $allData[11], $currentID);
$row->writeDataText();
$row = new updateRecord('fcfs', $allData[12], $currentID);
$row->writeDataText();
$row = new updateRecord('gas', $allData[13], $currentID);
$row->writeDataText();
$row = new updateRecord('cps', $allData[14], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_title', $allData[15], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_scripture', $allData[16], $currentID);
$row->writeDataText();
$row = new updateRecord('text_outline', $allData[17], $currentID);
$row->writeDataText();
$row = new updateRecord('research_notes', $allData[18], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_outline', $allData[19], $currentID);
$row->writeDataText();
$row = new updateRecord('illustrations', $allData[20], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_manuscript', $allData[21], $currentID);
$row->writeDataText();
echo "<script type='text/javascript'>
alert ('Changes saved to ID ' + $currentID);
</script>";

Ajax call should work, have you tried:
$.ajax({
url: "saverec.php",
success: function(data){
console.log('Changes saved.');
}
});
And you should have only one form to get the data:
<form method="post" id="save">
<input type="hidden" name="formData[]" value="<?php echo $row['ID']; ?>">
<div class="info">
Sermon Date: <input type="date" name="formData[]" value="<?php echo $row['sermon_date']; ?>">
Sermon Location: <input type="text" name="formData[]" value="<?php echo $row['sermon_location']; ?>">
Call to Worship: <input type="text" name="formData[]" value="<?php echo $row['call_to_worship']; ?>">
Hymn of Response: <input type= "text" name="formData[]" value="<?php echo $row['hymn_of_response']; ?>">
</div>
<br><hr style="width:90%"><br>
<div class="top">
Pericope:
<input type="text" size="40" name="formData[]" value="<?php echo htmlspecialchars($row['pericope'], ENT_QUOTES); ?>">
//and on and on...
<input type="submit" form="allData" value="Save Changes" id="saveBut" name="saveBut"/>
</form>

Just in case anyone stumbles across this, I figured I'd add the code that finally let me do an autosave of the form at onbeforeunload:
//get the initial state of the form and store it into a variable
var $formContents = $(document.getElementById("allData"));
origForm = $formContents.serialize();
window.onbeforeunload = function() {
//get the current state of the form on BeforeUnload and store it into a variable
var $formContents = $(document.getElementById("allData"));
nowForm = $formContents.serialize();
//compare the current state of the form with the initial state of the form
if (nowForm !== origForm) {
console.log('Changes detected.');
//use ajax to post the current form data to saverec.php
$.ajax({
type: 'post',
url: 'saverec.php',
data: nowForm,
success: function(data){
console.log('Changes saved.');
}
});
}
else {
console.log('No changes detected');
}
}
Of course, this means that the form will be saved even if the user doesn't want it to be, but that can be easily remedied with some sort of cancel button that overrides this onbeforeunload code. Besides, it's really not an issue with this application.

Related

Repeat self-processing form

My question is over creating a self-processing form that inserts to a database and then refreshes, incrementing arrays to change relevant info in the form. (though if there is an easier or better way to do this, I'm all ears).
So site is essentially a digital equivalent to an exercise journal. The user selects a template name from a select menu, then it queries the database for that template, then returns the result to a variable. The exercise names and number of sets per exercise (which will be used to calculate maximum number of form refreshes) are passed into their own respective arrays: $exerciseName[]; and $setNum[];
This is a screenshot of the form.
My question is how to go about setting up the logic so that I can keep submitting until the last set of the last exercise, where upon the final submission, would take to a different page.
I am using mysql_ functions, which I know is frowned upon, but it is for school which uses PHP 5.2.12 and that is what my teammates know so I have no other options. I haven't tried to prevent mysql injections because I don't intend to take this version online.
Here is the code for selecting type of workout and workout template:
session_start();
$user = $_SESSION['email'];
//This script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
if ($user) {
require("include/connect2db.inc.php");
require("include/htmlHead.inc");
//Default page buttons
$cardioBtn = $_POST['cardioBtn'];
$resistanceBtn = $_POST['resistBtn'];
//Cardio submit
$cardioSubmit = $_POST['cardioSubmit'];
if ((empty($cardioBtn))
&& (empty($resistanceBtn))
&& (empty($selectSubmit))
&& (empty($cardioSubmit))) {
echo <<<BODYDOC
<article id="newDayArticle">
<header>
<h2>Category</h2>
</header>
<fieldset id="ndFieldset">
<form action="$thisScript" method="POST" >
<button id="cardioButton" name="cardioBtn" value="cardioBtn" >Cardio</button>
<button id="resistanceButton" name="resistBtn" value="resistBtn" >Resistance</button>
</form>
</fieldset>
<!-- <div id="selection"></div>
<div id="template"></div> -->
</article>
BODYDOC;
} else if (isset($cardioBtn)) {
//Build cardio form
echo "<h2>Cardio</h2>";
echo <<<BODYDOC
<fieldset>
<legend>Cardio Log</legend>
<form action="$thisScript" method="POST">
<input type="number" name="distance" placeholder="Distance of Run" required />
<input type="number" name="duration" placeholder="Run Duration" required />
<button id="cardioSubmit" name="cardioSubmit">Submit</button>
<button id="back" type="button" onclick="document.location.href='newday.php';" value="Back">Back</button>
</form>
</fieldset>
BODYDOC;
} else if (isset($cardioSubmit)) {
$thisScript = htmlentities($_SERVER['PHP_SELF']);
//Cardio page
$distance = $_POST['distance'];
$duration = $_POST['duration'];
$date = date("Y-m-d");
//Submit cardio data to DB
updateCardio($distance, $duration, $user, $date);
//Show user stats in table
cardioStats($distance, $duration);
//End cardio form
} else if (isset($resistanceBtn)) {
//Workout template select
$selectSubmit = $_POST['selectSubmit'];
//page to select workout template
buildSelect();
//End resistance select
}//End else if
//Require footer
require("include/htmlFoot.inc");
mysql_close();
} else {
//Redirect users not logged in
require("include/redirect.php");
} //End redirect else
Here is the select function and functions for building the form and inserting it into the database.
function buildSelect() {
//Check if resistance button submitted
//Query for template names
$query = "SELECT templateName, templatePosition
FROM templates
WHERE userID = 0
ORDER BY templatePosition";
$result = mysql_query($query)
or
die("<b>Query Failed</b><br /> $query<br />" . mysql_error());
//Find number of rows
$numRows = mysql_num_rows($result);
//Array with spaces/capitals
$templateArray = array();
//Array with no spaces/no capitals
$noSpacesArray = array();
//Get template names and build arrays
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$templateName = $row[0];
$position = $row[1];
//Build array in order by pushing to $templateArray
array_push($templateArray, $templateName);
//Build array without spaces or capitals in $noSpacesArray()
$templateName = str_replace(' ', '', $templateName);
$templateName = strtolower($templateName);
array_push($noSpacesArray, $templateName);
} //End while
}//End for
//Check array values
//print_r($templateArray);
//print_r($noSpacesArray);
//Build page
echo <<<BODYDOC
<br />
<h2>Resistance</h2>
<form action="log.php" method="POST" >
<fieldset>
<legend>Resistance Templates</legend>\n
BODYDOC;
echo "<select name='mySelect' id='mySelect'>\n";
echo "\t<option value=''>Choose One</option>\n";
//Build Template
//Build Template
for ($i=0; $i < count($templateArray); $i++) {
//value='$noSpacesArray[$i] is for no spaces, all lower case
//value='$templateArray[$i] is for First letter capital, with spaces
echo "\t<option value='$templateArray[$i]'>$templateArray[$i]</option>\n";
} //End list generation
echo "</select>\n";
echo <<<BODYDOC
<input type="submit" name="selectSubmit" value="Submit" />
<br />
</fieldset>
</form>
BODYDOC;
} //End function buildSelect
//Function uses template name as argument in an SQL query to find exercise template
//Returns exercise IDs, exercise names, and # of sets per exercise in that template
function getResult($template) {
//Query template name and get templateID
$query = "SELECT templateID
FROM templates
WHERE templateName = '$template'";
$result = mysql_query($query)
or
die("<b>Query Failed</b><br />$query<br />" . mysql_error());
//This part made me smash my head into a wall
$templateID = mysql_fetch_object($result);
$templateID = $templateID->templateID;
//Get exercise template, exercise names, and number of sets with query
$query = "SELECT exerciseID, exerciseName, numSets
FROM exercises
WHERE templateID = $templateID";
$result = mysql_query($query)
or
die("<b>Query Failed</b><br />$query<br />" . mysql_error());
return $result;
} //End getExercises
//Get number of exercises
function getExerciseNum($result) {
//Get number
$numRows = mysql_num_rows($result);
return $numRows;
}//End getExerciseNum
//Get exercise names as array
function exerciseList($result, $numRows) {
//Initialize exercise name array
$exerciseArray = array();
//Exercise array increment
//
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$exerciseName = $row[1];
//Push names to array
array_push($exerciseArray, $exerciseName);
} //End while
} //End for
//Return name array
return $exerciseArray;
}//End exerciseList()
//Get number of sets per exercise
function getSets($result, $numRows) {
//
$setsArray = array();
//
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$numSets = $row[2];
//Push to array
array_push($setsArray, $numSets);
} //End while
} //End for
//Return array
return $setsArray;
} //End setsPerExercise()
//Build log form using query result and exercise name increment ($x)
function buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date) {
$logSubmit = $_POST['logSubmit'];
//echo "numRows = " . $numRows;
static $x = 0;
echo "<br />X = $x";
if (empty($logSubmit)) {
echo "<form action='$thisScript' method='POST' name='log' id='log'>\n";
echo "<fieldset>\n";
echo "<legend>$template</legend>\n";
echo "<h2>$exerciseArray[0]</h2>\n";
echo "<input type='hidden' name='exerciseArray[]' value='$exerciseArray[$x]'/>\n";
$j = 1;
//Generate exercise form with loop
for ($i=0; $i < $setsArray[$i]; $i++) {
echo "<fieldset>";
echo "<legend>Set $j</legend>\n";
//Use $template in a hidden value to work around issue of value being lost after submitting form
echo <<<BODYDOC
<label>Weight</label>
<input type="text" name="weight[]" required /> \n
<label>Reps</label>
<input type="number" name="reps[]" required /> \n
<label>Rest Time</label>
<input type="number" name="rest[]" required /> \n
<label>Notes</label>
<textarea name="notes[]"></textarea>
<input type="hidden" name="set[]" value='$j' />
<input type="hidden" name='mySelect' value='$template' />
</fieldset>
BODYDOC;
$j++;
} //End form for loop
echo "<br /><button type='submit' name='logSubmit'>Submit</button>\n";
echo "</fieldset>\n";
echo "</form>\n";
echo "<p><a href='newday.php'>Back</a></p>\n";
//Increment exerciseNameArray counter so next form dispays next exercise name
} //End if empty submit
if (isset($logSubmit)) {
//POSTed
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];
//Update Log
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date);
} //End else if
} //End buildLog($template, $x) function
function updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date) {
//Insert data with query
$numRows = count($exerciseArray);
echo "count exerciseArray = " . $numRows;
for ($i=0; $i < $numRows; $i++) {
$insert[$i] = "INSERT INTO stats_resistance
(userID, template, exerciseName, set, weight, reps, rest, notes, date)
VALUES
('$user','$template', $exerciseArray[$i]','$set[$i]','$weight[$i]','$reps[$i]','$rest[$i]', '$notes[$i]', '$date')"
or
die(mysql_error());
$result[$i] = mysql_query($insert[$i])
or
die(mysql_error());
} //End for
//Increment $x and pass it back to buildLog
//$x++;
//return $x;
} //End updateLog()
Here is the log.php form file:
Edit: Added htmlentities to PHP_SELF and changed some logic.
session_start();
//User
$user = $_SESSION['email'];
$date = date("Y-m-d");
//
$template = $_POST['mySelect'];
//Set log submit button
$logSubmit = $_POST['logSubmit'];
//Check if user is signed in
if ($user) {
if ($template) {
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
//Return query
$result = getResult($template); //Returns result of template
//numRows
$numRows = getExerciseNum($result);
//Return exercise array
$exerciseArray = exerciseList($result, $numRows); //Returns set of exercises in template
//For some reason, $result and $numRows is empty after being passed into $exerciseArray
//Reinitialize
$result = getResult($template); //Returns result of template
//numRows
$numRows = getExerciseNum($result);
//Return sets per exercise as array
$setsArray = getSets($result, $numRows);
//Build form
buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date);
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} else if (empty($template)){
//Do something if template is empty
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
echo "<p>Seems the template is empty</p>\n";
echo "<p>Template = $template</p>\n";
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} //End if ($template)
} /*else if (($user) && (isset($logSubmit))) {
//If user is signed in and log has been submitted
//Get form values and insert into database
require("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
echo "<pre>\n";
echo "print_r of POST<br />";
print_r($_POST);
echo "</pre>\n";
//Get Workout and POST info
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];
//Check if form is submitted, if so, insert into db
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date);
echo "<p>Entered update log else/if block</p>\n";
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
}*/ else if (!isset($user)) {
//If user not logged in
require("redirect.php");
}
You can use PHP_SELF (eg <?php echo htmlentities ($ _ SERVER ['PHP_SELF']); ?>) In the action of the form. See this article which explains why we need htmlentities. This PHP_SELF variable contains the path to the current script.
All the logic you can place where you have, before the template, where you should check the following:
Did happen a page submit?
If yes, check for errors with submitted data.
If there are no errors treats and saves the information. If there are send an array with errors for the template.
If not, nothing to do.
Thus, when there is submission of the form everything will always be submitted on the same page.

how should i put data fetched from ajax call in hidden div box

i am working on a project and come across a module.
page1
user have to search from search bar which will take him to page 2.
page2
On page 2 all fetched results will get displayed to user in div's. Each result has a checkbox associated with it.
when i click on add to compare check box ,ajax call is executed and fetched selected result should appear in hidden div.
my problem is it is only shows first result in hidden div and not working with another result.
My code of page 2
<script type="text/javascript">
$(document).ready(function()
{
var check = $('#compare').val();
$("#compare").change(function() {
if(this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').html(data);
}
});
$("#compare_box").show();
}
else
{
$("#compare_box").hide();
}
});
});
</script>
</head>
<body>
<?php
$query = $_GET['search_bar'];
$query = "call fetch_data('$query')"or die(mysqli_error($conn));
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result))
{
$id = $row['course_id'];
$title = $row['course_title'];
$description = $row['course_description'];
$course_url = $row['course_url'];
$video_url = $row['course_video_url'];
$fee = $row['course_fee'];
$duration = $row['course_duration'];
$start_date = $row['course_start_date'];
$university = $row['university_name'];
$course_provider = $row['course_provider_name'];
$instructor = $row['instructor_name'];
$_SESSION['result'][$id] = Array('id'=> $id,'course_title' => $title,'course_description'=> $description,'course_url' => $course_url,'video_url' => $video_url,'fee' => $fee,'course_duration'=>$duration,'start_date'=>$start_date,'university' => $university,'course_provider'=>$course_provider,'instructor'=>$instructor);
?>
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
<?php
}
?>
page3 compare.php
<?php
session_start();
include 'includes/dbconfig.php';
$check = $_POST['value'];
$sql = "SELECT * from course_info_table where course_id = '$check' " or die(mysqli_error($conn));
$result = mysqli_query($conn,$sql);
$index = 0;
while($row = mysqli_fetch_array($result))
{
$title = $row['course_title'];
?>
<?php
}
echo json_encode($title);
?>
You can change
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">
to
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">
^you can only have one unique 'id' value in your html doc, which means your first id="compare" will work fine and others with id="compare" will be ignored by the DOM tree
Reference:
http://www.w3schools.com/tags/att_global_id.asp

AJAX passing value confusion

I was looking for a way to submit data through a button so that the data will be saved or updated in database, without reloading. Now updating and inserting of data works. But I have used dataString a javaScript variable. I thought through this dataString variable post data are passed. But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
How post method gets the data from my ajax call here.
<html>
<title>Registration</title>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
$dbname = "registration_project";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<div style="width:350px">
<div style="float:left;width:40%">
Id:<br/><br/>
First Name:<br/><br/>
Last Name:<br/><br/>
Age:<br/><br/>
</div>
<div style="float:left;width:60%">
<form action="" method="post">
<input type="number" id="id_id" name="id" value=<?php
if (isset($_POST['id']))
echo $_POST['id'];
?>><br /><br />
<input type="text" id="id_fname" name="fname" value=<?php
if (isset($_POST['fname']))
echo $_POST['fname'];
?>><br /><br />
<input type="text" id="id_lname" name="lname" value=<?php
if (isset($_POST['lname']))
echo $_POST['lname'];
?>><br /><br />
<input type="number" id="id_age" name="age" value=<?php
if (isset($_POST['age']))
echo $_POST['age'];
?>><br /><br />
<input type="submit" id="id_submit" name="submit">
</form>
</div>
</div>
<script src="js/jquery-1.11.3.js"></script>
</body>
</html>
<?php
if (isset($_POST['id']))
echo $_POST['id'] . "<br/><br/>";
if (isset($_POST['fname']))
echo $_POST['fname'] . "<br/><br/>";
if (isset($_POST['lname']))
echo $_POST['lname'] . "<br/><br/>";
if (isset($_POST['age']))
echo $_POST['age'] . "<br/><br/>";
?>
<?php
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "select max(id) from registration";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$id = $row["max(id)"];
}
} else {
echo "0 results";
}
if ($id==$_POST['id']) {
$id = $_POST['id'];
$sql = "update registration set firstName='$fname', lastName='$lname', age=$age where id=$id";
mysqli_query($conn, $sql);
} else {
$id=$_POST['id'];
$sql = "Insert into registration(id,firstName,lastName,age) values($id,'$fname','$lname',$age)";
mysqli_query($conn, $sql);
}
}
mysqli_close($conn);
?>
<script>
$("#id_submit").click(function(e) {
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
</script>
Your click handler doesn't have e.preventDefault() in it. So after the AJAX call is sent, the form is also submitted normally. So even if you don't fill in dataString, the database will be updated from the form.
To make it only use AJAX, you should call e.preventDefault(). You also need to submit a value for the submit parameter, because the PHP code uses if(isset($_POST['submit'])) to know if it should process the form parameters.
$("#id_submit").click(function(e) {
e.preventDefault();
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "submit=submit&id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
In your case, values aren't getting passed. More over, the way you're trying to do ( ?id=...&fname=... etc) would be for passing it with $_GET.
You have to make something similar to :
$.ajax({
type:'POST',
data: { id : $("#id_id").val(),
fname : $("#id_fname").val(),
lname : $("#id_lname").val(),
age : $("#id_age").val()
},
url:'Registration.php',
success:function(data) {
// code
}
});
But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
Answer
When you remove var dataString all the fields having name attribute are automatically submitted along with form

Get mysql column of a clicked item

I have searched endlessly for an answer but have found none. I am trying to get the id of a clicked item. The item that I am clicking is from mysql database and has been displayed through a for loop. When the item is clicked I am taken to another page. In this page I want to utilize the id from the clicked item to get other information from that row in mysql database; this much I can do. The problem is getting the id from the clicked item and sending it.
This is the most recent way that I tried:
First I displayed the items from mysql.
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
$code = "<div id=\"challenge_preview\"><h7 class=\"challenge_preview_item\"
id=\"challenge_preview_name\"></h7><a href=\"challengeprofile.php\">
<video
class=\"challenge_preview_item\" id=\"challenge_video\"
src=\"".mysql_result($result, $i)."\"></video></a></div>";
echo $code;
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
Than I put the id in a hidden form so that I could attempt to POST it to the other page:
<form action="<?php echo $current_file; ?>" method="POST">
<input type="hidden" name="id" value="14">
</form>
On the script.php file that is included in both pages, I put
$(#challenge_video).click(function(){ <?php $id = $_POST['id']; ?> ;});
And on the page that the id is being posted to I put
<?php
include 'script.php';
echo getChallengeData('name', 'id', $id)
?>
Please help, Thank you
These are the edits
<div id='challenge_previews'>
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
echo "<div id=\"challenge_preview\"><video class=\"challenge_preview_item challenge_video\" src=\"".mysql_result($result, $i)."\"></video></div>";
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
<form action="<?php echo $current_file; ?>" method="GET">
<input type="hidden" name="id" value="14">
</form>
</div>
This is the code for page 2
<h1 id="challenge_profile_name">
<?php
$id = substr(base64_decode($_GET['id']),6);
echo getChallengeData('name', 'id', $id);
?>
</h1>
This is the code for the getChallengeData method in the core.inc.php
function getChallengeData($field1, $field2, $field3)
{
$query = "SELECT `$field1` FROM `challenge_name` WHERE `$field2` = '$field3'";
if($query_run = mysql_query($query))
{
if($query_result = mysql_result($query_run, 0, $field1))
{
return $query_result;
}
}
}
That error that I'm getting has to do with the implementation of the getChallengeData method on page 2. The error says
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 10 in C:\xampp\htdocs\ChallengeNetworkWebsite\core.inc.php on line 42

Create session variables out of looped database values

I am attempting to create a variable from a database array when an HTML link is clicked. The goal is to redirect the user to a form populated using one piece of array data. In other words, the database will be queried and form populated according to which link is clicked (whatever the values of $row[1], $row[2], and $row[3] are).
<?php
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
If anyone can provide me with some incite as to how I could accomplish this I'd appreciate it greatly.
Please read more about sessions here
Then, to answer your question:
First you need to start the session, as simple as session_start(); on the top of your script.
Second you need to instantiate session variables with the DB values like this: $_SESSION['var'] = $value;.
Third, in the html file or whatever, where the form relies, just check for it:
if(isset($_SESSION['var'])) {
echo '<input type="text" value="'.$_SESSION['var'].'" />';
} else {
echo '<input type="text" value="" />';
}
and use the value if it is set.
L.E:
So... first thing's first... session_start(); without it, there is no point of having session.
Second, you create it like $_SESSION['some_name'] = $row[1] so that var will keep the value from $row[1]. I am presuming that it's the value you need. Do NOT do do it like $_SESSION['$row1'] because first of all this is incorrect, you will NOT have the value of row1 there. You need an unique name so that you can call it where you have the form.
The above code will become something like this:
<?php
session_start();
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
$_SESSION['first_row'] = $row[1];
$_SESSION['second_row'] = $row[2];
$_SESSION['third_row'] = $row[3];
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
and, where you have the form and the <input type = "text" value = "" /> so where you need the value, just do it like this:
<input type = "text" value = "<?php echo (isset($_SESSION['first_row']) ? $_SESSION['first_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['second_row']) ? $_SESSION['second_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['third_row']) ? $_SESSION['third_row'] : ''); ?>" />
Hope this helps! :D

Categories

Resources