Ajax is not sending data to PHP - javascript

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

Related

Autofill Form Not Working

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() },

Ajax call php function breaks all javascript functions and page

I'm trying to validate if a username is already taking or not. This onchange of an input field. I already got other checks but they don't work anymore since I added the ajax call. I'm new to ajax and javascript so the error can be there.
the html form:
<form action="test" method="post">
<input id="username" type="text" placeholder="Gebruikersnaam" name="username" required onchange="checkUserName()">
<br>
<input id="email" type="text" placeholder="Email" name="email" required onchange="validateEmail()">
<br>
<input id="pass1" type="password" placeholder="Type wachtwoord" name="password1" required>
<br>
<input id="pass2" type="password" placeholder="Bevestig wachtwoord" name="password2" required onchange="passwordCheck()">
<br>
<select name="typeAccount">
<option value="bedrijf">Bedrijf</option>
<option value="recruiter">Recruiter</option>
<option value="werkzoekende">Talent zoekt job</option>
</select>
<p id="demo1">
</P>
<p id="demo2">
</P>
<button type="submit">Scrijf mij in!</button>
</form>
the javascript that I use:
<script src="jquery.js">
function passwordCheck(){
var password1 = document.getElementById('pass1').value;
var password2 = document.getElementById('pass2').value;
if(password1 !== password2){
document.getElementById("pass1").style.borderColor = "#ff3333";
document.getElementById("pass2").style.borderColor = "#ff3333";
}else{
document.getElementById("pass1").style.borderColor = "#1aff1a";
document.getElementById("pass2").style.borderColor = "#1aff1a";
}
}
function validate(email){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateEmail(){
var email = document.getElementById('email').value;
if(validate(email)){
document.getElementById("email").style.borderColor = "#1aff1a";
}else{
document.getElementById("email").style.borderColor = "#ff3333";
}
}
function checkUserName(){
var username = document.getElementById('username').value;
if(username === ""){
document.getElementById("username").style.borderColor = "#ff3333";
}else{
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
}
}
</script>
The php script I use this is in a different file:
<?php
include("connect.php");
$connect = new Connect();
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query('select username from usermaindata where username = "'. $username .'"');
if(mysql_num_rows($result)>0){
echo 0;
}else{
echo 1;
}
?>
The script and the html form is in the same html-file and the php is in a seperate PHP-file.
I just want to check if the name is already in the database or not.
I assume your database connection is perfect.
$username = mysql_real_escape_string($_POST['username']);
change above code to
$username = mysqli_real_escape_string($db_connection,$_REQUEST['action']);
because in your ajax you're doing like
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
You have not specified request type and you're fetching value using $_POST with different variable name username which is actually value
You should use $_REQUEST['action']
And make sure you've added jquery.js file in your html.

jQuery Ajax not working with $.ajax()

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>

back-end error_msg is not giving a alert..!

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

.val() doesn't work - can't find solution

$(document).ready(function() {
var login = $("#login").val();
var password = $('#password').val();
$('.login-button').click(function() {
alert(login);
});
});
HTML
<form method="post" class="login"> <p id="login-error"></p>
<p>
<label for="login">Username:</label>
<input type="text" name="login" id="login" placeholder="username">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" placeholder="password">
</p>
<p class="login-submit">
<button class="login-button">Login</button>
</p>
<p class="forgot-password">Fill your username and password.</p> </form>
It shows nothing! What's up with it? Any solution? The id names are correct
EDIT:
I have another problem. Dont want to open another question for that. I'm trying to get ajax answer from validate.php (it is in /views/admin/validate.php - it runs when opening domain.com/validate)
$(document).ready(function() {
$('.login-button').click(function() {
var login = $("#login").val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: '/view/admin/validate.php',
data: {
login : login,
password : password
},
success: function(data){
$('#login-error').html(data);
}
});
});
});
validate.php
<?php
session_start();
$user = mysql_real_escape_string($_POST['login']);
$password = mysql_real_escape_string(sha1($_POST['password']));
$query = mysql_query("SELECT * FROM `users` WHERE name = '$user' AND pass = '$password' AND privileges = 'superuser'");
$num_rows = mysql_num_rows($query);
if($num_rows == '0') {
echo "Username and Password are incorrect! (Maybe you don't have permission!)";
}
elseif($num_rows == '1') {
$expire = time()*60*60*60*60;
setcookie("user","$user",$expire);
$_SESSION['user'] = $user;
include '/views/admin/admin.php';
}
?>
It should return Username and Password are incorrect! (Maybe you don't have permission!) - but it doesn't.. Any solution??
var login = $("#login").val();
When this line runs, the input is empty.
You need to get the value after the user types something.
$('.login-button').click(function() {
var login = $('#login').val();
alert(login);
});
Try it :
$('.login-button').click(function() {
alert($("#login").val());
});
or :
$('.login-button').click(function() {
var login = $("#login").val();
alert(login);
});
or :
var login = "";
$('.login-button').click(function() {
login = $("#login").val();
alert(login);
});

Categories

Resources