Creating a register.html form where the user is prompt to enter a name, email and password, then clicks submit which triggers a php script to check is the email enter is already in use, and if it is not already in use, it places the users data in the appropriate fields in the table 'users-form' on mysql.
My issue is that AJAX isn't submitting the form. The javascript that states "Fill in empty fields" works fines. I don't know what I am doing wrong.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Reg Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div class="header">
<div>Register form</div>
</div>
<form action="">
<p> Enter name, email and password</p>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">
<label>Password :</label>
<input id="password" type="password">
<input id="submit" type="button" value="Submit">
</form>
//Internal Javascript
<script>
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
//success message when information is stored in database.
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password;
if (name == '' || email == '' || password == '') {
alert("Fill in empty fields");
} else {
//submits form
$.ajax({
type: "POST",
url: "connect.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
</script>
</body>
</html>
AJAX connect.php:
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("mydatabase", $connection); // Selecting Database
//Fetching Values from URL
$name2=$_POST['name1'];
$email2=$_POST['email1'];
$password2=$_POST['password1'];
//Insert query
$query = mysql_query("insert into users-form(name, email, password) values ('$name2', '$email2', '$password2')");
echo "Submitted!";
mysql_close($connection); // Connection Closed
?>
Any ideas? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Reg Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<script src="js/theme.init.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<div class="header">
<div>Register form</div>
</div>
<form action="" id="form">
<p> Enter name, email and password</p>
<label>Name :</label>
<input id="name" name="name1" type="text">
<label>Email :</label>
<input id="email" name="email1" type="text" required>
<label>Password :</label>
<input id="password" name="password1" type="password" required>
<input id="submit" type="button" value="Submit">
</form>
//Internal Javascript
<script type="text/javascript">
$(document).ready(function (e){
$("#form").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "connect.php ",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(result) {
alert(result);
}
});
return false
}));
});
</script>
</body>
</html>
Your javascript code is fine the problem is mysql has deprecated instead you can use mysqli so your connection could be something like this:
$con = mysqli_connect("localhost","username","password","dbname");
$name2=$_POST['name1'];
$email2=$_POST['email1'];
$password2=$_POST['password1'];
$query = mysqli_query($con, "insert into `users-form` (name, email, password) values ('$name2', '$email2', '$password2')");
if ($query) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
Related
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&email1='+ email + '&password1='+ password + '&contact1='+ contact;
if(name==''||email==''||password==''||contact=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="css/refreshform.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div id="mainform">
<h2>Submit Form Using AJAX and jQuery</h2> <!-- Required div Starts Here -->
<div id="form">
<h3>Fill Your Information !</h3>
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">
<label>Password :</label>
<input id="password" type="password">
<label>Contact No :</label>
<input id="contact" type="text">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
This is what I have in ajaxsubmit.php
$host = "myhost";
$user = "myusername";
$password = "******";
$database = "thisismydb";
$connection = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Fetching Values from URL
$name2=$_POST['name1'];
$email2=$_POST['email1'];
$password2=$_POST['password1'];
$contact2=$_POST['contact1'];
//Insert query
mysqli_query($connection,"SELECT * FROM databasetable");
mysqli_query($connection,"INSERT INTO databasetable (name, email, password, contact)
VALUES ($name2', '$email2', '$password2','$contact2')");
mysqli_close($connection);
?>
However whenever i click submit it only gives me an alert that shows the code from the ajaxsubmit.php and i dont know what I'm doing wrong D: Help please!
note:i'm using bootstrap3
You need to write <?php tag at top of ajaxsubmit.php
I am sending state,city,zip code to ajax.php file. using jquery.
I am unable to get those values in response
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Jquery Ajax</title>
</head>
<body>
<!------------------------Jquery-------POST DATA----------------------------------------->
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
-->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#id-submit').click(function() {
var reg_state = $('#reg_state').val();
var reg_city = $('#reg_city').val();
var reg_zip = $('#reg_zip').val();
var dataString = 'reg_state='+ reg_state;
//alert(dataString);
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data)
{
//$("#state").html(data);
alert(data);
}
});
});
});
</script>
<!------------------------Jquery-----------POST DATA END------------------------------------->
<form id="registration_form" action="" method="post">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="submit" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
</body>
</html>
This is the ajax.php file , from where i need to send response, and make it visible in div id="state
<?php
if($_POST['reg_state'])
{
echo $_POST['reg_state'];
}
else{
echo 'nothing';
}
?>
Try create an object
var dataString = { reg_state: reg_state, reg_city: reg_city, reg_zip : reg_zip }
I believe your problem lies in the type=submit. Replacing this with type=button gives you the result you want.
I'm unsure why this is, but I'm guessing it type=submit gives extra functionality to the input. The page seems to reload after hitting the submit button.
ps. don't forget you actually need to click the button in order for the function to trigger. Hitting enter after filling out the input fields will do nothing.
When ever we use input['type']="submit" in form
we have to use
$('#id-submit').click(function(e) {
e.preventDefault();
}
Here is the full working code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Jquery Ajax</title>
</head>
<body>
<!------------------------Jquery-------POST DATA----------------------------------------->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#id-submit').click(function(e) {
e.preventDefault();
var reg_state = $('#reg_state').val();
var reg_city = $('#reg_city').val();
var reg_zip = $('#reg_zip').val();
var dataString = { reg_state: reg_state, reg_city: reg_city, reg_zip : reg_zip }
//alert(dataString);
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(data)
{
$("#state").html(data);
// alert('hi');
}
});
});
});
</script>
<!------------------------Jquery-----------POST DATA END------------------------------------->
<form id="registration_form" action="" method="post">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="Response" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
</body>
</html>
ajax_city.php
<?php
if($_POST['reg_state'])
{
echo 'STATE: '.$_POST['reg_state'].'<br/>';
echo 'CITY: '.$_POST['reg_city'].'<br/>';
echo 'ZIP: '.$_POST['reg_zip'].'<br/>';
}
else{
echo 'nothing to respond';
}
?>
I am not able to write to db when creating new registrations.... ! I have a javascript which has both login and register parts and is shown below... This the updated version of the code for both the scripts and the php scripts for login anc
<!DOCTYPE html>
<html>
<head>
<title>Load </title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
Register
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="registerp">
<div data-theme="a" data-role="header">
<h3>Register</h3>
</div>
<div data-role="content">
<form id="registerform" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="fname">First Name:</label>
<input type="text" value="" name="fname" id="fname"/>
</div>
<div data-role="fieldcontain">
<label for="lname">Last Name:</label>
<input type="text" value="" name="lname" id="lname"/>
</div>
<div data-role="fieldcontain">
<label for="uname">User Name:</label>
<input type="text" value="" name="uname" id="uname"/>
</div>
<div data-role="fieldcontain">
<label for="pwd">Enter your password:</label>
<input type="password" value="" name="pwd" id="pwd"/>
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input type="text" value="" name="email" id="email"/>
</div>
<input type="button" data-theme="b" name="submit" id="register" value="Register">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>Welcome Page</h3>
</div>
<div data-role="content">
Welcome
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<script type="text/javascript">
$(document).on('pageinit', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: "action=login&" + $('#check-user').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert('Log on unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
<script type="text/javascript">
$(document).on('pageinit', '#registerp', function(){
$(document).on('click', '#register', function() {
if($('#uname').val().length > 0 && $('#pwd').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'insert.php',
data: "action=register&" + $('#registerform').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert(' Try again later ! Server is busy !');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
</body>
</html>
While my PHP Script is simple as shown below... please help
<?php
$con=mysqli_connect("...............", "...........", ".........","........");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['pwd']);
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES ('$uname', '$fname', '$lname', '$password','$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
if($action == 'register'){
$output = array('status' => true, 'message' => 'Registered');
}
echo json_encode($output);
?>
Insert php script doesnt work while the below register php script works fine.
<?php
// We don't need action for this tutorial, but in a complex code you need a way to determine Ajax action nature
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
// Get username
$username = $_POST['username'];
// Get password
$password = $_POST['password'];
$db = #mysql_connect('..........', '........', '..........') or die("Could not connect database");
#mysql_select_db('users', $db) or die("Could not select database");
$result = mysql_query("SELECT `password` FROM `userdb` WHERE `username`= '$username'");
$r = mysql_fetch_assoc($result);
$pass_ret = $r['password'];
// Lets say everything is in order
if($action == 'login' && $password == $pass_ret){
$output = array('status' => true, 'message' => 'Login');
}
else
{
$output = array('status' => false, 'message' => 'No Login');
}
echo json_encode($output);
?>
The way you are using the insert statement is wrong..and its wrongly encapsulated as #rbcummings said.
You must change
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES ('$uname', '$fname', '$lname', '$password','$email')";
to
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES (".$uname.", ".$fname.", ".$lname.", ".$password.",".$email.")";
without proper intentation you can get errors..so intending ur code can solve ur problem.
Try changing the way your variables are encapsulated. Example:
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES (".$uname.", ".$fname.", ".$lname.", ".$password.",".$email.")";
I am making a web app (android) with phonegap and jquery mobile.
I am trying to send three fields from an html form as json, to a php page which will decode the json string/object (im new to json, ajax, jquery) and add the three fields as a mysql query to a database on my localhost.
My html page looks like this:
<script type="text/javascript">
$(document).ready(function(){
$('#btn').bind('click', addvalues);
});
function addvalues(){
$.ajax({
url: "connection.php",
type: "POST",
data: "id=" + $("#id").val()+"&name=" + $("#name").val() + "&Address=" + $("#Address").val(),
datatype:"json",
success: function(status)
{
if(status.success == false)
{
//alert a failure message
}
else {
//alert a success message
}
}
});
}
</script>
</head>
<body>
<div data-role="header">
<h1>My header text</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" placeholder="ID">
</label>
<label for="name">
<input type="text" id="name" placeholder="Name">
</label>
<label for="Address">
<input type="text" id="Address" placeholder="Address">
</label>
<input type="submit" id "btn" value="Add record" data-icon="star" data-theme="e">
</form>
</div>
</body>
The Question is:
How exactly do i extract the three fields (ID, name, Address) from the string that i have sent to my php file (connection.php)?
connection.php is hosted by my local server.
I am familiar with making connections to database, as also with adding queries to mysql. I only need help with extracting the three fields, as i am new to ajax and jquery and json.
As of now, this is ALL i have done in connection.php:
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
//I do not know how to use the json_decode function here
//And this is how, i suppose, we will add the values to my table 'sample'
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
Please add the relevant code in this file and help me out.
I will be highly obliged.
:)
what you want to do this this
$(document).ready(function () {
$('#btn').on('click', function () {
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
datatype: "json",
success: function (status) {
if (status.success == false) {
//alert a failure message
} else {
//alert a success message
}
}
});
});
});
then in your php do this
//set variables from json data
$data = json_decode($_POST); // Or extract(json_decode($_POST) then use $id without having to set it below.
$id = $data['id'];
$name = $data['name'];
$Address = $data['Address'];
//And this is how, i suppose, we will add the values to my table 'sample'
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
be sure you sanitize those inputs before you insert them though.
use:
$id = json_decode($_POST['id']);
$name = json_decode($_POST['name']);
$Address = json_decode($_POST['Address']);
$sql .= "VALUES ($id, '$name', '$Address')";
in place of :
$sql .= "VALUES ($id, '$name', '$Address')";
use $id_json_encoded = json_encode($_POST['id']);
to encode the posts of the form
then use jquery script like this
<script type="text/javascript">
$(document).ready(function()
{
$("#audit").click(function(){
$.post("/audit_report/"+$('#branch').val()+"/"+$('#ttype').val()+"/"+$('#from').val()+"/"+$('#to').val(),
{
targetDiv:"divswitcher"
}
,
function(data){
$("#imagediv").html('<img src="/public/images/spinner_white.gif"> loading...');
//alert(data);
$("#bodydata").html(data);
$("#imagediv").html('');
// $("#divswitcher").html(data);
});
});
});
this is the complete code that encodes form data and send it to the server using ajax
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script type="text/javascript" charset="utf-8" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#btn").click(function(){
var encoded = json_encode("/audit_report/"+$('#id').val()+"/"+$('#name').val()+"/"+$('#Address').val());
$.post(encoded,
{
targetDiv:"divswitcher"
}
,
function(data){
$("#imagediv").html('<img src="spinner_white.gif"> loading...');
//alert(data);
$("#bodydata").html(data);
$("#imagediv").html('');
// $("#divswitcher").html(data);
});
});
});
</script>
</head>
<body>
<div data-role="header">
<h1>My header text</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" name="id" >
</label>
<label for="name">
<input type="text" id="name" name="name" >
</label>
<label for="Address">
<input type="text" id="Address" name="Address" >
</label>
<input type="button" id="btn" name="btn" value="Add record" />
</form>
</div>
</body>
</html>
<div id="bodydata" class="class">
</div>
I try to post the values from the input field with the jquery.ajax function to a php file. The php part must insert the data into an mysql database, generate a unique pincode and return the pincode by json to the jquery code.
But when submitting the form nothing happens...
When I go directly to the main.php file in my browser, it show me a unique pincode and the php script even insert the pincode in the database. So I think the JSON part goes wrong, but I can't figure out why.
I hope somebody can show me what I'm doing wrong. Any help would be fantastic!
Underneath code is the working code!
HTML part:
<!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>AJAX PHP JSON Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#userForm").submit(function() {
var inputFname = $('#inputFname').attr('value');
var inputLname = $('#inputLname').attr('value');
$.ajax({
type: "POST",
url: "main.php",
data: {inputFname: inputFname,inputLname: inputLname},
dataType: "json",
contentType:"application/json; charset=utf-8",
success: function(data) {
$("p.succesText").html(data.jsCode);
$("form#userForm").hide();
$("div.success").fadeIn();
},
error: function(xhr, status, error) {
$("form#userForm").hide();
$("p.errorHead").html("Something went wrong.");
$("p.errorText").text("ResponseText: " + xhr.responseText
+ "Statuscode: " + xhr.status
+ "ReadyState: " + xhr.readyState);
$("div.error").fadeIn();
}
});
return false;
});
});
</script>
</head>
<body>
<div class="MiddleWhite">
<form id="userForm" method="post" name="userForm" action="">
<label for="inputFname" class="LabelForInput">
Enter your Forename
</label>
<input type="text" name="inputFname" id="inputFname" class="TextInput"
size="20" />
<br />
<br />
<label for="inputLname" class="LabelForInput">
Enter your Surname
</label>
<input type="text" name="inputLname" id="inputLname" class="TextInput"
size="20" />
<br />
<br />
<br />
<button type="submit" class="Button">
Generate code</button>
</form>
<div class="success" style="display: none;">
<p class="succesText">
</p>
<p class="checkCallText">
</p>
</div>
<div class="error" style="display: none;">
<p class="errorHead">
</p>
<p class="errorText">
</p>
</div>
</div>
</body>
</html>
PHP part:
<?php header('content-type: application/json; charset=utf-8');
$log = array();
$varFname = htmlspecialchars($_POST["inputFname"]);
$varLname = htmlspecialchars($_POST["inputLname"]);
//Make Database connection
$db = mysql_connect("192.168.178.254","root","852456");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("Ajax" ,$db);
//Generate code and check if code already exists in the database
do
{
$varCode = rand(10000, 99999);
$dbCheckCode = "";
$dbCheckCode = mysql_query("SELECT * FROM TableAjax WHERE code='$varCode'");
}
while (mysql_fetch_array($dbCheckCode) !== false);
//Save the Form data in the database
$sql = "INSERT INTO TableRecordcall (fname, lname, code) VALUES (".PrepSQL($varFname) . ", " .PrepSQL($varLname) . ", " .PrepSQL($varCode) . ")";
mysql_query($sql);
//Return code to frontend
$log['jsCode'] = $varCode;
echo json_encode($log);
//Clean SQL statement
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
From the JQuery API here
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.
You wrote
<form id="submit" method="post" name="submit" action="">
Try to change id/name of the form.
Also you didn't use
return false;
in summit callback to prevent default form submission. Change your js code like this
$(document).ready(function() {
$("form#submit").submit(function() {
var inputFname = $('#inputFname').attr('value');
var inputLname = $('#inputLname').attr('value');
$.ajax({
type: "POST",
url: "main.php",
data: {inputFname: inputFname,inputLname: inputLname},
dataType: "json",
contentType:"application/json; charset=utf-8",
success: function(data) {
$("p.succesText").html(data.jsCode);
$("form#submit").hide();
$("div.success").fadeIn();
},
error: function(xhr, status, error) {
$("form#submit").hide();
$("p.errorHead").html("Something went wrong.");
$("p.errorText").text("ResponseText: " + xhr.responseText
+ "Statuscode: " + xhr.status
+ "ReadyState: " + xhr.readyState);
$("div.error").fadeIn();
}
});
return false;
});
});
In $.ajax replace
data: {'inputFname': inputFname,'inputLname': inputLname},
by
data: {inputFname: inputFname,inputLname: inputLname},
Hope it helps.