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.
Related
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);
}
$(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 have the following form:
<form name="register" id="register" action="include/process_registration.php" method="post">
<div class="form_error">Ooops! There is some missing or incorrect information. Please look back over this section. </div>
<div class="left_form2" >
<div class="inner_form1">
<p>Your First Name:*</p>
<p>Your Last Name:*</p>
<p>Date of Birth:*</p>
</div>
<div class="inner_form2">
<input type="text" name="firstname" id="firstname" class="login_form2" autocomplete="off"><br/>
<input type="text" name="lastname" id="lastname" class="login_form2" autocomplete="off"><br/>
<input type="text" name="dob" id="dob" class="login_form2"><br/>
</div>
</div>
<div class="left_form2" style="text-align:right;">
<div class="inner_form1">
<p>Email Address:*</p>
<p>Confirm Email:*</p>
</div>
<div class="inner_form2">
<input type="text" name="email" id="email" class="login_form2" autocomplete="off"><br/>
<input type="text" name="email2" id="email2" class="login_form2" autocomplete="off"><br/>
</div>
</div>
<input type="submit" id="register1" name="register" value="Register" class="buttons_register">
</form>
i am then using ajax to post my form data to my mysql query process_registration.php:
Ajax:
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#register1').click(function() {
var a = $('#firstname').html();
var b = $('#lastname').html();
var c = $('#dob').html();
var d = $('#email').html();
var f = $('#email2').html();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "include/process_registration.php",
data: {theOption: a, theOption2: b, theOption3: c, theOption4: d, theOption5: f},
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
my php file process_registration which contains my mysql query looks like so:
<?php
session_start();
include("config.php");
include("verify.php");
//retrieve our data from POST
$firstname = $_POST['theOption'];
$lastname = $_POST['theOption2'];
$dob = $_POST['theOption3'];
$email = $_POST['theOption4'];
$email2 = $_POST['theOption5'];
$firstname = stripslashes($firstname);
$firstname = mysql_real_escape_string($firstname);
$lastname = stripslashes($lastname);
$lastname = mysql_real_escape_string($lastname);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$email2 = stripslashes($email2);
$email2 = mysql_real_escape_string($email2);
$dob = stripslashes($dob);
$dob = mysql_real_escape_string($dob);
include '../dependables/secure.php';
$sql = "INSERT INTO supplier_registration (id, first_name, last_name, supplier_email, supplier_password, salt, dob, date) VALUES ('', '$firstname','$lastname','$email2', '$hash', '$salt', '$dob', now())";
$result2 = mysql_query($sql);
?>
for some reason i am getting taken to the process_registation.php page on the form submit and getting undefined index errors for all my form values. Can someone please show me where i am going wrong? Thanks
You are going to that page because the action of the form says it.
You can prevent that with javascript/jquery when submiting the form and then do the ajax code.
$("#register1").on("click", function(e) {
e.preventDefault();
//rest of your code
});
Also you won't get the inputs values with .html(), should use .val()
PS: you can get less code with serialize function for your forms. Take a look on jQuery API.
Remove this from your form...
action="include/process_registration.php"
Just make it action="" if you want it to reload the current page.
You might want to actually echo something from your process_registration.php too, otherwise the "whatigot" from the success function will always be empty.
You'll want to use e.preventDefault() to stop the submit click working as it is usually expected to.
You also need to use .val() instead of .html() as you should be getting the value of the input and not the html within the input.
$('#register1').click(function(e) {
e.preventDefault();
var a = $('#firstname').val();
var b = $('#lastname').val();
var c = $('#dob').val();
var d = $('#email').val();
var f = $('#email2').val();
// AJAX Call
});
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>