PHP for parsing JSON and adding to database mysql - php

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>

Related

insert to mysql from ajax and php

Hi i am trying to insert data to mysql from ajax with php here is my code can anyone help.
The only error i get is that the data is not insert, in my mysql the values is not pass in.
Where is the problem in my ajax?
or in my php when i pass values.
index.php
<?php include "bd.php"; ?>
<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX and jQuery</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div class="container ">
<form class="form-signin text-center col-md-6" method="post" action="">
<h2 class="form-signin-heading">Please Insert value in</h2>
<div class="form-group">
<label for="name" class="sr-only">Name:</label>
<input type="text" id="name" name="name" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label for="last_name" class="sr-only">Last name</label>
<input type="text" id="last_name" name="last_name" class="form-control" placeholder="Last Name" >
</div>
<div class="form-group">
<label for="email" class="sr-only">email:</label>
<input type="text" id="email" name="email" class="form-control" placeholder="Email" >
</div>
<div class="form-group">
<label for="phone" class="sr-only">Phone:</label>
<input type="text" id="phone" name="phone" class="form-control" placeholder="Phone" >
</div>
<div class="form-group">
<label for="bridge">Select list:</label>
<select class="form-control" id="bridge" name="bridge">
<option>None</option>
<option>eAgent</option>
<option>iArts</option>
<option>Orbit</option>
<option>G&G</option>
<option>EstateWeb</option>
<option>Globalc</option>
</select>
</div>
<div class="form-group">
<label for="comments">Comment:</label>
<textarea class="form-control" rows="5" id="comments" name="comments"></textarea>
</div>
<button type="button" id="submit" class="btn btn-lg btn-primary btn-block" >Register</button>
</form>
<div class="col-md-6">
<h2>Here is tha form with ajax.</h2>
</div>
</div> <!-- /container -->
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").serialize();
var last_name = $("#last_name").serialize();
var email = $("#email").serialize();
var phone = $("#phone").serialize();
var bridge = $("#bridge").serialize();
var comments = $("#comments").serialize();
$.ajax({
type : "POST",
url : "ajax.php",
data : {'name': name,'email': email ,'last_name':last_name,'phone':phone,'bridge': bridge, 'comments': comments},
success : function(result) {
alert(result);
}
});
});
});
</script>
</body>
</html>
Now my file of php where the connection is done.
<?php
/**
* Created by PhpStorm.
* User: erevos13
* Date: 26/6/2017
* Time: 11:13 μμ
*/
//is the databases connection
include "bd.php";
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['name'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$bridge = $_POST['bridge'];
$comments = $_POST['comments'];
$sql = "INSERT INTO info (`id` , `name`, `last_name`, `email `, `phone`, `bridge` , `comments` ) VALUES ( '' , '" . $name . "', '" . $last_name . "','" . $email . "', '" . $phone . "' , '" . $bridge . "', '" . $comments . "')";
$query = mysqli_query($connection, $sql);
if ($query) {
echo "data insert successfully";
} else {
echo "data is not insert";
}
}
The only error i get is the "data is not insert".
You should use console.log() function to check the data in the javascript code.
And read a little bit more about serialize function at here.
Your javascript code should be something like:
$.ajax({
type : "POST",
url : "ajax.php",
data : $("form").serialize();
Try val() in place of serialize().Check code for jquery:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var bridge = $("#bridge").val();
var comments = $("#comments").val();
$.ajax({
type : "POST",
url : "ajax.php",
data : {'name': name,'email': email ,'last_name':last_name,'phone':phone,'bridge': bridge, 'comments': comments},
success : function(result) {
alert(result);
}
});
});
});
</script>
Use .val() function instead .serialize(), if you have value of name is niklesh it will give name=niklesh and you expect only niklesh here.
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var bridge = $("#bridge").val();
var comments = $("#comments").val();
$.ajax({
type : "POST",
url : "ajax.php",
data : {"name": name,"email": email ,"last_name":last_name,"phone":phone,"bridge": bridge, "comments": comments},
success : function(result) {
alert(result);
}
});
});
});
Also use parameterised mysqli :
http://php.net/manual/en/mysqli.prepare.php#refsect1-mysqli.prepare-examples
Thanks to every one i found all the problem it was in :
$sql = "INSERT INTO info ( name, last_name, email , phone, bridge, comments ) VALUES ( '{$name}' , ' {$last_name} ','{$email }', '{$phone}' , '{$bridge}','{$comments}')";
I manage to find put in this in my code.:
mysqli_error($connection)
and i find that the mysql it was not insert one row.
I fix that and all is good.

Ajax won't submit and store information in database?

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);
}

Not inserting data to MySql database

$(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

Submitting data using jquery php mysql?

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.")";

jQuery, AJAX, PHP data exchange issue

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.

Categories