I have a registration form which when filled and "Register" button pressed is being checked by js, to find empty fields and to check availability of username, or if email or mobile num was already used by sending info through ajax to php and receiving answer. But my js won't work all the way through. This is my js script:
$("#reg_button").click(function(){
user = $("#usr").val();
pass = $("#psw").val();
fname = $("#first_name").val();
sname = $("#second_name").val();
dateb = $("#date_birth").val();
email = $("#email").val();
mobnum = $("#mob_num").val();
if(user == ""){
alert("First name must be filled out");
$('#usr').focus();
return false;
}else if(pass == ""){
alert("Password must be filled out");
$('#psw').focus();
return false;
}else if(fname == ""){
alert("First name must be filled out");
$('#first_name').focus();
return false;
}else if(sname == ""){
alert("Second name must be filled out");
$('#second_name').focus();
return false;
}else if(dateb == ""){
alert("Date of birth must be filled out");
$('#date_birth').focus();
return false;
}else if(email == ""){
alert("Email must be filled out");
$('#email').focus();
return false;
}else if(mobnum == ""){
alert("Mobile number must be filled out");
$('#mob_num').focus();
return false;
}else{
ajaxCheck();
}
function ajaxCheck(){
$.ajax({
type: "POST",
url: "http://imes.*********.com/php/check_info_reg.php",
data: "usr="+user+"&email="+email+"&mob_num="+mobnum,
dataType: "json",
success: function(json){
if(json.success){
var user_conf = json.data.usr;
var email_conf = json.data.email;
var mob_conf = json.data.mob;
if(user_conf == "taken"){
alert("Username already taken. Choose another one.");
$('#usr').focus();
return false;
}
if(email_conf == "taken"){
alert("Email already registered. If you lost your password, retrieve it on login page.");
$('#email').focus();
return false;
}
if(mob_conf == "taken"){
alert("Mobile number already registered. If you lost your password, retrieve it on login page.");
$('#mob_num').focus();
return false;
}
}else{
//Here could go another ajax, for actualy sending the
//info into the php script which sends it to database.
}
},
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
});
return false;
}
});
And my php:
<?php
$username = mysql_real_escape_string($_POST['usr']);
$email = mysql_real_escape_string($_POST['email']);
$mob_num = mysql_real_escape_string($_POST['mob_num']);
include('mysql_connection.php');
mysql_select_db("jzperson_imesUsers", $con);
$sql1 = mysql_query("SELECT * FROM registered_user WHERE username='$username'");
$sql2 = mysql_query("SELECT * FROM registered_user WHERE email='$email'");
$sql3 = mysql_query("SELECT * FROM registered_user WHERE mobile_num='$mob_num'");
$res1 = mysql_num_rows($sql1);
$res2 = mysql_num_rows($sql2);
$res3 = mysql_num_rows($sql3);
if(isset($username) && !empty($username){
if($res1 >= 1){
//JSON message: Username already taken. Choose different.
echo json_encode(array('success'=>true, 'usr'=>"taken"));
}
}
elseif(isset($email) && !empty($email)){
if($res2 >= 1){
//JSON message: Email already registered. Retrieve on "login"(login => link).
echo json_encode(array('success'=>true, 'email'=>"taken"));;
}
}
elseif(isset($mob_num) && !empty($mob_num)){
if($res3 >= 1){
//JSON message: Mobile number already registered. Retrieve on "login"(login => link).
echo json_encode(array('success'=>true, 'mob'=>"taken"));
}
}
else{
echo json_encode(array('success'=>false));
}
?>
You are missing a parenthesis in your php file:
if(isset($username) && !empty($username){
Should be
if(isset($username) && !empty($username)){
Related
i want to validate login form using ajax success response is working but if all goods it should be redirect to index page but it's not working , i don't understand what's wrong please help. thanks in advance..
$(document).ready(function(){
var response;
$('#submit').click(function(e){
e.preventDefault();
$('.alert-box').html('<div id="loading" style="margin: 0 auto;" >
</div>');
var action = 'ajax_validation';
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url:"do_login.php",
method:"POST",
data:{action:action, username:username, password:password},
success:function(data){
response = data;
if(response === 1){
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response);
}
}
});
});
});
above these ajax request
this is action page code
include('includes/db.php');
if(isset($_POST["action"])){
$check_username = $_POST['username'];
$check_password = $_POST['password'];
if(empty($check_username) && empty($check_password)){
echo "Please fill all field";
}else{
$query = "SELECT * FROM user WHERE email = '{$check_username}' AND password = '{$check_password}' ";
$select_query=mysqli_query($connection,$query);
if(!$select_query){
die("QUERY FAILED".mysqli_error($select_query));
}
if(mysqli_num_rows($select_query)==0){
echo "Username or password are incorrect!";
}else{
while ($row=mysqli_fetch_assoc($select_query)) {
$_SESSION['username'] = $row['email'];
echo $row['email'];
}
}
}
}
In your resposne you are echoing
echo $row['email'];
This should be:
echo 1;
Your problem is that you are checking if value is 1 in ajax:
success:function(data){
response = data;
if(response === 1){ //<- there you are checking if your echo is 1 but you are trying to echo $row['email'];
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response);
}
}
change your echo from $row['email'] to 1
I think that the problem is response checking condition in ajax success.
You're checking if a string (email or error message) is equal and the same type of 1.
...
dataType: 'json',
success:function(data){
response = data;
if(response === 1){
...
You can use a json response with status/error code:
...
success:function(data){
response = JSON.parse(data);
if(response.status === 1){
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response.data);
}
}
...
$check_username = $_POST['username'];
$check_password = $_POST['password'];
$res = array('status'=> 0, 'data' => '');
if(empty($check_username) && empty($check_password)){
$res['status'] = 0;
$res['data'] = "Please fill all field";
}else{
$query = "SELECT * FROM user WHERE email = '{$check_username}' AND password = '{$check_password}' ";
$select_query=mysqli_query($connection,$query);
if(!$select_query){
$res['status'] = 0;
$res['data'] = "QUERY FAILED".mysqli_error($select_query);
echo json_encode($res);
return;
}
if(mysqli_num_rows($select_query)==0){
$res['status'] = 0;
$res['data'] = "Username or password are incorrect!";
}else{
while ($row=mysqli_fetch_assoc($select_query)) {
$_SESSION['username'] = $row['email'];
$res['status'] = 1;
$res['data'] = "".$row['email'];
}
}
}
echo json_encode($res);
In addition i suggest to put only the username in query where condition and check if the password match with php.
After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
I am building a website that has a reservation. I use ajax to send information from forms into the another page which insert the information into my database. To make it even useful, I want to make a test connection into my database. After a user fills up all the fields required he will click the submit button and a test connection must check first before sending the data. And when the connection fails, it will tell the user that the connection is not set(maybe his internet connection is lost, or the server itself is failing). In that way, the website prevents prompting the user that their reservation data is sent, but actually NOT.
EDITED:
Here's my running and fixed code:
$("#esubmit2").click(function(){
var event2 = document.getElementsByName("eevent2")[0].value;
var engager2 = document.getElementsByName("eengager2")[0].value;
var contact2 = document.getElementsByName("econtact2")[0].value;
var eadd2 = document.getElementsByName("eeadd2")[0].value;
var venue2 = document.getElementsByName("evenue2")[0].value;
var datein2 = document.getElementsByName("edatein2")[0].value;
var message2 = document.getElementsByName("emessage2")[0].value;
var reg2 = /^(([^<>()[\]\\.,;:\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,}))$/;
if(event2 == "" || event2 == " "){
$("#eevent2").focus();
return false;
}
else if(engager2 == "" || engager2 == " "){
$("#eengager2").focus();
return false;
}
else if(contact2 == "" || contact2 == " "){
$("#econtact2").focus();
return false;
}
else if(venue2 == "Venue:"){
$("#evenue2").focus();
return false;
}
else if(datein2 == "" || datein2 == " "){
$("#edatein2").focus();
return false;
}
else if(message2 == "" || datein2 == " "){
$("#emessage2").focus();
return false;
}
else if(eadd2 != ""){
if(reg2.test(eadd2) == false){
$("#eeadd2").focus();
$("#eeadd2").css("backgroundColor","#800517");
$("#eeadd2").css("color","#FFFFFF");
return false;
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
})
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string,
success: function(json) {
if(json == 1){
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").val("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
return false;
}
else{
alert("Sorry for the inconvenience but the connection to our database failed.\nPlease check you internet connection or refresh you page.\n\nIf one of the above failed please report to our admin.\nThank You.");
return false;
}
}//end success function
}); //end ajax call
return false; // IMPORTANT
}
submitreserve_eventpc.php:
if($test){
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$ok = 1;
}
else{
$ok = 0;
}
echo json_encode($ok);
If there's any improvement that you see please edit. For now this met my needs :)
You should do something like this.
Your php.file
<?php
$con=mysql_connect('localhost','root','root');
if($con){
// do insertion data here into the database
$sql = "Insert into table query";
if($sql){
echo "Data inserted successfully";
}else{
echo "Sorry! some error occured ".mysql_error();
}
}else{
echo "Unable to connect to the server";
}
?>
You could try something like this.
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string
}).done(function(data) {
data = $.parseJSON(data);
message = data.message;
if (message == "success")
{
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").text("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
$("#esubmit2").blur();
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
} else {
console.log(message);
}
});
return false; // IMPORTANT
}
In your PHP file could be changed to what is below.
$myDatabase = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$myDatabase)
{
$message = 'Could not connect: ' . mysql_error();
} else {
$event2 = $_POST['eevent2'];
$engager2 = $_POST['eengager2'];
$contact2 = $_POST['econtact2'];
$eadd2 = $_POST['eeadd2'];
$venue2 = $_POST['evenue2'];
$datein2 = $_POST['edatein2'];
$message2 = $_POST['emessage2'];
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$message = 'success';
}
$response = array('message' => $message);
echo json_encode($response); // This is the data that your AJAX function gets in .done
I have a form that will be validated client side before being submitted via an ajax request to the server for server-side validation. Should the validation fail server side then a postback will need to be made containing all the error messages. Is there some way I can do this?
For example:
if ((!empty($nameError) && (!empty($emailError)) {
$_POST['nameError'] = $nameError;
$_POST['emailError'] = $emailError;
// send postback with values
}
else {
echo 'No errors';
}
UPDATE ------------------------------------------------
Here is the javascript that handles the submission of the form:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if ((name == "") || (name.length < 4)){
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if (phone == "") {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var comment = $.trim($("#comments").val());
if ((!comment) || (comment.length > 100)) {
$("label#commentErr").show();
$("#comments").focus();
alert("hello");
return false;
}
var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
$(":input").val('');
return false;
});
And here is the php function that the ajax posts to:
function submit_data() {
$nameErr = $emailErr = $phoneErr = $commentErr = "";
$full = explode("&", $_POST["info"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$fcomment = explode(":", $full[3]);
$comment = $fcomment[1];
if ((empty($name)) || (strlen($name) < 4)){
$nameErr = "Please enter a name";
}
else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Please ensure you have entered your name and surname";
}
if (empty($email)) {
$emailErr = "Please enter an email address";
}
else if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Please ensure you have entered a valid email address";
}
if (empty($phone)) {
$phoneErr = "Please enter a phone number";
}
else if (!preg_match("/(?:\(?\+\d{2}\)?\s*)?\d+(?:[ -]*\d+)*$/",$phone)) {
$phoneErr = "Please ensure you have entered a valid phone number";
}
if ((empty($nameErr)) && (empty($emailErr)) && (empty($phoneErr)) && (empty($commentErr))) {
$conn = mysqli_connect("localhost", "John", "Change9", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone, Comment) VALUES ('$name', '$email', '$phone', '$comment')");
}
else {
// display error messages
}
die();
}
Your answer will be in two parts:
Pseudo code:
Part1: PHP
if ($error) {
$reply["status"]=false;
$reply["message"]="Fail message"; //Here you have to put your own message, maybe use a variable from the validation you just did before this line: $reply["message"] = $fail_message.
}
else {
$reply["status"]=true;
$reply["message"]="Success message"//$reply["message"] = $success_message;
}
echo json_encode($reply);//something like {"status":true, "message":"Success message"}
Part2 AJAX: modify you ajax response to this.
success: function(response) {
if (response.status == true) {
alert("success: "+response.message);
}
else {
alert("fail: " + response.message);
}
}
Use json ajax request. In case error exists show the error message. I generally put a flag for success or fail .
$message='';
if ((!empty($nameError) && (!empty($emailError)) {
$errorArray=array();
$errorArray['nameError'] = $nameError;
$errorArray['emailError'] = $emailError;
// send postback with values
}
else {
$message='No errors';
}
echo json_encode(array(
"message"=>$message,
"errors"=>$errorArray
));
Guys I'm trying to make a Log in form by using Ajax and PHP. Every-time when I submit the form I'm getting the right response, but the problem here is that I have an "IF CONDITION" in my Javascript file did not execute while I get a "success" response. I don't know why. This is my code, please anybody help.
Ajax File
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Javascript File handling Log in - The problem is here in this file
function signin(){
var logstat = _("logstat");
var loge = _("SignInEmail").value;
var logp = _("SignInPasswordActive").value;
if(loge == "" || loge == "Email address" || logp == ""){
logstat.innerHTML = "Fill out all of the form data.";
} else {
_("loginbtn").style.display = "none";
logstat.innerHTML = 'please wait ...';
var ax = ajaxObj("POST", "signin.php");
ax.onreadystatechange = function() {
if(ajaxReturn(ax) == true) {
if(ax.responseText != "success"){
logstat.innerHTML = ax.responseText;
_("loginbtn").style.display = "block";
} else {
//Here is the problem I get success in Ajax Response, but this condition did not run
logstat.innerHTML = "login success";
_("loginbtn").style.display = "block";
}
}
}
ax.send("le="+loge+"&lp="+logp);
}
}
PHP File
<?php
if(isset($_POST['le']) && isset($_POST['lp'])){
$p = $_POST['lp'];
require_once('includes/database.php');
include_once('randStrGen.php');
$e = $_POST['le'];
$p_hash = md5($p);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if($e == "" || $e == "Email address" || $p == ""){
echo "Fill out all of the form data.";
exit();
} else {
$sql = "SELECT id, email, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db->connection, $sql);
$numrows = mysqli_num_rows($query);
if($numrows == 0){
echo "This account is not exist";
exit();
}else{
$row = mysqli_fetch_array($query);
$db_id = $row['id'];
$db_em = mysqli_real_escape_string($db->connection, $row['email']);
$db_ps = substr($row['password'],10,-10);
if($p_hash != $db_ps){
echo "Email or Password combination failed";
exit();
}else{
//This is the successful Log in condition
echo "success";
exit();
}
}
exit();
}
exit();
}
?>
Try swaping the condition so checking if it's equals (even ===) to 'success' and do the rest in the else clause