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']
Related
I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?
I am a wordpress user and try to update the database using jquery.ajax. My code updates the database but the success function doesn't return anything to html div tag. Here are some portions of my code:
PHP Code:
$connect = mysqli_connect(HOST, USER, PASS, NAME);
if(mysqli_connect_errno()){
$msg = "Connection With Database is not Successful. Error: ".mysqli_error();
echo $msg;
die();
}
$nam = $_POST['name'];
$eml = $_POST['email'];
$entry = "INSERT INTO `table` (name, email,) VALUES ('$nam', '$eml')";
if(!mysqli_query($connect, $entry)){
$msg = "Error while submitting Your Data. Error: ".mysqli_error();
echo $msg;
die();
}
$msg = "Your data submitted successfully";
echo $msg;
mysqli_close($connect);
?>
HTML Code:
<form method="POST" id="data_form">
<input type="text" name="name" id="name" placeholder="Full Name" />
<br>
<input type="email" name="email" id="email" placeholder="Email Address" required />
<br>
<button type="submit" id="submit">Submit</button>
</form>
<div id="output"></div>
jQuery Code:
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false,
success: function(result){
$("#output").html(result);
}
});
});
});
I also used 'done' instead of 'success' but didn't work.
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false
}).done(function(result){
$("#output").html(result);
});
});
});
Actually I am trying to print the $msg variable from the php file to the 'output' div tag.
Any help would be greatly appreciated.
I'm trying to create a login system that takes the user's input(username and password), retrieves it and then input the session data into a new table(tbl_sessions) and then redirect the user based on an attribute in the user's table called personcode(000000 for lecturer and 111111 for students)...I figured I need to chain two ajax requests. One to retrieve the result (from test.php which sends the session data as JSON) and the other ajax to insSession.php which inserts the session data into the table and returns a JSON object(i passed jd as parameter).......my code works!! well sort of firstly, I can't receive JSON data from the ajax call insSession.php(I tried json_decode maybe I'm using it wrongly)so I just bypassed it and used $_SESSION and return a JSON the second problem I'm facing is that if I make an ajax request, my browser refreshes please I need help
how do I send data from the first ajax call (var a1) to the 2nd(var a2)
how can I successfully redirect the user after the 2nd call without the browser refreshing?
below are the relevant documents
HTML
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!---->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/test.js"></script>
<script src="js/functions.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<!-- Optional Bootstrap theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<link href="css/design.css" rel="stylesheet" type="text/css">
</head>
<body>
<!-- container tag-->
<div class="container">
<div class="col-md-5 col-md-offset-4 col-sm-12 col-xs-12 login-panel">
<!--<div class="col-md-4 col-md-offset-4 login_panel">-->
<form class="form-horizontal" method="post" id="login-form">
<h4 class="text-center panel-heading">Login<!--<small><span class="glyphicon glyphicon-lock"></span></small>--></h4>
<hr>
<div class="alert alert-danger user-empty" style="display:none">
×
<strong>Warning!</strong> Username field is empty.
</div>
<!-- end of user-empty -->
<div class="alert alert-danger pass-empty" style="display:none">
×
<strong>Warning!</strong> Password field is empty.
</div>
<!-- end of pass-empty-->
<div class="alert alert-danger both-empty" style="display:none">
×
<strong>Warning!</strong> Both fields are empty.
</div>
<!--end of both-empty-->
<div class="row">
<div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-8 col-xs-offset-2 " >
<div class="input-group form-group">
<!--<div class="input-group">-->
<span class="input-group-addon"><span class="glyphicon glyphicon-user "></span></span>
<input type="text" class="form-control username" id="username" placeholder="Username">
<!--</div>-->
</div>
</div>
<div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-8 col-xs-offset-2 ">
<div class="input-group form-group ">
<!--<div class="form-group">-->
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" class="form-control password" id="password" placeholder="Password">
<!--</div>-->
</div>
</div>
<div class="form-group form-group-sm">
<button class="btn btn-primary col-md-offset-4 col-md-4 col-sm-offset-4 col-sm-4 col-xs-4 col-xs-offset-4 sign-in " type="submit">Sign In <i class="glyphicon glyphicon-log-in"></i></button>
</div>
</div><!-- End of row -->
</form>
<!--</div>--><!--end of login_panel-->
<div class="clearfix"></div>
</div><!-- end of row-->
</div><!-- end of container-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</body>
</html>
functions.js
//function that runs a check on login variables
function input_Check(a,b){
/**
Where a = username
b = password
**/
//to specify the missing input, check if it's the username field, password or both
if(a =="" && b!="")
{
$(".user-empty").fadeIn();
return false;
}
else if(a !="" && b =="")
{
$(".pass-empty").fadeIn();
return false;
}
else if(a!="" && b!="")
{
return true;
}
else
{
$(".both-empty").fadeIn();;
return false;
}
}
AjAX CALL
enter cod// JavaScript Document
$(document).ready(function(e)
{
$(".sign-in").click(function(){
//Login Variables
var username = $(".username").val();//"ayaradua"
var password = $(".password").val();//Password12
//Setup login data structure
var login_Data=
{
'key':"Login",
'username': username,
'password': password
}
//If the Input isnt empty, make the Ajax call
if(input_Check(username,password)== true)//you can remove this if statement
{
var a1= $.ajax({
data:login_Data,
type:"POST",
url: './php/test.php',
dataType: 'json',
beforeSend: function()
{
$(".sign-in").text("connecting...");
},
}),
a2 = a1.then(function(data) {
// .then() returns a new promise
return $.ajax({
url: './php/insSession.php',
//type:"POST",
//dataType: 'json'
//data: {'user_Id':data.user_Id,
});
//return $.getJSON('./php/insSession.php');
});//end of a2
//i user this alert to confirm if data has been received
a1.done(function(data,textStatus,xhr){
alert(data.user_Id+data.session_Id+data.date);
});
//after the promise is returned, check the personcode to determine the user's status and redirect them accordingly
a2.done(function(jd,textStatus,xhr) {
if(jd.personcode == 000000)
{
window.location.href='./lecturer.php';
//alert("lecturer");
}
else if(jd.personcode==111111)
{
window.location.href='./student.php';
//alert("student");
}
else {
$("hr").append("<p class=\"text-danger text-center\">Sorry Couldn't Login check username and password </p>")};
});
a2.fail(function(){
$("hr").append("<p class=\"text-danger text-center\">Problem with Ajax Call </p>");
});
}// end of input_Check if statement
});//end of click method
});// end of ready functione here
test.php
session_start();
//include relevant files
include("../inc/connect.php");
include("./functions.php");
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$username =$_POST["username"];
$password= $_POST["password"];
// Setup Query
$query = "SELECT Id,firstname,lastname,username,password,personcode FROM tbl_User WHERE `username`=? AND `password`=?";
// Get instance of statement
$stmt = mysqli_stmt_init($mysqli);
// Prepare Query
mysqli_stmt_prepare($stmt, $query);
// Bind Parameters [s for string]
mysqli_stmt_bind_param($stmt,'ss',$username,$password);
// Execute Statement
if (mysqli_stmt_execute($stmt))
{
// Bind results to variable
mysqli_stmt_bind_result($stmt,$Id,$firstname,$lastname,$user,$pass,$personcode);
// Fetch Value
$fetch= mysqli_stmt_fetch($stmt);
$array = array("user_Id"=>$Id,
"firstname"=>$firstname,
"lastname"=>$lastname,
"username"=>$user,
"password"=>$pass,
"personcode"=>$personcode
);
$data = json_encode($array);
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
$_SESSION = set_Session($array,$new_sessionid);
unset($_SESSION["firstname"]);
unset($_SESSION["lastname"]);
unset($_SESSION["username"]);
unset($_SESSION["password"]);
//array_push($_SESSION,$ses_Data);
header('Content-Type: application/json');
$dat=json_encode($_SESSION);
echo $dat;
// Close Statement
mysqli_stmt_close($stmt);
}
}
//if ($_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest')
//{
/**
// Setup parameter to be bound into query
$username =$_POST["username"]; //"ayaradua";
$password= $_POST["password"];//"Password12";
//}
**/
insSession.php
session_start();
include("../inc/connect.php");
include("../php/functions.php");
$x = array();
$session_Var= array_merge($x,$_SESSION);
//get table columns
$query = "INSERT INTO `tbl_Session` `user_Id`,`personcode`,`session_Id`,`date`)VALUES(?,?,?,?)";
$stmt = mysqli_stmt_init($mysqli);
if(mysqli_stmt_prepare($stmt,$query))
{
// bind parameters for markers
mysqli_stmt_bind_param($stmt,"ssss",$session_Var['user_Id'],$session_Var['personcode'],$session_Var['session_Id'],$session_Var['date']);
// execute query
if(mysqli_stmt_execute($stmt))
{
header('Content-Type: application/json');
$json = json_encode($session_Var);
echo $json;
}
else{
echo "Sorry didn't execute";
}
}
You may chain the two ajax calls in this way, of course this is not the only way (in this way you have full control on the two ajax calls: the parameters/variables to pass from the first to the second and when to redirect):
$(function () {
$(".sign-in").click(function (e) {
//Login Variables
var username = $(".username").val();//"ayaradua"
var password = $(".password").val();//Password12
//Setup login data structure
var login_Data =
{
'key': "Login",
'username': username,
'password': password
}
//If the Input isnt empty, make the Ajax call
if (input_Check(username, password) == true)//you can remove this if statement
{
$.ajax({
data: login_Data,
type: "POST",
url: './php/test.php',
dataType: 'json',
beforeSend: function () {
$(".sign-in").text("connecting...");
}
}).done(function (data, textStatus, xhr) {
//{"result":true,"data":{"user_Id":"user_Id","personcode":"personcode","session_Id":"LocalSession_Id","data":"date"}};
alert(data.user_Id + data.session_Id + data.date);
if (data.result) {
$.ajax({
url: './php/insSession.php'
type:"POST",
dataType: 'json',
data: JSON.stringify(data.data),
}).done(function (data, textStatus, xhr) {
if (jd.personcode == 000000) {
window.location.href = './lecturer.php';
//alert("lecturer");
} else if (jd.personcode == 111111) {
window.location.href = './student.php';
//alert("student");
} else {
$("hr").append("<p class=\"text-danger text-center\">Sorry Couldn't Login check username and password </p>")
}
;
}).fail(function (jqXHR, textStatus, errorThrown) {
$("hr").append("<p class=\"text-danger text-center\">Problem with Ajax Call </p>");
});
} else {
// the first PHP (insSession.php) returned error so...............
}
});
}
});
});
Your insSession.php file need to return always a json value like for instance:
{"result":true,"data":{"user_Id":"user_Id","personcode":"personcode","session_Id":"LocalSession_Id","data":"date"}}
or
{"result":false,"data":null}
To achieve this result your insSession.php could be something like:
<?php
$retVal = array( 'result' => false, 'data' => null );
if(result or some computation is true) {
$data = array( 'user_Id' => 'user_Id', 'personcode' => 'personcode', 'session_Id' => 'LocalSession_Id', 'data' => 'date');
$retVal = array( 'result' => true, 'data' => $data );
}
header('Content-type: application/json');
echo json_encode( $retVal );
?>
So whenever you return from this php you have a json object, always valid with a first field containing a value: the oiperation was successfull or not.
If not you cannot continue with the next operation (call the second php) but you need to stop. Instead if you get a successfull result you may see what is changed in the previous done function: now the test is much more easy and the parameters to pass to the second php are very easy.
I am using jquery to make a .php file execute but my major problem is when ever a error is thrown from back-end i used a alert to display that error_msg..but ever i submit with a error intentionally...its just moving on to page specified in action...no error alert poped up...plz help me out of this.!!pardon me if am wrong
here gose the DB_Function.php
<?php
class DB_Functions {
private $db;
// constructor for database connection
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
die('Error in database requirments:' . $e->getMessage());
}
}
/**
* Storing new user
* returns user details of user
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
/*to check if user is
already registered*/
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
}
/*to check if user
exist's by mobile number*/
public function isMobileNumberExisted($mobile){
try{
$sql = "SELECT mobile FROM users WHERE mobile = '$mobile' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch(Exception $e){
die('Error accessing database: ' . $e->getMessage());
}
}
//DB_Functions.php under construction
//more functions to be added
}
?>
here gose the .php file to be clear on what am doing..!!
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate your password
if(strlen($password) > 6){
//validate your mobile
if(strlen($mobile) == 12){
//Check for valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}
} else {
$response["error"] = true;
$response["error_msg"] = "Mobile number is invalid!";
echo json_encode($response);
}
} else {
//min of 6-charecters
$response["error"] = true;
$response["error_msg"] = "password must be of atleast 6-characters!";
echo json_encode($response);
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
and here gose the main file .js
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
e.preventDefault();
}
});
});
});
and here gose the corresponding .html file
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjh8AG"></div>
<!-- End Thumbnail-->
</div>
<?php include("js/captcha.php");?>
</div>
<div class="form-group">
<div cle the terms and policy </label></div>
</div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
<
/form>
From the comments:
So only after displaying Registeration successful! I want to submit the form and redirect it to login.html
Well the solution is quite simple and involved adding and setting async parameter to false in .ajax(). Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
Your jQuery should be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
So the form will only get submitted if the registration is successful, otherwise not.
Edited:
First of all make sure that <!DOCTYPE html> is there on the top of your page, it stands for html5 and html5 supports required attribute.
Now comes to your front-end validation thing. The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method.
For the purpose of simplicity I removed your terms and conditions checkbox and Google ReCaptcha. You can incorporate those later in your code.
So here's your HTML code snippet:
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required />
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required />
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required />
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required />
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required />
</div>
<!--Your checkbox goes here-->
<!--Your Google ReCaptcha-->
<input type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b" value="Register" />
</form>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
And your jQuery would be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
your form submit takes action before ajax action so its reloading the page and use form submit instead of submit button click
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
Ok steps to be sure that everthing works fine while you try to use ajax
1st : use form submit and use e.preventDefault(); to prevent page reloading
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
alert('Form submited');
});
if the alert popup and form not reloading the page then the next step using ajax
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
$.ajax({
url: "register.php",
type: "POST",
dataType: "JSON",
data: {success : 'success'},
success : function(data){
alert(data);
}
});
});
and in php (register.php)
<?php
echo $_POST['success'];
?>
this code should alert with "success" alert box .. if this step is good so now your ajax and php file is connected successfully then pass variables and do another stuff
I am simply trying to use the data submitted in a search form to query the database and bring back results similar to the search. My form looks like this:
<div id="searchform">
<form method="get">
<form id="submitsearch">
<input id="shop" name="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="submit" value="Go"/>
</form>
</form>
<div id="searchresults">
</div>
</div>
the Javascript I've got is:
$("#submitsearch").submit(function(event) {
event.preventDefault();
$("#searchresults").html('');
var values = $(this).serialize();
$.ajax({
url: "external-data/search.php",
type: "post",
data: values,
success: function (data) {
$("#searchresults").html(data);
}
});
});
return false;
I have also tried...
$("#submitbutton").click(function(){
var form_data = $("#submitsearch").serialize();
$.ajax({
url: "external-data/search.php",
type: 'POST',
data: form_data,
success: function (data) {
$("#searchresults").html(data);
}
});
return false;
});
And this seems to work slightly as it shows results, the first doesn't do anything. It's not sending the data to the PHP page but the PHP I've got is:
<?php
$str_shops = '';
$shop = $_POST['form_data'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE name LIKE '%$shop%'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<strong>" . $row['name'] . "</strong><br>" .
$row['address'] . "<br><br>";
}
mysqli_free_result($result);
echo $str_shops;
mysqli_close($db_server);
?>
Any help would be greatly appreciated! Thanks in advance.
You have two form tags. This won't work. You want one form tag with two attributes
<form method="get">
<form id="submitsearch">
to
<form method="get" id="submitsearch">
you can do it without using html form.
first you call the php page and then display a data within html.
this is what I do?!
<div>
<input id="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="button" value="Go"/>
</div>
<div id="searchresults">
</div>
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function(){
try
{
$.post("root/example.php",
{
'shop':$("#shop").val().trim()
}, function(data){
data=data.trim();
$("#searchresults").html(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>