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.
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);
}
I have written a code to pass values of input fields to a php script using ajax but it is not working. Can anyone suggest how to rectify this code ? I want to display the values passed through ajax in the php file.
ex.php
<?php
$temp = $_POST['start_date'];
$name = $_POST['end_date'];
echo $temp.$name;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").change(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
$.ajax({
method: "POST",
url: "ex.php", // path to php file
data: { start_date: fname, end_date: lname } // send required data here
})
.done(function( msg ) {
});
});
});
</script>
</head>
<body>
<form action="#" method="post" name="form1">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
</form>
</body>
</html>
try using below code :
<?php
$temp = $_POST['start_date'];
$name = $_POST['end_date'];
echo $temp.$name;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").change(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var post = "&start_date=" + fname + "&end_date=" + lname;
$.ajax({
'url': ex.php,
'data': post,
'type': 'POST',
'success': function (data)
{
}
});
});
});
</script>
</head>
<body>
<form action="" method="post" name="form1">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
</form>
</body>
</html>
Add an element to your makeup
<span id="idOfSomeElementYouWantToUse"></span>
and in your callback set it's text.
.done(function( msg ) {
$("#idOfSomeElementYouWantToUse").text(msg);
});
Add a div to your page and use html() to append the data that comes from the ajax request
<body>
<form action="#" method="post" name="form1">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
</form>
<div class="ajax-result"></div>
</body>
js:
$("input").change(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
$.ajax({
method: "POST",
url: "other_file.php", // path to php file
data: { start_date: fname, end_date: lname }, // send required data here
success:function(data){
$(',ajax-result').htm(data);
}
});
Note: from what i can tell you are ajaxing to the same page,i strongly suggest you create a new php file(other_file.php) with your logic in it
From what I can understand from your comment above, you want to insert textbox value to the database, to do this you don't want to call ajax on textChange event because at that time not all value will be present, I suggest adding submit button to the form and call ajax on form submit.
Here is the main file:
ajax_ex.php (You should name it as per your requirement)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form id="frmInsert" method="post" name="form1">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
<input type="submit" value="Insert" />
</form>
<div id="msg">
</div>
</body>
<!-- You should put javascript at bottom -->
<script src="jQuery-2.1.4.min.js"></script>
<script type="text/javascript">
$("#frmInsert").submit(function(e){
var fname = $("#fname").val();
var lname = $("#lname").val();
$.ajax({
method: "POST",
url: "insert.php", // path to php file
data: { start_date: fname, end_date: lname } // send required data here
})
.done(function( msg ) {
msg = $.trim(msg);
if (msg == 'true') {
$('#msg').html("Data is inserted successfully");
}else {
$('#msg').html("Data insertion failed");
}
});
e.preventDefault();
});
And you should not call the same file in ajax, I recommend that you create individual file that will be called in ajax, this file will handle all back-end processing.
insert.php
<?php
//Check if post data is available (You should also check for particular attribute if it is available)
if (!empty($_POST)) {
$temp = $_POST['start_date'];
$name = $_POST['end_date'];
//Insert Data into database
// Your code
$result = 'true'; //check for operation if it is success and store it in result
//Echo result so you can check if insert is success of not in your ajax callback.
echo $result;
}
?>
I am working on a script that echoes an answer based on a selected value. This will be multiple values later on but for now i'm just testing.
The php script is called trough AJAX so the results will show on the same page.
The only problem is that my variable $brand in this case isn't passed so the script will always return my else statement. I have included the variable in the echo to check wether it was passed, which it isn't. What is going wrong here?
this is my index file code:
<?php
session_start();
?>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="JS/jquery-1.10.2.js" ></script>
<script>
function myCall(){
var request = $.ajax({
url: "process.php",
type: "post",
dataType: "html"
});
request.done(function(msg) {
$("#response").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<div id="formulier">
<form method="" action="" name="form" id="form">
<label for="brand">Brand</label>
<select id="brand" name="brand">
<option value="" >- Select -</option>
<option value="1">Marlboro (1)</option>
<option value="2">Pall Mall (2)</option>
</select>
<input type="button" value="submit" onclick="myCall();">
</form>
</div>
<div id="response">
</div>
This is my php file (process.php):
<?php
session_start();
$brand = $_POST['brand'];
if( $brand == '1'){
echo "Value is 1";
}
else{
echo "Value is: ".$brand;
}
?>
I see several problems in your script:
at no point you reference the actual fields of your form
I'd rather put the handlers inside the ajax call
Try this:
function myCall(){
var request = $.ajax({
url: "process.php",
type: "post",
dataType: "html",
data: $('#form').serialize(), //here you send the form fields
success: function(msg) {
$("#response").html(msg);
},
error: function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
}
}
You should use json_encode (http://us1.php.net/json_encode) for responding in process.php.
Make sure you set the session variable and read it later (in your php else block), e.g.,
$_SESSION["brand"] = "2";
You should try the define the form attributes
<form method="POST" action="" name="form" id="form">
I'm learning how to integrate JQuery, AJAX and PHP together.
My problem is that my success function isn't getting any value from the parameter and just getting a '0'. I'm not really sure what I'm doing wrong either, but I have just been following this tutorial JQuery & PHP Tutorial and just copied how he got the value from the PHP code using echoes and a parameter variable r.
I have tried searching for the solution, but I'm not sure if any of the results are relevant to what I am doing. I tried following some of their advice but none seems to work (the promise thing for jQuery)
I hope someone can enlighten me what I am doing wrong as I am eager to learn more PHP and jQuery.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function () {
jQuery("form").submit(function(e) {
var input = $("#input").val();
var url = 'input=' + input;
$.ajax({
type: "POST",
url: "process.php",
data: url,
success: function(r) {
$("#output").text(function(r) {
return r;
});
}
});
e.preventDefault();
});
});
</script>
<title>Insert title here</title>
</head>
<body>
<form action="process.php" method="post">
Inputs:<br />
<textarea rows="15" cols="60" id="input" name="input">Some text...
</textarea><br /><br />
Start:
<input type="text" id="start" name="start" />
End:
<input type="text" id="end" name="end" /><br />
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<p id="output">Output: Some Random Text</p>
</body>
</html>
PHP:
require 'parser.php';
$parser = new Parser();
#header('index.php');
$hash = $parser->parse($_POST['input']);
$keys = array_keys($hash);
foreach($keys as $key) {
echo "$key ->";
$dests = $hash[$key];
foreach($dests as $dest) {
echo " $dest";
}
echo "<br />";
}
?>
<script>
$(function () {
jQuery("form").submit(function(e) {
var input1 = $("#input").val();
var url = {'input' : input1}; // a little change to the data parameter
$.ajax({
type: "POST",
url: "process.php",
data: url,
success: function(r) {
// $("#output").text(r); //<--- changed to this
$("#output").html(r); // this is better as you output html
}
});
e.preventDefault();
});
});
</script>
for jquery text(), use the return value from the server directly. If you are outputting html use jquery html() instead
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>