Send data from AJAX function to PHP file - javascript

I have an AJAX function that take data form a submit form and should pass varaibles to process.php
index.html is the main page
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>League of Legends Straw Poll</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">Game Straw Poll</h1>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<!-- FORM -->
<form name="form" id="form" method="post">
<div class="row">
<div class="col-md-12">
<!-- GAME -->
<select class="form-control" id="game-group" name="game" onchange="ChangeBackground();">
<option selected disabled>Select your Game...</option>
<option value="League_of_Legends">League of Legends</option>
<option value="Heartstone">Hearthstone</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<!-- QUESTION -->
<div class="input-group" id="question-group">
<input type="text" class="form-control" name="question" id="question" placeholder="Start typing your question...">
<span class="input-group-addon">
<i class="glyphicon glyphicon-question-sign"></i>
</span>
</div>
</div>
</div>
<br>
<div class="row">
<!-- OPTIONS -->
<div class="form-group form-group-options col-md-12 col-sm-12 col-xs-12">
<div class="input-group input-group-option col-md-12 col-sm-12 col-xs-12" id="options-group">
<input type="text" name="option[]" id="option" class="form-control" placeholder="Options...">
<span class="input-group-addon input-group-addon-remove">
<span class="glyphicon glyphicon-remove"></span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<!-- CHOICE -->
<div class="checkbox" id="choice-group">
<label>
<input type="checkbox" id="choice" name="choice" value="Yes">Allow multiple choice
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-primary btn-lg pull-left" name="submit_button" id="submit_button" data-toggle="modal" data-target="#myModal">Create Poll</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Poll created</h4>
</div>
<div class="modal-body">
<p>Share it: http://gamepoll.net/<?php echo $rand_value; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary">Invia</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type='text/javascript' src='js/addfield.js'></script>
<script type='text/javascript' src='js/changebackground.js'></script>
<script type='text/javascript' src='magic.js'></script>
</body>
</html>
This is magic.js file
$(document).ready(function()
{
$("#submit_button").click(function()
{
var game = $("#game-group:selected").val();
var question = $("#question").val();
var option = $("#option[]").val();
var choice = $("#choice").val();
if (game == '' || question == '' || option == '' || choice == '')
{
alert("Insertion Failed Some Fields are Blank....!!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("process.php", {
game1: game,
question1: question,
option1: option,
choice1: choice
},
function(data)
{
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
And this is process.php file
<?php
//Include configuration file
include('includes/config.php');
//Define variables
$game2=$_POST['game'];
$question2=$_POST['question'];
$option2=$_POST['option'];
$choice2=$_POST['choice'];
//Generate random number
$rand_value=rand();
//Create temporary folder
mkdir($rand_value);
//Copy page of Ask Poll
copy('page.php', $rand_value . '/page.php');
rename($rand_value . '/page.php', $rand_value . '/index.php');
//Add data into database
mysql_connect($db_host, $db_username, $db_password) or die ("Errore di connessione!");
mysql_select_db($db_name) or die ("Impossibile selezionare database!");
$sql1="CREATE TABLE `" . $rand_value . "` (Question VARCHAR(200), Options VARCHAR(200), Choice INT(11))";
mysql_query($sql1) or die ("Impossibile eseguire la query!");
//Count number of Options available
$count=count($option);
for ($i=0; $i<($count-1); $i++)
{
${$sql . $i}="INSERT INTO `" . $rand_value . "` (Question, Options, Choice) VALUES ('$question2', '$option2[$i]', '$choice2')";
mysql_query(${$sql . $i});
}
?>
The problem is that the AJAX function doesn't pass data to process.php in fact i don't see any folder into my server or data saved into the database

change
var option = $("#option[]").val();
to
var option = $("#option").val();
you have assign [] operater in id selecter

Your javascript property names dont match your php array keys:
{
game1: game,
question1: question,
option1: option,
choice1: choice
}
$game2=$_POST['game'];
$question2=$_POST['question'];
$option2=$_POST['option'];
$choice2=$_POST['choice'];
change one or the other, eg:
{
game: game,
question: question,
option: option,
choice: choice
}

The only issue I see is when calling the POST vars in your php you need to use the key names from your object. Not the variable names.
//Define variables
$game2=$_POST['game1'];
$question2=$_POST['question1'];
$option2=$_POST['option1'];
$choice2=$_POST['choice1'];
Hope this helps!

Related

onClick function not creating option in select menu

function getOption(){
var select = document.getElementById("dynamic-select");
if(select.options.length > 0) {
var option = select.options[select.selectedIndex];
alert("Text: " + option.text + "\nValue: " + option.value);
} else {
window.alert("Select box is empty");
}
}
function addOption(){
var select = document.getElementById("dynamic-select");
select.options[select.options.length] = new Option('New Element', '0', false, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.pac-container {
z-index: 10000 !important;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<h2>Shipping Method</h2>
<form>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="optradio" checked>Deliver To *</label>
</div>
</div>
<div class="form-group">
<select id="dynamic-select">
<option value="None">Select Shipping</option>
</select>
</div>
<div class="form-group">
<a data-toggle="modal" data-target="#myModal">Add Delivery Address</a>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span><i class="fa fa-map-marker" aria-hidden="true"></i></span>Add your Delivery Details</h4>
</div>
<div class="modal-body">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Address</h3>
</div>
<div class="panel-body">
<input id="autocomplete" placeholder="Enter your address"
onFocus="geolocate()" type="text" class="form-control">
<br>
<div id="address">
<div class="row">
<div class="col-md-6">
<label class="control-label">Street address</label>
<input class="form-control" id="street_number">
</div>
<div class="col-md-6">
<label class="control-label">Route</label>
<input class="form-control" id="route">
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="control-label">City</label>
<input class="form-control field" id="locality">
</div>
<div class="col-md-6">
<label class="control-label">State</label>
<input class="form-control" id="administrative_area_level_1">
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="control-label">Zip code</label>
<input class="form-control" id="postal_code">
</div>
<div class="col-md-6">
<label class="control-label">Country</label>
<input class="form-control" id="country">
</div>
</div>
</div>
<button type="submit" onclick="addOption()">Add NEW</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
I'm new to Javascript and in this example, basically I have created a Shipping Method Page. In the "ADD Delivery Address" link, on clicking there is a address form which needs to be filled out and after pressing the ADD NEW button, all the address form data should appear in the select menu option like in the picture below. But I'm unable to do so. Can someone please enlighten me on his. It would be a immense help to me. Thank you
This is line bug, id newopt don't exist in html.
var newopt = $('#newopt').val();

Auto-suggest search box using PHP and AJAX

I tried a downloaded code for auto-suggest search box but it didn't work. It does not display anything from my database. I'm still new in this programming language especially in using AJAX and JavaScript.
Here's my code:
dbcon2.php
<?php
$con2['host'] = 'localhost';
$con2['user'] = 'root';
$con2['pass'] = 'thirteen';
$con2['db'] = 'pis';
$sel2 = mysql_connect($con2['host'], $con2['user'], $con2['pass']);
mysql_select_db($con2['db'], $sel2);
mysql_set_charset("utf-8");
$datab2 = $con2['db'];?>
set_creditlimit.php
<!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>Autocomplete search using php, mysql and ajax</title>
<link rel="stylesheet" type="text/css" href="assets/css/custom.css">
<script type="text/javascript" src="assets/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if (searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click", function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("</div>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function(e){
var $clicked = $(e.target);
if (! $clicked.hasClass("search")) {
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
</head>
<body>
<div id="page-wrapper">
<div id="page-inner">
<div class="row">
<div class="col-md-12">
<h2>ACL</h2>
</div> <!-- <div class="col-md-12"> -->
</div> <!-- <div class="row"> -->
<hr />
<div class="row">
<div class="col-md-12">
<!-- Start of Form -->
<div class="panel panel-success">
<div class="panel-heading">
Set-up Allowable Credit Limit
</div> <!-- <div class="panel-heading"> -->
<!-- End of Heading -->
<!-- Start of Body -->
<div class="panel-body">
<form class="form-horizontal">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<label>Search Employee:</label>
<input type="text" id="searchid" placeholder="Search Employee" class="search">
</div>
<div id="result"></div>
</div>
<br />
<!-- ------------- -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<label>Position:</label>
<input class="form-control" disabled>
</div>
</div>
<br />
<!-- ------------- -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<label>Department:</label>
<input class="form-control" disabled>
</div>
</div>
<br />
<!-- ------------- -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<label>Business Unit:</label>
<input class="form-control" disabled>
</div>
</div>
<br />
<!-- ------------- -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<label>Allowed Credit Limit:</label>
<input class="form-control">
</div>
</div>
<br />
<br />
<!-- ------------- -->
<div class="control-group">
<div class="controls">
<center>
<button class="btn btn-success btn-lg"><i class="glyphicon glyphicon-hand-right fa-1x"> Submit</i></button>
</center>
</div>
</div>
</form>
</div> <!-- <div class="panel-body"> -->
</div> <!-- <div class="panel panel-success"> -->
</div> <!-- <div class="col-md-12"> -->
</div> <!-- <div class="row"> -->
</div> <!-- <div id="page-inner"> -->
</div> <!-- <div id="page-wrapper"> -->
</body>
</html>
search.php
<?php
include('dbcon2.php');
if ($_POST)
{
$q = $_POST['search'];
$sql_res = mysql_query("SELECT emp_id, name from employee3 where emp_id like '%$q%' or name like '%$q%' order by emp_id LIMIT 5 ");
while ($row = mysql_fetch_array($sql_res))
{
$emp_id = $row['emp_id'];
$name = $row['name'];
$b_emp_id = '<strong>'.$q.'</strong>';
$b_name = '<strong>'.$q.'</strong>';
$fina_emp_id = str_ireplace($q, $b_emp_id, $emp_id);
$final_name = str_ireplace($q, $b_name, $name);
?>
<div class="show" align="left">
<span class="name"><?php echo $fina_emp_id; ?></span>
</div>
<?php
}
}
?>
You are passing the wrong data format in the ajax call.
It should be like this:
data: { search: searchid }
try this and it should work i believe.
Refer this: http://api.jquery.com/jquery.ajax/

Don't refresh page after submit

I have a site http://gamepoll.net and I want that when I click Create Poll, the page doesn't refresh. This is the HTML code:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>League of Legends Straw Poll</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">Game Straw Poll</h1>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<form name="submitForm" id="submitForm" action="" method="post">
<div class="row">
<div class="col-md-12">
<select class="form-control" id="theme" name="game" onchange="ChangeBackground();">
<option selected disabled>Select your Game...</option>
<option value="League_of_Legends">League of Legends</option>
<option value="Heartstone">Hearthstone</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<div class="input-group">
<input type="text" class="form-control" name="question" id="question" placeholder="Start typing your question...">
<span class="input-group-addon">
<i class="glyphicon glyphicon-question-sign"></i>
</span>
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-group form-group-options col-md-12 col-sm-12 col-xs-12">
<div class="input-group input-group-option col-md-12 col-sm-12 col-xs-12">
<input type="text" name="option[]" id="option" class="form-control" placeholder="Options...">
<span class="input-group-addon input-group-addon-remove">
<span class="glyphicon glyphicon-remove"></span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="checkbox">
<label>
<input type="checkbox" id="choice" name="choice" value="Yes">Allow multiple choice
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit|button" class="btn btn-primary btn-lg pull-left" name="submit_button" id="submit_button" onclick="SubmitForm();" data-toggle="modal" data-target="#myModal">Create Poll</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Poll created</h4>
</div>
<div class="modal-body">
<p>Share it: http://gamepoll.net/<?php echo $rand_value; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary">Invia</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type='text/javascript' src='js/addfield.js'></script>
<script type='text/javascript' src='js/changebackground.js'></script>
<script type='text/javascript' src='norefresh.js'></script>
</body>
</html>
JS Code
function SubmitForm(e) {
e.preventDefault();
var game = $("#game").val();
var question = $("#question").val();
var option = $("#option").val();
$.post("submit.php", { game: game, question: question, option: option },
}
submit.php Code
<?php
//Include configuration file
include('includes/config.php');
//Define variables
$question=$_POST['question'];
$game=$_POST['game'];
$option=$_POST['option'];
$choice=$_POST['choice'];
//Generate random number
$rand_value=rand();
//Create temporary folder
mkdir($rand_value);
//Copy page of Ask Poll
copy('page.php', $rand_value . '/page.php');
rename($rand_value . '/page.php', $rand_value . '/index.php');
//Add data into database
mysql_connect($db_host, $db_username, $db_password) or die ("Errore di connessione!");
mysql_select_db($db_name) or die ("Impossibile selezionare database!");
$sql1="CREATE TABLE `" . $rand_value . "` (Question VARCHAR(200), Options VARCHAR(200), Choice INT(11))";
mysql_query($sql1) or die ("Impossibile eseguire la query!");
//Count number of Options available
$count=count($option);
for ($i=0; $i<($count-1); $i++)
{
${$sql . $i}="INSERT INTO `" . $rand_value . "` (Question, Options, Choice) VALUES ('$question', '$option[$i]', '$choice')";
mysql_query(${$sql . $i});
}
?>
All works perfectly but the only problem is that when i click Create Poll button, the browser redirect me to submit.php blank page
UPDATE
This code doesn't work
function SubmitForm(e) {
e.preventDefault();
var game = $("#game").val();
var question = $("#question").val();
var option = $("#option").val();
$.post("submit.php", { game: game, question: question, option: option }
return false;
}
Can you write me an AJAX function as the last comment says?
place return false; at the end of your SubmitForm function and loose the comma at the end of the last sentence
function SubmitForm(e) {
e.preventDefault();
var game = $("#game").val();
var question = $("#question").val();
var option = $("#option").val();
$.post("submit.php", { game: game, question: question, option: option }
return false;
}
Either place return false; at the end of the function SubmitForm or change onclick="SubmitForm();" to onclick="SubmitForm(); return false;"
You can just add onsubmit="return false;" to your form:
<form onsubmit="return false;">
*****
****
</form>
use Ajax function if you want that the page doesn't refresh on click the "Create Poll" button.
It loads the part of the page without refresh the whole page.

How to keep the email and password if the browser is refreshed in my keep logged in function?

I want to do is to keep the email and password in the modal dialog login page if I click the checkbox button and if I refresh the same page and click the modal dialog again the email and password should be still there.
My problem is if I sign in in my login modal dialoge box and checked the keep me logged checkbox and click the button and refreshed the page again the email and password I've typed are gone it wasn't there anymore.
Does anyone here know how to keep what I typed in the email and password in my modal dialog box if I checked the checkbox keep me logged in button?
Whole html code:
<?php
session_start();
$unm=isset($_SESSION['email'])?$_SESSION['email']:'default_username';
$pwd=isset($_SESSION['password'])?$_SESSION['password']:'default_password';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.css" />
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="bootstrap/js/jquery-1.11.0.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript"> <!--submit form script-->
$(document).ready(function(){
$('#sumbit').on('click', function(){
window.location.replace("profile.php");
$('.modal').modal('hide');
});
$('[name="chkbox"]').on('click', function(){
$.post( "savestate.php", { email: $('[name="email"]').val(), email: $('[name="password"]').val() }).done(function( data ) {
alert( "Data Loaded: " + data );
});
});
});
</script>
</head>
<body>
<a data-toggle="modal" href="#myModal"><span class="glyphicon glyphicon-user"></span> Login</a>
<div class="container">
<div class="row">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h5 class="modal-title">PLEASE ENTER YOUR EMAIL ADDRESS AND PASSWORD TO LOG IN.</h5>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<input type="text" name="email" value="<?php echo $unm; ?>" class="form-control" placeholder="Enter Email Address..." />
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input type="password" name="password" value="<?php echo $pwd; ?>"" class="form-control" placeholder="Enter Password..." />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="checkbox" name="chkbox" value="staylogged" class="checkbox-inline" />
<label> Keep me logged in</label> <b>|</b>
Forgot your password?
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" id="submit" name="login" class="btn btn-primary" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-user"></span> Login</button>
<button type="button" id="show_signup_md" class="btn btn-info" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-list-alt"></span> Register</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
savestate.php
<?php
session_start();
$_SESSION['email']=$_POST['email'];
$_SESSION['password']=$_POST['password'];
$unm=isset($_SESSION['email'])?$_SESSION['email']:'default_username';
$pwd=isset($_SESSION['password'])?$_SESSION['password']:'default_password';
?>
You set variables in server side when user clicks check button.Probably by using AJAX.
And then use them in your page when you display the page.
Here is jquery:
$(document).ready(function(){
$('#sumbit').on('click', function(){
window.location.replace("profile.php");
$('.modal').modal('hide');
});
$('[name="chkbox"]').on('click', function(){
if(!$(this).attr('checked'))return;
$.post( "/savestate.php", { email: $('[name="email"]').val(), password: $('[name="password"]').val() }).done(function( data ) {
// alert( "Data Loaded: " + data );
});
});
});
Here is savestate.php
session_start();
$_SESSION['email']=$_POST['email'];
$_SESSION['password']=$_POST['password'];
You can reuse in your php page as
$unm=isset($_SESSION['email'])?$_SESSION['email']:'default_username';
$pwd=isset($_SESSION['password'])?$_SESSION['password']:'default_password';
Why don't use instead jQuery's plugin for cookies?
http://plugins.jquery.com/cookie/
In general terms, it is a really bad practice to store the password in the cookie but if you wan't to do it, I'm no one to tell you not to do it.
Another better solution will be store the information in the session of PHP. Here is a good tutorial of this. Although a still better solution will be store the session in database, so your app is stateless.
Using jQuery's plugin will be as easy as:
jQuery(function () {
$("#email").val($.cookie("unm"));
$("#password").val($.cookie("pwd"));
});
In this way, if there is something in the cookie, the value will be that, otherwise, will be blank. Or you can do
$("#email").val($.cookie("unm") || "Default value for usermane");
To set a default value if the return of that cookie is null (or empty).
You can also use local storage (http://www.w3schools.com/html/html5_webstorage.asp) but I recommend using a server side option.

Echo / Display php errors via javascript

I have a form which i validate via php. this is how i do it:(example is for one 1 field)
elseif (ctype_alpha($firstname) != true)
{
$err_alpha_firstname = "First Name cannot contain numbers";
}
If in case the user does use an alpha numeric firstname, i display the error as :
<p><input type="text" class="span2" maxlength = "20" name="firstname" required id="firstname" placeholder="First Name"></p>
<?php if (isset($err_alpha_firstname)) {echo $err_alpha_firstname;}?>
It all works fine. however since this validation is server side via php, inorder for the errors to show up, i have to submit the form, which then reloads( since the form submits to the page itself) and then the errors are displayed. Now I want those errors which are stored in a php variable ex:$err_alpha_firstname , to be displayed instantaneously via javascript or ajax (i dont know anything about either of the languages so pardon me please). Is there a simple script that would let me display those errors on the fly? I know php is server side and javascript is client side so there might be an issue.
html file:
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">
<title>Fantasy Football</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="bootstrap/css/jumbo.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="jumbotron.css" rel="stylesheet">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Fantasy Football</a>
</div>
<div class="navbar-collapse collapse">
<form class="navbar-form navbar-right" method="post" action="checkuser.php" name="check_form">
<div class="form-group">
<input type="text" placeholder="Username" name ="username" id="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" name="password" id="password" class="form-control">
</div>
<input type="hidden" name="action" value="submit" />
<button type="submit" class="btn btn-success">Sign in</button>
Forgot Password?
</form>
</div>
</div>
</div>
<div class="jumbotron">
<div class="container">
<h1>Fantasy Football</h1>
<p>Bring out the football manager in you!</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Register »
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">New User Registration</h4>
</div>
<div class="modal-body">
<form class="form-inline" method="post" action="<?php echo $_SERVER['PHP_SELF']?>" name="login_form">
<span id="formerror" class="error"></span>
<p><input type="text" class="span2" maxlength = "20" name="firstname" required id="firstname" placeholder="First Name"></p>
<?php if (isset($err_alpha_firstname)) {echo $err_alpha_firstname;}?>
<p><input type="text" class="span2" maxlength = "20" name="lastname" required id="lastame" placeholder="Last Name"></p>
<?php if (isset($err_alpha_lastname)) {echo $err_alpha_lastname;}?>
<p><input type="text" class="span2" maxlength = "20" name="username" required id="username" placeholder="Username"></p>
<?php if (isset($err_ln_username)) {echo $err_ln_username;}?>
<?php if (isset($err_empty_username)) {echo $err_empty_username;}?>
<?php if (isset($err_alnum_username)) {echo $err_alnum_username;}?>
<?php if (isset($err_unp)) {echo $err_unp;}?>
<p class="help-block" style="font-size:12px"> Username should be between 4-20 characters long.</p>
<p><input type="password" class="span2" name="password" placeholder="Password"></p>
<?php if (isset($err_unp)) {echo $err_unp;}?>
<?php if (isset($err_ln_password)) {echo $err_ln_password;}?>
<?php if (isset($err_alnum_password)) {echo $err_alnum_password;}?>
<p class="help-block" style="font-size:12px"> Password must be between 4-20 characters long. Must be alpha-numeric</p>
<p><input type="password" class="span2" name="password_conf" placeholder="Re - Enter Password"></p>
<?php if (isset($err_passwordconf)) {echo $err_passwordconf;}?>
<p><input type="email" class="span4" name="emailid" required id="emailid" placeholder="Email ID"></p>
<p><input type="text" class="span2" name="team_name" required id="team_name" placeholder="Team name"></p>
<p class="help-block" style="font-size:12px"> Select your Unique team name.</p>
<p>
<select class="secret_question">
<option>Select one of the below ....</option>
<option value ="0">The name of the city where you were born</option>
<option value ="1">The name of your first pet</option>
<option value ="2">What is your mother's maiden name</option>
</select>
</p>
<p><input type="text" class="span2" name="secret_answer" required id="secret_answer" placeholder="Secret Answer"></p>
<p><input type="hidden" value="submit" /><br />
<button type="submit" name="action" value = "submit" class="btn btn-primary">Register</button></p>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<h2>Rules</h2>
<p>Rules of the Game </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Meet The Developers</h2>
<p>Everyones name get mentioned here </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Contact Us</h2>
<p>have an issue with the game. Click here to contact us.</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
</div>
<hr>
<footer>
<p>© B561 Project Fall 2013</p>
</footer>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<?php include('newuseradd.php');?>
</body>
</html>
You could either use straight JavaScript or AJAX to PHP.
I'm going to show you the straight JS method.
You'd do something like this for each input.
var hint = $("#fname-hint");
var fname = $("#firstname");
fname.on("change", function(){
if (!this.value.match(/\d+/g)) { // dosen't contain numbers
hint.html("");
fname.removeClass("error");
}
else {
fname.addClass("error");
hint.html("Your name can't contain numbers!");
}
});
Now when the form is submitted, make sure there are no errors:
var form = $("#form");
form.submit(function(e) {
var inputs = form.children("input");
inputs.each(function(){
var input = $(this);
if (!input.hasClass("error")) {
alert("Errors in form!");
input.select();
e.preventDefault();
break;
}
});
});
I use the jQuery $.post() function and return json from my php code:
function fail ($message){
die(json_encode(array('status'=>'fail', 'message'=>$message)));
}
function success ($message){
die(json_encode(array('status'=>'success', 'message'=>$message)));
}

Categories

Resources