I want to make form, if i fill the first input (i.e 'rollnumber') , i want the rest of the input will filled automatically with data from mysql database (if the 'rollnumber' i filled is found in the database)
And if the 'rollnumber' not found in database it will say "Rollnumber not found".
How to achieve that goal?
The results with below code are:
The autofill not working, data won't show even i fill the right 'rollnumber'
the only thing that works is the #loading1, it show after i fill the data, but it won't hide back.
In case someone is kind enough to help me try my code to see what is wrong, here is the database (database name: login):
login.sql
These are my codes so far:
Form HTML:
<div class="form-group">
<input type="text" name="rollnumber" id="rollnumber" tabindex="1" class="form-control" placeholder="Roll Number" value="">
<img src="ajax-loader.gif" id="loading1"></img>
</div>
<div class="form-group">
<input type="text" name="fname" id="fname" tabindex="1" class="form-control" placeholder="First name1" value="">
</div>
<div class="form-group">
<input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last name" value="">
</div>
<div class="form-group">
<input type="email" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value="">
</div>
<div class="form-group">
<input type="text" name="phone" id="phone" tabindex="1" class="form-control" placeholder="Phone">
</div>
<div class="form-group">
<input type="text" name="batch" id="batch" tabindex="1" class="form-control" placeholder="Batch">
</div>
<div class="form-group">
<input type="text" name="lclass" id="lclass" tabindex="1" class="form-control" placeholder="Class">
</div>
Javascript:
$(document).ready(function()
{
$("#loading1").hide();
$("#rollnumber").change(function()
{
$("#loading1").show();
var id = $("#rollnumber").val();
var data = 'one=' + id;
$.ajax
({
type: "POST",
url: "checkrollnumber.php",
data: data,
dataType: 'json',
success: function (data)
{
$("#loading1").hide();
if (data)
{
for (var i = 0; i < data.length; i++) { //for each user in the json response
$("#fname").val(data[i].fname);
$("#lname").val(data[i].lname);
$("#email").val(data[i].email);
$("#phone").val(data[i].phone);
$("#batch").val(data[i].batch);
$("#lclass").val(data[i].lclass);
} // for
} // if
} // success
}); // ajax
});
});
checkrollnumber.php:
require_once "conn.php";
header('Content-type: application/json; charset=utf-8');
if(isset($_POST['one'])){
$json = array();
$id = trim($_POST['one']);
$query = "SELECT fname, lname, email, phone, batch, lclass FROM users WHERE rollnum = ?";
$stmt = $DB_con->prepare($query);
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($nFname, $nLname, $nEmail, $nPhone, $nBatch, $nLclass);
while ($stmt->fetch()){
$roll=array('fname'=>$nFname,'lname'=>$nLname,'email'=>$nEmail,'phone'=>$nPhone,'batch'=>$nBatch,'lclass'=>$nLclass);
array_push($json,$roll);
}
echo json_encode($json, true);
}
conn.php (connection)
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "login";
try
{
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
You should return false if the rollnumber isn't in the database, so to do that you could check if the array is empty or not using count(), replace the following line :
echo json_encode($json, true);
By :
if( count($json) == 0){
echo json_encode("false", true);
}else{
echo json_encode($json, true);
}
Then is your JS code you should add a condition to show "Rollnumber not found" like :
$(document).ready(function(){
$("#loading1").hide();
$("#rollnumber").on('input', function(){
$("#loading1").show();
var id = $(this).val();
$.ajax({
type: "POST",
url: "checkrollnumber.php",
data: {one: id},
dataType: 'json',
success: function (data)
{
if (data == 'false')
{
alert("Rollnumber not found");
}else{
for (var i = 0; i < data.length; i++) { //for each user in the json response
$("#fname").val(data[i].fname);
$("#lname").val(data[i].lname);
$("#email").val(data[i].email);
$("#phone").val(data[i].phone);
$("#batch").val(data[i].batch);
$("#lclass").val(data[i].lclass);
} // for
} // if
$("#loading1").hide();
} // success
}); // ajax
});
});
NOTE : The data parameter should be sent like data: {one: id}.
I suggest also the use of input as event since it's more efficient when you track the use inputs :
$("#rollnumber").on('input', function(){
Hope it will help you.
Don't declare variable similar to keyword, as in your case you declared variable data, which is confusing with data keyword in ajax.
var data = 'one=' + id;
Also, change below line of code
data: data,
to
data: {one : $("#rollnumber").val() },
Related
I'm new at ajax and i am confused becouse i think my ajax file is not sending data to php file or php is not getting it, IDK, Help me please
This is the form
<form id="register-form" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="text" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" name="confirm-password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
</div>
</div>
</div>
</form>
This is the .js
$(document).ready(function(){
$("#register-submit").click(function(){
var email = $("#email").val();
var username = $("username").val();
var password = $("password").val();
$.ajax({
type: "POST",
url: "register.php",
data: "email="+email+"&username="+username+"&password="+password,
success:function(data){
alert("succes");
}
});
});
});
This is the .php
<?php
require_once("functions.php");
$email = $_POST["email"];
$username $_POST["username"];
$password $_POST["username"];
mysqli_query($connection, "INSERT INTO users(email, username, password) VALUES('$email', '$username', '$password')");?>
First of all:
var username = $("username").val();
var password = $("password").val();
Should be:
var username = $("#username").val();
var password = $("#password").val();
data: "email="+email+"&username="+username+"&password="+password
Should be:
data: {email: email, "username": username, password: password}
And
$username $_POST["username"];
$password $_POST["username"];
Should be:
$username = $_POST["username"];
$password = $_POST["password"];
You have to send the data in JSON format like:
var data = { "email": email, "username": username, "password": password };
so pass data var in data Ajax function!
1st: instead of using submit input click event you can use form submit event
$("#register-form").on('submit',function(){
and while you use a submit sure you need to prevent the page from default reload .. I think you problem is this point .. so you need to prevent the form by using e.preventDefault(); you can use it like
$("#register-form").on('submit',function(e){
e.preventDefault();
// rest of code here
$(document).ready(function(){
$("#submit").click(function(event) {
event.preventDefault();
var inputEmail = $("#email").val();
var inputUsername = $("#username").val();
var inputPassword = $("#password").val();
$.ajax({
type: "POST",
url: "register.php",
data: ({ email: inputEmail, password: inputPassword, username: inputUsername}),
success: function(data){
var obj = jQuery.parseJSON(data);
alert("Success " + obj.username + " " + obj.password + " "+ obj.email);
}
});
});
});
Here in .js file I put at the top in .click(function(event) { event.preventDefault(); }
preventDefault();
this function prevent the page from realoding when you press the submit button
data: ({ email: inputEmail, password: inputPassword, username: inputUsername})
Here i send the data data: ({nameOfTheVarieableYouWantToReadWithPHP: nameOfTheVariableFromJs})
Here is the .php file
require_once("database.php"); //require the connection to dabase
$email = protect($_POST['email']); //This will read the variables
$username = protect($_POST['username']); //sent from the .js file
$password = protect($_POST['password']); //
$result = array(); //This variable will be sent back to .js file
//check if the variables are emtpy
if(!empty($email) && !empty($username) && !empty($password)){
//db_query is my function from database.php but you can use mysqli_query($connectionVariable, $sqlString);
db_query("INSERT INTO users (email, username, password) VALUES ('$email','$username','$password')"); //Here insert data to database
//we will set array variables
$result['username'] = $username; //Here we set the username variable fron the array to username variable from js
$result['password'] = $password; // the password same as the username
$result['email'] = $email; //the email same as the username and password
}else{ // if the variables are empty set the array to this string
$result = "bad";
}
echo json_encode($result); //transform the result variable to json
In the .js file
success: function(data){
var obj = jQuery.parseJSON(data); //create a variable and parse the json from the php file
//You can set the variables get from the json
var usernameFromPhp = obj.username;
var passwordFromPhp = obj.password;
var emailFromPhp = obj.email;
alert("Success " + usernameFromPhp + " " + passwordFromPhp + " "+ emailFromPhp);//
}
I have this "register users" file in which I have a form, I'll simplify in here what I have:
<form action="" method="POST">
<label for="user" class="control-label">User </label>
<input type="text" name="user" class="form-control" id="user" value="" required=""/>
<label for="user" class="control-label">Password1 </label>
<input type="text" name="password1" class="form-control" id="password1" value="" required=""/>
<label for="user" class="control-label">Password2 </label>
<input type="text" name="password2" class="form-control" id="password2" value="" required=""/>
<button type="button" value="signUp" name="submit" class="btn btn-lg btn-primary btn-block" onClick="register()">Sign up!</button>
As you can see, there is an event in there, in a JS file. This file has all the vaidations of the inputs and it works just fine (I don't think it's relevant, so I won't post it). It also has the AJAX call to the PHP file that will insert the data into the database.
function register(){
if(validationRegister()){
$.ajax({
url: "http://localhost/myProject/extras/processSignUp.php",
type: "POST",
data: {"user": user,
"password": password,
"password2": password2,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "Registered"){
window.location.href = "http://localhost/myProject/index.php";
}else{
window.location.href = "http://localhost/myProject/signUp.php";
}
}
});
}else{
alert("Incorrect data");
}
}
And this is the PHP file:
<?php
include_once "connection.php"; --> this has all the data for the connection to the database
if($_POST['user'] == '' || $_POST['password'] == '' || $_POST['password2'] == ''){
echo 'Fill all the information';
}else{
$sql = 'SELECT * FROM `user`';
$rec = mysqli_query($con, $sql);
$verify_user = 0;
while($result = mysqli_fetch_object($rec)){
if($result->user == $_POST['user']){
$verify_user = 1;
}
}
if($verify_user == 0){
if($_POST['password'] == $_POST['password2']){
$user = $_POST['user'];
$password = $_POST['password'];
$sql = "INSERT INTO user (user,password) VALUES ('$user','$password')";
mysqli_query($con, $sql);
echo "Registered";
}else{
echo "Passwords do not match";
}
}else{
echo "This user has already been registered";
}
}
?>
The PHP code, works great when used on its own (it used to be at the beginning of the form file, surrounded by if($_POST['submit']){}) But now I want to use it in a separate file, and use AJAX, and I'm unable to register a user :/ the value of data is never "Registered"... Any ideas?
Thanks in advance! :)
Please never run this code in a live environment, your code is open to SQL injection and you NEED to hash passwords.
This line:
if($_POST['user'] == '' or $_POST['password']){
Looks to be your issue. You want to be testing $_POST['password'] somehow, like $_POST['password'] == '' or !isset($_POST['password']).
Your logic is also horribly constructed, you may want to go look at a few tutorials. e.g. why are you fetching ALL your users just to test if one exists, do that logic in the SQL code itself to avoid fetching an entire table for no reason.
I am trying use for fetching data and displaying it through jQuery. This is my script
<script>
$("#kys_SignUp_form").submit(function(event){
event.preventDefault();
var $form = $(this);
var $url = $form.attr('action');
var $email = $("#email").val();
var $username = $("#username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: $url,
data: { email: $email, password: $password, username: $username },
success: function(data) {
alert("Transaction Completed!");
}
});
});
</script>
And this is my form:
<form role="form" action="kys_SignUp.php" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I am new to jQuery. The problem that I am facing is the page is being redirected to the php file even after using ajax, I think ajax function is not at all called.
This is my php file:
<?php
include "kys_DbConnect.php";
$email = $username = $password = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
}
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
echo "Username or Email already exists";
}
else{
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param("sss",$username,$email,$password);
$insert->execute();
header("Location: http://localhost/KeyStroke/index.html");
exit();
}
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I am not able find out what's wrong with my code.
Updated try this :
<form role="form" action="kys_SignUp.php" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button id="submit_btn" class="btn btn-default">Submit</button>
</form>
UPDATED 2 :
<script>
$(function() {
// Handler for .ready() called.
$("#submit_btn").on('click',function(event){
//alert is not being called at all . That means .submit() is never beign called
alert("hello there");
event.preventDefault();
var form = $('#kys_SignUp_form'); //changed from $(this)
var url = form.attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: 'POST',
url: url,
dataType:"json", //<-- add this
data: { email: email, password: password, username: username },
success: function(data) {
if(data.success){
window.location.href=data.result;
}else {
alert("ERROR. "+data.result);
}
}
});
});
});
</script>
and in your PHP code
<?php
include "kys_DbConnect.php";
$email = $username = $password = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
}
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
echo json_encode(array("success"=>false,"result"=>"Username or Email already exists"));
}
else{
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param("sss",$username,$email,$password);
$insert->execute();
echo json_encode(array("success"=>true,"result"=>"http://localhost/KeyStroke/index.html"));
}
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script>
$("#clickbutton").click(function(){
var $url = 'kys_SignUp.php';
var $email = $("#email").val();
var $username = $("#Username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: $url,
data: 'email='+$email+'&password='+$password+'&username='+$username,
success: function(data) {
alert("Transaction Completed!");
}
});
});
</script>
and also remove action in your form and change your submit button
<button type="button" id="clickbutton" class="btn btn-default">Submit</button>
Try this function:
<script>
$(function() {
$('#kys_SignUp_form button[type="submit"]').on('click',function(event){
alert("hello there");
event.preventDefault();
var form = $("#kys_SignUp_form");//note here we select the form element to get the url
var url = form.attr('action');
var email = form.find("#email").val();
var username = form.find("#username").val();
var password = form.find("#password").val();
$.ajax({
type: 'POST',
url: url,
dataType:"json",
data: { email: email, password: password, username: username },
success: function(data) {
if(data.message == "Success") {
window.location ='http://localhost/KeyStroke/index.html';
} else {alert(data.message)}
});
});
});
</script>
php:
include "kys_DbConnect.php";
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function isUser($username,$email)
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
return true;
}
}
function inserNewUser($username,$email,$password)
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param($username,$email,$password);
$insert->execute();
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
if (isUser($username,$email)) {
echo json_encode(['message'=>'Username or Email already exists'])
} else {
inserNewUser($username,$email,$password);
echo json_encode(['message'=>'Success']);
}
} else {
echo json_encode(['message'=>'Error get method not allowed'])
}
Look at my way, may be it will help you.
$('#frmReportWithparams').submit(function () {
$.ajax({
url: "#Url.Content("~/LeftMenu/SendReportWithParameter")",
type: "POST",
data: $('#frmReportWithparams').serialize(),
success: function (result) {
if (result.IsSuccess == true) {
alert("Thank You.")
$('#modalHomeIndex').dialog('close')
}
else {
alert("'Error Occurs.Try Later.")
$('#modalHomeIndex').dialog('close')
}
}
})
return false;
})
actually the code is for C#, but i just set where to post a form in ajax.
look at #Url.content where i passed the values where my form will be posted.
and the parameters are serialized in data field.
if you have any other query then ask further...
Why Use $ in js variable this is wrong.
Use This One.
var form = $(this);
var url = $form.attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
try this may be this will work
<script>
$(document ).ready(function() {
$('#kys_SignUp_form').on('submit', function(e) {
e.preventDefault();
});
});
// ================ SUBMIT =====================
$('#kys_SignUp_form .form_submit').on('click', function(e){
e.preventDefault();
var $form = $(this);
var $email = $("#email").val();
var $username = $("#username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: 'kys_SignUp.php',
dataType: 'json',
data: { email: $email, password: $password, username: $username },
success: function(data) {
alert("Transaction Completed!");
},
error : function( errorThrown) {
alert('errorThrown ' + errorThrown);
}
});
});
</script>
HTML
<form role="form" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-default form_submit">Submit</button>
You need to do two things.
1- Change var var url = $form.attr('action'); to
var url = $("#kys_SignUp_form").attr('action');
2- Add a return statement just before you submit function ends
complete script will look like below-
<script>
$( document ).ready(function() {
// Handler for .ready() called.
$("#kys_SignUp_form").submit(function(event){
alert("hello there");
event.preventDefault();
var form = $(this);
var url = $("#kys_SignUp_form").attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: 'POST',
url: url,
data: { email: email, password: password, username: username },
success: function(data) {
alert("Transaction Completed!");
}
});
return false;
});
});
</script>
I have made form of customer details form when I click the button, It send Json data to customer. But my code is not inserting data into database. I am new in web technology, please tell me where I am wrong.
my Script:
<script>
$(document).ready(function(){
$("#btnBooking").on("click", function(){
var uName = document.getElementById('userName').value;
var mailId = document.getElementById('addressemailId').value;
var mobNum = document.getElementById('userContactNumber').value;
$.ajax({
url:"http://192.168.1.11/customerhomes/customer.php",
type:"GET",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum},
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
alert("13");
},
error: function(err){
alert(JSON.stringify(err));
}
})
});
});
</script>
form in html
<body>
<div class="page-header text-center">
<form >
<div class="col-lg-8">
<div class="form-group">
<label class="col-lg-3 control-label">Name:<font style="color: red;">*</font></label>
<div class="col-lg-9">
<input type="text" class="form-control" id="userName" name="userName" placeholder="Full Name" value="">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Mobile:<font style="color: red;">*</font></label>
<div class="col-lg-9">
<input type="text" class="form-control" id="userContactNumber" name="userContactNumber" type="number" placeholder="" onkeypress="enableKeys(event);" maxlength="10" placeholder="9966778888">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:<font style="color: red;">*</font></label>
<div class="col-lg-9">
<input type="text" class="form-control" name="addressemailId" id="addressemailId" placeholder="you#example.com" value="">
</div>
</div>
<div class="form-group marg-bot-45">
<label class="col-lg-3 control-label"></label>
<div class="col-lg-9">
Confirm Booking
</div>
</div>
</div>
</form>
</div>
</body>
server code
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("customer_details");
if(isset($_GET['type']))
{
if($_GET['type']=="booking"){
$name = $_GET ['Name'];
$mail = $_GET ['Email'];
$mobile = $_GET ['Mob_Num'];
$query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mail','$mobile')";
$result1=mysql_query($query1);
}
}
else{
echo "Invalid format";
}
Use this
JavaScript Code:
<script>
$(document).ready(function(){
$("#btnBooking").on("click", function(e){
// as you have used hyperlink(a tag), this prevent to redirect to another/same page
e.preventDefault();
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://192.168.1.11/customerhomes/customer.php",
type:"GET",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum},
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
alert(JSON.stringify(response));
},
error: function(err){
alert(JSON.stringify(err));
}
})
});
});
</script>
PHP Code
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("customer_details");
if(isset($_GET['type']))
{
$res = [];
if($_GET['type'] =="booking"){
$name = $_GET ['Name'];
$mail = $_GET ['Email'];
$mobile = $_GET ['Mob_Num'];
$query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mail','$mobile')";
$result1 = mysql_query($query1);
if($result1)
{
$res["flag"] = true;
$res["message"] = "Data Inserted Successfully";
}
else
{
$res["flag"] = false;
$res["message"] = "Oppes Errors";
}
}
}
else{
$res["flag"] = false;
$res["message"] = "Invalid format";
}
echo json_encode($res);
?>
If data is inserted successfully it return true flag with message, otherwise false flag with message
I would first of all change the "GET" to a "POST" on both the ajax call and the receiving PHP page on the server.
Secondly, I'd check that the values are actually being passed to the PHP page by using echo to output each of them on the PHP side. That way you'll know at least the values are coming through.
JavaScript:
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('userContactNumber').val();
$.ajax({
url:"http://192.168.1.11/service4homes/customer.php",
type:"POST",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum},
complete: function(response){
var test = $.parseHTML(response);
alert(test);
}
});
PHP Code:
echo $_POST["type"];
echo $_POST["Name"];
//etc...
try this it might help you.
in your ajax function:
1st change :
ContentType:"application/json" to contentType: "application/json; charset=utf-8"
2nd
in data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum} change to data:{type1:"booking",Name:uName, Email:mailId, Mob_Num:mobNum}. see you set type as GET in ajax function so i am thinking that "type" is reserved word, so it might not work. and also check your url where you are sending ajax request if it is correct or not bcoz you are using ip address.
in your server code i am seeing typo.
there is space between
$_GET ['name'], $_GET ['Email'], $_GET ['Mob_Num'].
there should be no space so change it to this,
$_GET['name']
$_GET['Email']
$_GET['Mob_Num']
I'm hoping someone could look over my code and let me know what's going on. I have a form. When it is submitted the popup comes up and tells me that it failed and I get a page that just says "undefined". Anyone got any ideas on A: why the send is failing and B: How I need to amend my JavaScript to get the page to go back to the homepage after submission.
HTML:
<div class="contact-form">
<p class="mandatory">* indicates Manadatory Field</p>
<div data-role="fieldcontain" class="text-field">
<label for="firstname">First Name*:</label>
<input type="text" name="firstname" value="" placeholder="" class="required" id="firstname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="surname">Last Name:</label>
<input type="text" name="surname" value="" placeholder="" id="surname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="email">Email Address*:</label>
<input type="email" name="email" value="" placeholder="" class="required" id="email" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="mobilephone">Mobile Number:</label>
<input type="number" name="mobilephone" value="" placeholder="" id="mobilephone" />
</div>
<div data-role="fieldcontain">
<label for="message">Message*:</label>
<textarea name="message" id="message" placeholder="" class="required"></textarea>
</div>
<div class="send">Send Message</div>
JAVASCRIPT
$(function () {
$("#symptomsemployersbutton").click(function () {
$("#symptomsemployers").toggle("slow");
});
});
$('#send-feedback').live("click", function () {
var url = 'submit.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form');
$('.required', $contactform).each(function (i) {
if ($(this).val() === '') {
error++;
}
}); // each
if (error > 0) {
alert('Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk *.');
} else {
var firstname = $contactform.find('input[name="firstname"]').val();
var surname = $contactform.find('input[name="surname"]').val();
var mobilephone = $contactform.find('input[name="mobilephone"]').val();
var email = $contactform.find('input[name="email"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type: "GET",
url: url,
data: {
firstname: firstname,
surname: surname,
mobilephone: mobilephone,
email: email,
message: message
},
success: function (data) {
if (data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Unable to send your message. Please try again.');
}
}
}); //$.ajax
}
return false;
});
PHP
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["firstname"])) {
$firstname = strip_tags($_GET['firstname']);
$surname = strip_tags($_GET['surname']);
$email = strip_tags($_GET['email']);
$mobilephone = strip_tags($_GET['mobilephone']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">rn";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'mark#launchintervention.com';
$subject = 'Contact Form';
$mailbody = "
First Name: $firstname
Last Name: $surname
Email: $email
Mobile Phone: $mobilephone
Message: $message
IP: $ip
Browser info: $httpagent
Referral: $httpref
Sent: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>
Your conditional statement never fires in your success function because it will always be false. (data == 'success') will never work because your json encoding of that string returns the value, "success" as opposed to success. I don't know why you're json encoding it anyway, but you should do something else such as
$result = array(
'status' => 'success'
);
echo json_encode($result);
Then you can do
(data.status == 'success')
As far as redirecting after the result returns successful, after the following line:
$contactpage.find('.contact-form').hide();
You should do something like:
setTimeout(function(){
window.location = 'mydomain.tld/my-homepage.ext';
}, 5000);
And your element with the class of contact-thankyou should have some type of text like, "We have received your submission. You will be redirected to the home page in 5 seconds.". Then after 5 seconds they will be redirected based on the previously defined setTimeout function.
You also have an rn at the end of your header declaration which i assume should be \r\n, however you do not continue concatentation of the headers and therefore it is not required. Please review the RFC2822 on this.