How can I see $_POST variable from a form using JQuery? - php

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.

Related

jQuery send data AJAX after the time is up

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?

Input from PHP generated form is not being recorded

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'.

Approved method to navigate between pages on same website

I have researched many places to find an answer to this question, but they never quite answer my real question: What is the best/approved way to move to a new page within the same website? I have read that it is bad to use window.location because search engines will think you are hiding something. But, when I don't want to open a new window (window.open), then I don't know how else to do it. I use href anchors in links and form actions, where appropriate. But when I have menus or buttons with onclick, then I need something else.
Here's an snippet of my code:
my javascript: (with one option commented)
function gotoCat() {
var catcdF = document.catSelect.catcd.value;
<?php
echo "window.location.href='http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF; ";
/*
echo "window.open('http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF,'','resizable=1,scrollbars=1,toolbar=1,top=50,left=300,width=950,height=800,location=0'); ";
*/
?>
}
My dynamic SELECT list in a form (within PHP):
echo " <select name='catcd' id='catcd' size='8' onclick=gotoCat() > \n";
// display list of categories
if ($numcats == 0) { // print message text only
echo "<option value='0' >".$catMsg."</option> \n";
}
else {
for ($i=1; $i<=$numcats; $i++) {
$catcd_db = $catAry[$i][1];
$catName_db = $catAry[$i][2];
echo "<option value='".$catcd_db."'> ".$catName_db." </option> \n";
}
}
echo "</select>";
So, as you can see, I just want a method to allow the user a choice and then automatically go to the correct web page once selected. This is not always in a select list. Often it's when they want to exit or get an error:
if (mysqli_connect_errno()) {
echo "<br/> <p style='text-align:center;'> <button type='button'
class='buttonStyle' style='padding: 4px 20px;' value='Exit' ";
echo "onClick=\"window.location.href='http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev'\" > ";
echo "Exit </button></p> ";
}
I cannot use "go back" because they need to go to a prior page, not the form they came from.
So, unless my navigation methods are really off-the-mark, I guess I need to know the acceptable method for using javascript onClick to move to the next page in the same website. Is window.location okay, or should I use something else?
Any opinions or suggestions are welcome!
To navigate to another page using Javascript, use:
window.location.href = "url";
That's how it's done and there's nothing wrong about it.
For the sake of argument, you could create a hidden link and simulate a click on it, but as I said, there's really no need.
You can use php header('location') instead:
<form action="submit.php">
<input type="hidden" value="test" name="hidden1" />
<input type="submit" Value="Exit" ... />
submit.php
<?php
if (isset($_POST['hidden1'])
{
header('Location: http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev');
exit;
}
?>
More info about header('Location ...');:
http://php.net/manual/en/function.header.php
Instead of a hidden, you use your select's value and get it via the $_POST variable.

improve my PHP user interaction

I have a situation where a user fills out 1 of 2 forms on a registration page and is sent to a software download page. If they sign up as a new user, form is processed inserted into a MySQL database and they go to the page no problem.
Here is my issue. If they are a returning user and enter a license key, the processor script checks to see if its valid against the database and if it is it sends them to the software download page. If it is NOT a valid license key (heres what I dont like) the screen goes to the url of the script, page is white, an alert pops down telling them its not a valid license key and they are returned to the registration page to try again. I hate this. I need to figure out a way to either pop the alert on the registration page w/o leaving it or better yet display some kind of message on the page. One drawback is that the script is and always will be on a different server than my forms. Ive tried curl and had success with other situations but can't close the MySQL connection on this one. Is there another way to achieve some semblance of "cross domain AJAX" I would really like it to not go to the script url/white page/alert then return them. I would like it to happen all on one page. Here is that part of my script:
if ($_POST['license_code'] != "")
{
$result = mysql_query("(//mysql stuff here)");
if (($row = mysql_fetch_assoc($result)))
{
header("Location: http://" . $redirect);
}
//here is the part I dont like
else
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The license ID you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
}
mysql_close($link);
}
//I use jquery valiadate.js for CS validation, but realize this is necessary and would like it to behave like the desired result for the above
else
{
if (strpos($_POST['email1'], '#') === false)
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The email address you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
return;
}
thx
Is it possible to remove the alert and when you redirect to registrationpage.php also send a parameter using the redirect url and popup an alert or error message after the redirect ?
Look into using AJAX. jQuery has a great API for this:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/load/
EDITIED - For cross-domain
You could do something like this:
<div id="results"></div>
<script type="text/javascript">
$("#the_form").submit(function() {
$.getJSON("http://remote.domain/script/to/validate.php?data=" + escape($(this).serialize()) + "&callback=?", function(data) {
$("#results").html(data);
});
return false;
});
</script>
This will (once the IDs are pointed at the correct elements) intercept the form submission, pull together the values from the form (through the serialize() function), and shoot it out to the validation script via AJAX. The output of the script is displayed in the #results div.
Hope this helps!

how to collaborate between javascript and php

i am calling a javascript for image gallery and php on a single page.
let me show you some code to make things clear:
PHP
echo "<form method = post action = 'user_submit.php'>";
// get possible answers using question ID
$query = "SELECT aid, atitle FROM answers WHERE qid = '$qid' ORDER BY aid ASC";
$result = mysql_query($query) or die("ERROR: $query.".mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_object($result)) {
echo "<div id=captionbox style='width: 110px;float:left;color:#FFF;text-align:center;'>";
echo "<a href='#' class='thumb' ><img class='thumb-img' src='images/roadies/th".$row->aid.".jpg' /> </a>";
echo "<input type = hidden name = aid id = rd".$row->aid." value = ".$row->aid.">".$row->atitle."</input>";
echo "</div>";
}
echo "<input type = hidden name = qid value = '".$qid."'>";
echo "<br/>";
echo "<input type = submit name = submit value = 'Vote!'>";
}
echo '</form>';
}
the above code fetches object ids and places jpeg images accordingly (thumbnails).
now when i click on these thumbnails the javascript opens an overlay to display the large version. i want to pass the value of $row->aid to javascript.
then from the javascript i want to fill out a form and pass the $row->aid and the form to user_submit.php to add it to the DB.
i am new to php. please help me out.
You can write a variable, object or array literal declaration to your javascipt file or to a <script> element in a HTML file, as kiamlaluno correctly said. but i would suggest, (1) use the var keyword and (2) consider using a separate namespace.
If you have several things to tell the JS, it's handy to put them in a PHP hash and json_encode() and then write the encoded string to your output. This takes care of the namespace and correct escaping of the data. For example:
<?php
$jsdata = array(
'this' => "It\"s gone.\nWhat?",
'that' => array(1,3,2),
'another' => 0x2f );
$jsdata = json_encode($jsdata);
?>
<html>
<head></head>
<body>
<script type="text/javascript">
var thedata = <?php echo "$jsdata;" ?>
window.console.log(thedata);
</script>
</body>
</html>
Try that and look at the javascript console to see if it works.
EDIT: Another reason I like this approach is because you can use PHP's array handling conveniences to construct an arbitrarily complex $jsdata while not worrying about escaping issues and only consuming one global JS object name.
First of all, you don't need to echo everything. Something like this is just as valid:
while ($row = mysql_fetch_object($result)) { ?>
<div id=captionbox style='width: 110px;float:left;color:#FFF;text-align:center;'>
<a href='#' class='thumb' ><img class='thumb-img' src='images/roadies/th<?=$row->aid?>jpg' /> </a>
<?php ...
In this case, uses php's echo shortcut tag to echo the value of the contents. It is equivalent to <?php echo $some_variable ?> .
Second, I don't actually see any JavaScript code in your question. But to accomplish what it sounds like you want to do, you can make an HTML form with a SINGLE hidden input whose value is set by selecting one of your images, and then have that form submit to user_submit.php.
The value-setting can happen in a number of ways, which is really up to you. But suppose you wanted it to happen when the user clicked an image. Then you could set the onClick event inside the img tag, like onclick="hidden_input.value='<?=$row->aid?>'"
There are many ways to pass data to JavaScript; the easier is the following:
<script>
aid = <?php print $row->aid; ?>
// The rest of the script
</script>
I only wrote the necessary code, without even write all the attributes for the tag SCRIPT.

Categories