So, I have a form that has to be filled by the user in a duration. (Fyi, it's still a dummy web). Let's say the duration is 100sec. After 100sec, the data should be sent to database. Here are my codes :
HTML
<div id="countdown"></div>
<form class="test" method="post">
<?php
for($num=1;$num<=10;$num++){
echo "<div class=\"question\">" .$num. "<br>"; /* the question is written here */
echo "<input type=\"radio\" name=\"answer" .$num. "\" value=\"A\">A<br>";
echo "<input type=\"radio\" name=\"answer" .$num. "\" value=\"B\">B<br>";
echo "<input type=\"radio\" name=\"answer" .$num. "\" value=\"C\">C<br>";
}
?>
</form>
Why did I do PHP and looping? Coz this is the prototype of my form and also for shortening purpose. I'll not do this for the real web. But, if you think this is a bad idea although it's just a dummy web, just tell me :)
jQuery
var duration=100;
var countdown=setInterval(timer,1000);
function timer(){
duration=duration-1;
$("#countdown").html(duration+" sec");
if(duration<=0){
clearInterval(countdown);
var form_data=$(".test").serialize();
$.post("action.php",form_data,function(){alert("success!")});
}
}
action.php
<?php
include("connection.php"); /* it's the connection to the database */
$answer1=$_POST["answer1"];
$answer2=$_POST["answer2"];
$answer3=$_POST["answer3"];
$answer4=$_POST["answer4"];
$answer5=$_POST["answer5"];
$answer6=$_POST["answer6"];
$answer7=$_POST["answer7"];
$answer8=$_POST["answer8"];
$answer9=$_POST["answer9"];
$answer10=$_POST["answer10"];
mysqli_query($link,"INSERT INTO prototype (`answer1`,`answer2`,`answer3`,`answer4`,`answer5`,`answer6`,`answer7`,`answer8`,`answer9`,`answer10`) VALUES ('$answer1','$answer2','$answer3','$answer4','$answer5','$answer6','$answer7','$answer8','$answer9','$answer10')";
?>
So, the problem is : after the duration = 0, the success action (alert) appears, but after I checked the database, no data has been stored. Wut's actually happen?
Related
I am trying to obtain the $_POST variable generated from a login form using JQuery.
My web page has three sections Header, Navigation and Main.
"Main" contains the form and should be changed depending on the results of the input to the form, (login validation).
I can get the "main" section to change when thr form is submitted but cannot obtain the $_POST variables created by the form's tags.
I suspect I need to use ajax in order to do this but I am totally new to ajax and can't find a good and simple example to follow.
Help and suggestions as to how I can get this working would be greatly appreciated.
Here are the test files that I am using to try this out. (The array dump in TEST_1.php is always returned empty)
TEST.php
<?php
session_start();
echo "<!DOCTYPE html><html lang='en'><head>";
echo "<script language='JavaScript1.1' src='scripts/KSG.js'></script>";
echo "<script type='text/javascript' charset='utf-8'>
function valid_mem(){
if (document.form_1.member.value.length === 0){
req('Username.');
return false;
}else{
if (document.form_1.mpass.value.length === 0){
req('Password');
return false;
}return true;
}}
</script>";
echo "<script src='js/jquery-1.8.0.min.js'></script>";
echo "</head>";
echo "<body style='background-color:#eeeecc'>";
echo " <div style='background-color:#6495ed; height: 80px;'>";
echo " <div class='col-md-12 text-center'><b>HEADER</b> div</div>";
echo " </div>";
echo " <div id='mainx' style='background-color:#cccccc; height: 600px;'>";
require ('TEST_0.php');
echo " </div></body></html>";
?>
TEST_0.php
<?php
echo "<script type='text/javascript' charset='utf-8'>
$(document).ready(function(){
$('#form_1').submit(function(e){
e.preventDefault();
var z = valid_mem();
if(z){
var x = $('#form_1').attr('action');
alert('debug_1: '+x);
console.log(x);
$('#mainx').load(x);
}
});
});
</script>";
echo "<form id='form_1' name='form_1' action='TEST_1.php' method='post'>";
echo "<b>MAIN</b> div<br>A test form using submit<br><br>";
echo "Member: <input type='text' name='member' > ";
echo "Password: <input type='text' name='mpass' >";
echo "<button id='but1' type='submit' >OK</button>";
echo "</form>";
?>
TEST_1.php
<?php
echo " THIS IS A DUMMY PAGE: TEST 1<br><br>";
echo "<pre>";var_dump($_POST);echo "</pre>";
?>
First of all, you seem new to PHP in general. I recommend you read the "getting started" section on php.net (specifically, you shouldn't be "echo"ing everything, it makes your code hard to read - just leave it outside the tags).
Second, as PHP variables are server side, you cannot access them directly via JS. You have the following options:
Changing the page on the server side depending on the content of $_POST. As a rule of thumb, you should always do this when possible.
Embed the relevant data in $_POST in elements on the page via JQuery data attributes that can later be accessed.
As to AJAX, it is generally a great way to get data from the server side to the client side dynamically, but in this case it would be unneccesarily complicated, as $_POST is only available to the page the form is sent to.
I am trying to create a 'submit' input type button that when clicked will call up a switch case action that I've defined in PHP. When the 'submit' button is clicked, I want the form action to essentially create a link and display in the URL form action so that it is called properly by the PHP file.
However when I click on the submit button, the URL does not properly display the desired link and action.
PHP:
$getuserid_result = mysql_query($getuseridsql, $conn);
$userid_array = mysql_fetch_array($getuserid_result);
$userid = $userid_array['uid'];
// Above code works fine and retrieves the current user's ID
// PHP Form code is below
// Variables used for creating the id of the input since the submit button is displayed
// in an HTML table with multiple rows. These variables are working fine.
$time_cell_row = 1;
$time_cell_column = 1;
echo "<form action='enter_time.php?uid='" . $userid . "?action=timesubmit method='get'>";
echo "<td><input name=submit_time type=submit id=submit_time" . $time_cell_row . $time_cell_column . "></input></td>";
echo "</form></tr>";
// PHP Action code
/* This is currently commented out and will eventually be filled with code to handle
the 'timesubmit' action
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'timesubmit':
}
}
*/
The problem now is when I click on the 'submit' button, the URL displayed enter_time.php?submit_time=Submit" instead of "enter_time.php?uid=3?action=timesubmit
You might want to add in the final apostrophe after timesubmit
echo "<form action='enter_time.php?uid=" . $userid . "?action=timesubmit' method='post'>";
You have a quote after uid that should not be there:
"<form action='enter_time.php?uid=" . $userid . "?action=timesubmit method='get'>";
If you are using a form to submit GET variables into a url you could do something like
<a id="submit_time<?= $time_cell_row . $time_cell_column ?>" href="enter_time.php?uid=<?= $userid ?>">Submit Time</a>
If you prefer to use a form, writing it this way looks clearer to me
PHP
<?php
$getuserid_result = mysql_query($getuseridsql, $conn);
$userid_array = mysql_fetch_array($getuserid_result);
$userid = $userid_array['uid'];
// Above code works fine and retrieves the current user's ID
// PHP Form code is below
// Variables used for creating the id of the input since the submit button is displayed
// in an HTML table with multiple rows. These variables are working fine.
$time_cell_row = 1;
$time_cell_column = 1;
?>
<form action='enter_time.php' method='get'>
<input type="hidden" name="action" value="<?= $timesubmit ?>">
<input type="hidden" name="uid" value="<?= userid ?>">
<input name="submit_time" type="submit" id="submit_time<?= $time_cell_row . $time_cell_column ?>" />
</form>
<?php
// PHP Action code
/* This is currently commented out and will eventually be filled with code to handle
the 'timesubmit' action
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'timesubmit':
}
}
*/
?>
Just off top of my head it should be:
echo "<form action='enter_time.php?uid=" . $userid . "?action=timesubmit' method='get'>";
Single quote after "uid=" was in the wrong place. Shouldn't be until after "timesubmit".
I'm trying to update records in DB without refreshing Form. I have grid.php page with the form to display and update records. Then, I have the file update.php with the UPDATE query. The third file is js1.js with AJAX code. If I map the grid.php to update.php through action=update.php, the update query works great. But as soon as I try to include js1.js file to prevent form refreshing, it stops working.
The code is as following:
grid.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="j1.js"></script>
<?php //query.php
require_once 'header.php';
if (!$loggedin) die();
$query = "SELECT SpringMgmt.SpringMgmtID,
SpringMgmt.SpringMgmtActiveYear,
SpringMgmt.PoolID,
SpringMgmt.Notes,
SpringMgmt.SOIEstSubmitted,
SpringMgmt.EstAdditional,
SpringMgmt.SOIMeetingScheduled,
Pool.Pool,
Pool.AreaManager,
Employees.EmployeeID,
Employees.FirstName
FROM SpringMgmt
INNER JOIN Pool ON SpringMgmt.PoolID = Pool.PoolID
INNER JOIN Employees ON Employees.EmployeeID = Pool.AreaManager ";
$result = mysql_query($query);
echo "OK</div>";
if (!$result) die ("Database access failed0: " . mysql_error());
//TABLE AND ITS HEADING
echo '<table id="header" cellpadding="0" cellspacing="0" border="0" >';
echo "
<tr>
<th>Pool</th>
<th>Notes</th>
<th>SO Sent</th>
<th>Est</th>
<th>Meet Date</th>
</tr>
";
while($record = mysql_fetch_array($result)){
echo "<form id='myForm' name='myForm' method=post>";
echo "<tr>";
echo "<td >$record[Pool]</td>";
echo "<td ><textarea size=4 name=Notes rows=3 cols=22>$record[Notes]</textarea> </td>";
echo "<td style=background-color:><input type=text size=3 name=SOIEstSubmitted value='$record[SOIEstSubmitted]' /></td>";
echo "<td ><textarea size=4 name=EstAdditional rows=3 cols=12>$record[EstAdditional]</textarea></td>";
echo "<td style=background-color:><input type=text size=3 name=SOIMeetingScheduled value='$record[SOIMeetingScheduled]' /></td>";
echo "<td>
<input type=hidden name='SpringMgmtID' value=$record[SpringMgmtID] />
<input type=submit name='submit' id='submit' value='Submit' />
</div></td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
?>
update4.php:
<?php
require_once 'header.php';
if (!$loggedin) die();
if(isset($_POST['submit'])){
$UpdateQuery = "UPDATE SpringMgmt
SET Notes='$_POST[Notes]',
SOIEstSubmitted='$_POST[SOIEstSubmitted]',
EstAdditional='$_POST[EstAdditional]',
SOIMeetingScheduled='$_POST[SOIMeetingScheduled]'
WHERE SpringMgmtID='$_POST[SpringMgmtID]'";
mysql_query($UpdateQuery);
};
?>
js1.js
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
Disclosure: I may sound incredibly patronizing and even mean in my response, please note that it is not my intention. I will show you how to fix the issue, but let me first add some comments about the code above along with some suggestions:
The structure of your HTML is not good: a form shouldn't be wrapping each tr, you should consider using div instead of a table, or a "table inside a form inside a cell" (the code looks as ugly as it sounds). You can read more about a similar case here: Create a HTML table where each TR is a FORM
Your SQL statement is subject to SQL injection. This is bad. Really, really bad. As I mentioned in the comments, consider changing to MySQLi or PDO and using parameterized queries. You can read more about it here: How can I prevent SQL injection in PHP?
Your HTML code is not clean. In general, your page will work because the browser will help, but trust me, that is bad programming: you'll eventually change the code, forget about it, and it will be a mess. From what I see:
There are multiple elements with the same ID (all the forms created by the loop).
There is incomplete inline CSS (background-color:).
Quotes are missing in many places.
There are a couple of closing </div> without an opening <div> (this could be OK if the opening div comes from header.php; but even if that was the case, the code would be difficult to maintain)
Finally, the solution. I hope you didn't skip all the text above and jump directly here, because it will really help you not only now but in the future.
Change these two things and your code will work (both in js1.js):
Wrap the function in a $(document).ready so it is executed when the page finishes loading.
Change the data from $("form").serialize() to $(this).serialize(), this way you will be sending only the information from the form with the button that you clicked on (instead of all the forms).
The final code for js1.js would look like this:
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $(this).serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
Okay, so a few things I'm going to try and help you out with quickly.
Query
Your query is complicated, but I feel needlessly so. I've been doing things with MySQL for quite some time now and I can't recall a situation where I used INNER JOIN in the method you are. A much shorter syntax for your query would therefore be: SQL Aliases
$query = "SELECT s.*, p.Pool, p.AreaManager, e.EmployeeID, e.FirstName
FROM SpringMgmt as s, Pool as P, Employees as E
WHERE s.PoolID = p.PoolID AND e.EmployeeID = p.AreaManager ";
HTML
Assuming the HTML in your script is the way you want for it to be shown, here's a few things: you can escape double quotes so that they do not break your code. I would change the code inside your loop to this: Click Here to understand the ".$variable." statements I put in your code
echo "<form id=\"myForm\" name=\"myForm\" method=\"post\">";
echo "<tr>";
echo "<td data-field-id=\"pool\">".$record['Pool']."</td>";
echo "<td ><textarea data-field-id=\"notes\" size=\"4\" name=\"Notes\" rows=\"3\" cols=\"22\">".$record['Notes']."</textarea> </td>";
echo "<td style=\"background-color:\"><input data-field-id=\"submitted\" type=\"text\" size=\"3\" name=\"SOIEstSubmitted\" value=\"".$record['SOIEstSubmitted']."\" /></td>";
echo "<td ><textarea size=\"4\" data-field-id=\"additional\" name=\"EstAdditional\" rows=3 cols=\"12\">".$record['EstAdditional']."</textarea></td>";
echo "<td style=\"background-color:\"><input data-field-id=\"meetingScheduled\" type=\"text\" size=\"3\" name=\"SOIMeetingScheduled\" value=\"".$record['SOIMeetingScheduled']."\" /></td>";
echo "<td>
<input type=\"hidden\" name=\"SpringMgmtID\" value=\"$record[SpringMgmtID]\" />
<input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Submit\" />
</div></td>";
echo "</tr>";
echo "</form>";
AJAX/Javascript Calls
This is a bit more complicated to explain. The jQuery ajax object success function can accept a few parameters to help you in your request. See this link for more explanation. Jump the section about the .done() function. One of them is the data returned FROM the request. This means that in your update4.php file, if you would output the data to the browser as a JSON object, you could then use that data back on your original page.
$(document).ready(function(){
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $(this).serialize(),
success: function (data,successText) {
for(var x in data){
//Use tree traversing to find the input/text elements that have the data-field-id option equal to the x variable; I can't test it right now so I don't want to have this here.
}
}
});
});
});
Update4.php
As another user pointed out in the comment section, your query here is very prone to SQL Injection. Please follow the link they provided to read more.
Now, assuming you want all of the data returned back, the very last set of lines in your update4.php file should be something close to :
<?php
require_once 'header.php';
if (!$loggedin) die();
if(isset($_POST['submit'])){
$UpdateQuery = /*"UPDATE SpringMgmt
SET Notes='$_POST[Notes]',
SOIEstSubmitted='$_POST[SOIEstSubmitted]',
EstAdditional='$_POST[EstAdditional]',
SOIMeetingScheduled='$_POST[SOIMeetingScheduled]'
WHERE SpringMgmtID='$_POST[SpringMgmtID]'";
Don't do this, please use a prepared statement or mysql(i)_real_escape_string() on the data.*/
$result = mysql_query($UpdateQuery);
if($result!==false){
echo json_encode(array(
'notes'=> $_POST['Notes'],
'submitted'=> $_POST['SOIEstSubmitted'],
'additional'=>$_POST['EstAdditional'],
'meetingScheduled'=>$_POST['SOIMeetingScheduled']
));
}
};
NOTE I do NOT recommend doing this. You should move these $_POST variables into other variables that you have properly sanitized. NEVER assume that your users have no knowledge of web technologies. Always, ALWAYS assume the user is someone who has the malicious intent to steal the data from your database. Therefore, ALWAYS check user-inputted data. The only reason I have set this up is because you seem like you are fairly new to these aspects of web development and with all of the other information I've presented I don't want to overload you and turn you off from web development/design.
Side Note
I would suggest looking up a template engine of some variety. It is generally a better practice to have your display (HTML) and data (PHP) as separate as possible. The only template engines I've used previously were a modified version of PhpBB 3's template engine, and Smarty (which the phpBB team based their template engine on).
Since beginning to type this I've seen another answer posted and read it quickly. I think both of us address slightly different portions of your overall problem, so I will give this post to you as a reference, though I think the other user's answer is a bit better than mine is. I repeat his sentiment though, if I sound condescending or mean, I don't mean to.
Also, as I'm sure someone will or has pointed out to you, get in the habit of using mysqli_* functions as mysql_ will be deprecated (no longer usable) in coming versions of PHP.
I have this form that contains dynamically generated textboxes filled with values (those are read from the database), and I let the user modify and save them.
But I don't know how to save the data, how to pass them to the "saver" php page (which eventually the same now, doesn't matter...)
For now, they seem like this:
echo "<td><input type=\"text\" id=\"category$category_id\" name=\"category$category_id\" value=\"$category_sequence\" style=\"width: 25px;\" /></td>";
What should be the "name" in this side, and how to reach them from the $_POST on the other side?
In PHP, take a look what you have from your form so far:
<?php
print_r($_POST);
?>
This code will show you what you have. Then you can access any field by its name:
<?php
$variable = $_POST['field_name'];
?>
Be sure to check if there is any POST data was sent:
<?php
if (isset($_POST) && is_array($_POST))
{
// ...
}
?>
Be sure that you have needed field sent by POST form:
<?php
$variable = (array_key_exists('field_name', $_POST) ? $_POST['field_name'] : '');
?>
Finally I got results.
I should use this way:
print "<input type="text" name="cat[]" value="$category_sequence" />"
Then an array ($_POST['cat']) will be created I can iterate through.
Or:
print "<input type="text" name="cat[$catId]" value="$category_sequence" />"
Again, iteration.
On the server side, if I stay on my original idea:
$i=1;
while(isset($_POST['cat'.$i]))
{
print "There is "cat".$i item, it is processable."
$i++;
}
All I wanted was this... thank you.
The issue I have been experiencing deals with input from HTML which was generated using PHP echo statements. Here is the function I have that outputs the form:
function confirm_recipients()
{
echo "<form action = ' ' name ='email_options' method='post'>";
echo "<input type='submit' name='sendRecipients' value='Yes, I want to send the emails' >";
echo "</form>";
}
Later on in the same PHP page, I call the function and then check to see if the submit button was set.
confirm_recipients();
if (isset($_POST['sendRecipients']))
{
//perform actions
}
However, this code is not functional seeing as even when the submit button is set (clicked by the user), the if statement block is never executed. Perhaps there is an issue with posting from the same file I want to "read in" from? Thanks for any advice.
Updates
Thank you for such immediate response. Sadly none of the suggestions have worked (removing the space in the action value or the suggestion made by user623952). No errors have been reported, the button is just failing to be set. I am looking for other places in the file that might have errors, perhaps in the order I call the function.
This works fine for me:
<?php
print "<pre>".print_r($_POST,true)."</pre>";
confirm_recipients();
function confirm_recipients() {
echo "<form action = ' ' name ='email_options' method='post'>";
echo "<input type='submit' name='sendRecipients' value='Yes, I want to send the emails' >";
echo "</form>";
}
if (isset($_POST['sendRecipients']))
{
print "<br/>sendRecipients is set!<br/>";
}
?>
I think your problem might be somewhere else in the code.
It's okay to POST the form data to the same script that contains the form. Change the action attribute to the URL of the script, do not set it to whitespace, which is what you did.
I don't think the value of a submit input is sent as part of the POST. Try using an input type="hidden" with the name 'sendRecipients'.