Ajax code doesn't work inside of jquery form validation - php

I want to write (register section) code that can check if email have been used in past or the login is empty.
The code is working fine, but my ajax code dont run at all.
I checked everything, path to php file is good, variables are good etc. Don't how to solve it.
Code:
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var self = $(this);
var $name = self.find('[type=name]');
var $email = self.find('[type=email]');
var $pass = self.find('[type=password]');
var emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailRegex.test($email.val())) {
createErrTult("Błąd! Email ma zły format!", $email)
error++;
}
//MY AJAX CODE
var email = $email.val();
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
}
});
if ($name.val().length > 1 && $name.val() != $name.attr('placeholder')) {
$name.removeClass('invalid_field');
} else {
createErrTult('Error! Wrong name!', $name)
error++;
}
if ($pass.val().length > 1 && $pass.val() != $pass.attr('placeholder')) {
$pass.removeClass('invalid_field');
} else {
createErrTult('Error! Wrong password!', $pass)
error++;
}
if (error != 0) return;
self.find('[type=submit]').attr('disabled', 'disabled');
self.children().fadeOut(300, function() {
$(this).remove()
})
$('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
.hide().delay(300).fadeIn();
// var formInput = self.serialize();
// $.post(self.attr('action'),formInput, function(data){}); // end post
});
php:
<?php
include ("config.php");
if($action == "emailcheck"){
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo json_encode($dodano);
}
?>

First, you should try adding error callback:
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
This may alert you about some occured error.
Second, you can try to use json instead of plain text:
Client-side:
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
dataType: 'json', // THIS ROW
type: 'POST',
success: function(odp) {
if (odp['result'] == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
},
error: function(xhr, textStatus, error)
{
alert(error);
}
});
Server-side:
<?php
include ("config.php");
if (isset($_GET['action'])){
$action = $_GET['action'];
if($action == "emailcheck") {
if(isset($_GET['email'])) {
$email = $_GET['email'];
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo (json_encode(array("result" => $dodano))); // THIS ROW
}
}
}
}
?>

before everything check you config.php file path .. In your case config.php should be in the same path with rejestracja.php and try this.. lets start with ajax
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
email: email
},
type: 'GET',
success: function(odp) {
if (odp == 1) {
alert('Email exists');
}else{
alert('Email dosen\'t exists');
}
}
});
then in php
<?php
include ("config.php");
if (isset($_GET['action'])){
$action = $_GET['action'];
if($action == "emailcheck"){
if(isset($_GET['email'])){
$email = $_GET['email'];
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo ($dodano);
}
}
}
?>
you should get alert with ('Email exists')

Related

JQuery validation not catching ajax response and setting variable to true

I have a HTML form that when posted fires an JQuery script to check a validation function before sending data to an ajax call to insert the data into a mySQL database.
It works as it should, except when it is running an ajax check to see if the posted email address already exists in the database.
I need the email_error var to return true if the response from the ajax call is not 'success'. My code:
function validate_add_relative() {
var check_error = false;
var email_error = false;
var title = document.forms["add_relative_form"]["title"].value;
if (title == null || title == "") {
check_error = true;
}
var first_name = document.forms["add_relative_form"]["first_name"].value;
if (first_name == null || first_name == "") {
check_error = true;
}
var surname = document.forms["add_relative_form"]["surname"].value;
if (surname == null || surname == "") {
check_error = true;
}
var phone = document.forms["add_relative_form"]["phone"].value;
if (phone == null || phone == "") {
check_error = true;
}
var email = document.forms["add_relative_form"]["email"].value;
if (email == null || email == "") {
check_error = true;
}
var address = document.forms["add_relative_form"]["address"].value;
if (address == null || address == "") {
check_error = true;
}
var postData = $(this).serializeArray();
$.ajax(
{
url : '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR) {
if(data == 'success') {
email_error = false;
return true;
}
else {
alert('test');
email_error = true;
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Error. Please try again later.');
email_error = true;
}
});
if (email_error == true) {
alert("Please choose another email address, that one is already in use.");
return false;
}
if (check_error == true) {
alert("Please ensure you fill in all mandatory fields.");
return false;
}
if (email_error == false && check_error == false) {
return true;
}
}
$('.add_relative_form').submit(function(e) {
e.preventDefault();
if(validate_add_relative()) {
var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
form_data = $('.add_relative_form').serialize();
$.post(ajaxurl, form_data, function (response) {
//location.reload();
});
}
});
When running the above code, the first part (Form validation) works as it should, and it also gives the alert and does the class hiding after. But it carries on and is not catching the fact that email_error is set to true after the alert line. So it continues through the code and adds the entry through the last ajax post controllers/ajax/add_relative.php
add complete function after error and write your code inside that function
complete:function(data, textStatus, jqXHR) {
if(data == 'success') {
email_error = false;
return true;
}
else {
alert('test');
email_error = true;
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
}
},
JavaScript is asynchronous in the sense that it can make, for example, Ajax calls. Hence your outer conditions will get mislead. Try to add return statement inside AJAX response for expected result.
Please try following solution
function validate_add_relative() {
var check_error = false;
var email_error = false;
var title = document.forms["add_relative_form"]["title"].value;
if (title == null || title == "") {
check_error = true;
}
var first_name = document.forms["add_relative_form"]["first_name"].value;
if (first_name == null || first_name == "") {
check_error = true;
}
var surname = document.forms["add_relative_form"]["surname"].value;
if (surname == null || surname == "") {
check_error = true;
}
var phone = document.forms["add_relative_form"]["phone"].value;
if (phone == null || phone == "") {
check_error = true;
}
var email = document.forms["add_relative_form"]["email"].value;
if (email == null || email == "") {
check_error = true;
}
var address = document.forms["add_relative_form"]["address"].value;
if (address == null || address == "") {
check_error = true;
}
if(check_error===false){
var postData = $(this).serializeArray();
$.ajax(
{
url : '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR) {
if(data == 'success') {
return true;
}
else {
alert('test');
return false;
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Error. Please try again later.');
return false;
}
});
}
else{
return false;
}
}
$('.add_relative_form').submit(function(e) {
e.preventDefault();
if(validate_add_relative()) {
var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
form_data = $('.add_relative_form').serialize();
$.post(ajaxurl, form_data, function (response) {
//location.reload();
});
}
});
UPDATES
change following code :
if(data == 'success') {
return true;
}
else {
alert('test');
return false;
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
}
To
if(data == 'success') {
return true;
}
else {
alert('test');
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
return false;
}
You can check, if the email already exists by using .blur() as soon after the user enters their email, you send AJAX call to check if the email exists and disable the submit button and show proper message to the user.
Form
<form action="" name="add_relative_form" class="add_relative_form">
<input type="text" name="title">
<input type="text" name="first_name">
<input type="text" name="surname">
<input type="text" name="phone">
<input type="text" id="email" name="email"> <!-- give email an id -->
<input type="text" name="address">
<input type="submit" id="sub" value="Sub"> <!-- give submit an id -->
Javascript
function validate_add_relative() {
var check_error = false;
var email_error = false;
var title = document.forms["add_relative_form"]["title"].value;
if (title == null || title == "") {
check_error = true;
}
var first_name = document.forms["add_relative_form"]["first_name"].value;
if (first_name == null || first_name == "") {
check_error = true;
}
var surname = document.forms["add_relative_form"]["surname"].value;
if (surname == null || surname == "") {
check_error = true;
}
var phone = document.forms["add_relative_form"]["phone"].value;
if (phone == null || phone == "") {
check_error = true;
}
var email = document.forms["add_relative_form"]["email"].value;
if (email == null || email == "") {
check_error = true;
}
var address = document.forms["add_relative_form"]["address"].value;
if (address == null || address == "") {
check_error = true;
}
if (email_error == true) {
alert("Please choose another email address, that one is already in use.");
return false;
}
if (check_error == true) {
alert("Please ensure you fill in all mandatory fields.");
return false;
}
if (email_error == false && check_error == false) {
return true;
}
}
$('.add_relative_form').submit(function (e) {
e.preventDefault();
if (validate_add_relative()) {
var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
form_data = $('.add_relative_form').serialize();
$.post(ajaxurl, form_data, function (response) {
//location.reload();
console.log(response)
});
}
});
$('#email').on('blur', function () {
$.ajax({
url: '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
type: "POST",
data: {email: $(this).val()},
success: function (data, textStatus, jqXHR) {
if (data == 'success') {
$('#sub').prop('disabled', false);
}
else {
$('.relative_email_error').show();
$('.relative_email_error').html('Email is already in use. Please choose another.');
$('#sub').prop('disabled', true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Error. Please try again later.');
}
});
})
Then in your PHP get the email from post
<?php
$email = $_POST['email'];
// your SQL code here

Cannot get data from json_encode in jQuery AJAX with php

I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.
The status is OK, but the responseText is undefined.
$(document).ready(function () {
$("#comments_form").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'process_in.php',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
var x = jQuery.parseJSON(result);
alert(x.f);
},
});
});
})
<?php
include ('connection.php');
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
}
function xssafe($d)
{
$x = filter_var($d, FILTER_SANITIZE_STRING);
return $x;
}
A good practice is to always catch the errors too. In your ajax request there is no error callback to handle the exception.
Use dataType: "JSON" instead of jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.
$.ajax({
type: 'POST',
url: 'process_in.php',
dataType: 'JSON',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
console.log(result.f);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
You can learn how to debug the code and check your error logs
Now lets get to your code, there are many possible cases that you are not getting the value.
It could be your php code or it could be your jquery.
In php to check whether its returning a valid json hit the url in browser like this
http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo
As in your php code you haven't return any value so add an else part for the
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
} else {
echo json_encode(['error'=>'Invalid request']);
}

CodeIgniter + jQuery Ajax runs error but successfully callback is called

My Codeigniter: (Do you think there is an error?)
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
My jQuery Code: (Do you think there is an error?)
$(".submit").on("click", function(){
var kuladi = $("#kullaniciadi").val();
var email = $("#email").val();
var sifre = $("#sifre").val();
var confirm = $("#sifreonay").val();
var hata = $("#hata").val();
var checkbox = $("#checkbox").is(":checked");
var link = "http://tantunisiparis:8080/main/anasayfa/KayitOl";
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
if (!kuladi || !email || !sifre) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Boş bırakılan alanlar var!");
}
else if (!pattern.test(email)) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Lütfen geçerli bir e-mail giriniz!");
}
else if (!checkbox) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Kullanıcı Sözleşmesini Kabul Etmediniz.");
}
else if (sifre != confirm) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Şifreler eşleşmiyor!");
}
else{
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
console.log(data.status);
alert("Success döndü");
},
error: function (data){
console.log(data.status);
alert("Error döndü");
}
});
}
});
Why I am having a problem like this?
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
You need to set HTTP status code. So in case of error call this code in the controller $this->output->set_status_header(500);.
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
$this->output->set_status_header(500); // or any other code
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
You can read more about output class in the docs http://www.codeigniter.com/userguide3/libraries/output.html
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
if(data.status == 'success'){
console.log(data.status);
alert("Success döndü");
}
if(data.status == 'error'){
console.log(data.status);
alert("Error döndü");
}
}
});
I thing, This code will work for you...

Validation for email availability if email exists with an alert using php [duplicate email]

I wrote some ajax validation for email check by verifying the availability using php the ajax script just displays whether email is available or not?
<script type="text/javascript">
$(document).ready(function()
{
$("#email_id").change(function(){
var email = $("#email_id").val();
var regdata = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(!(regdata).test($("#email_id").val()))
{
$("#email_id").css('border','1px solid red');
$("#email_id").focus();
$("#status").html("enter the valid emailid!");
return false;
}
else{
$("#email").css('border','1px solid #7F9DB9');
$("#email_id").html('Checking Email Availability...');
$.ajax({
type: "POST",
url: "fresherreg_email_avail.php",
data:"q="+ email,
success: function(server_response){
$("#status").ajaxComplete(function(event,request){
if(server_response == '0')
{
$("#status").html('Email Available');
}
else if(server_response == '1')
{
$("#status").html('Email Not Available');
}
});
}
});
}
});
});
</script>
and my php availability check code is
<?php
include_once("include_dao.php");
$q = $_REQUEST['q'];
if($q != "")
{
$row=DAOFactory::getTblFreshersRegistrationDAO()->queryByEmailId($q);
$num = count($row);
if($num > 0)
{
echo "1";
}
else
{
echo "0";
}
}
else
{
echo "Email Id should not be empty";
}
?>
what i need is?
it should show an alert using script until he choose a new mail id
It can be done this way . I will edit your code and add the required thing .
In the javascript/jquery part:
<script type="text/javascript">
$(document).ready(function()
{
$("#email_id").change(function(){
var email = $("#email_id").val();
var regdata = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(!(regdata).test($("#email_id").val()))
{
$("#email_id").css('border','1px solid red');
$("#email_id").focus();
$("#status").html("enter the valid emailid!");
return false;
}
else{
$("#email").css('border','1px solid #7F9DB9');
$("#email_id").html('Checking Email Availability...');
$.ajax({
type: "POST",
url: "fresherreg_email_avail.php",
data:"q="+ email,
success: function(server_response){
if(server_response == '0')
{
$("#status").append("<font color='green'>email available</font>");
}
else if(server_response == '1')
{
$("#status").append("<font color='red'>email already exits</font>");
}
else
{
$("#status").append("<font color='red'>"+server_response+"</font>");
}
}
});
}
});
});
</script>
Now in your php script .
<?php
include_once("include_dao.php");
$q = $_REQUEST['q'];
if($q != "")
{
$row=DAOFactory::getTblFreshersRegistrationDAO()->queryByEmailId($q);
$num = count($row);
if($num > 0)
{
echo "1";
}
else
{
echo "0";
}
}
else
{
echo "Email Id should not be empty";
}
?>
<script type="text/javascript">
$(document).ready(function(){
$('#submit');
var emaildone = false;
var myRegForm = $("#registration"),email = $("#email_id"), status = $("#status");
myRegForm.submit(function(){
if(!emaildone)
{
alert("Email Id Already Exists!!! So Please Try Another Email Id");
email.attr("value","");
email.focus();
return false;
}
});
email.blur(function(){
$.ajax({
type: "POST",
data: "q="+$(this).attr("value"),
url: "fresherreg_email_avail.php",
beforeSend: function(){
status.html('<img src="images/loader.gif" align="absmiddle"><font color="blue">Checking Email Availability...</font>');
},
success: function(data){
if(data == "invalid")
{
emaildone = false;
status.html("<font color='red'>Inavlid Email!! Please Select a Vaild Email</font>");
}
else if(data != "0")
{
emaildone = false;
status.html('<img src="images/not_available.png" align="absmiddle"><font color="red">Email Already Exist</font>');
}
else
{
emaildone = true;
status.html('<img src="images/available.png" align="absmiddle"> <font color="green">Email Available</font>');
}
}
});
});
});
</script>
Change script to this.

ModalBox Email pass php variable to sms sender

Ok, so I use ModalBox to create an email form on my website..however, i need the modal box to send the email not to me, but to the user who added the car(its a car selling website), and so I need to pass the $email variable to the sendmessage.php.
This is what i did so far:
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
setTimeout("$.fancybox.close()", 10);
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>Se trimite...</em>");
$.ajax({
type: 'POST',
url: 'http://automoka.ro/sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Mesajul a fost trimis!</strong></p>");
setTimeout("$.fancybox.close()", 10);
$_POST['contact'] = $email;
});
}
}
});
}
});
});
and in the php sender :
$email = $_POST['contact'];
$sendto = $email;
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
What am I doing wrong? Please help....Thanks in advance!
EDIT:
Nevermind..figured it out!...I added another textarea which was hidden to the modalbox...and used post to get it to sendmessage.php.

Categories