JQuery validation not catching ajax response and setting variable to true - php

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

Related

sending variable in php to ajax function

How can i push variable to ajax function in php file (witch refers to ajax )
if i have $v in my php . if all is ok it's echo "ok" in php file .So what should i do next
if ($_POST){
for ($j=0; $j< count($row);$j++){
mysql_query("INSERT INTO `".PREFIX_USR."delivery_address` (`id_personl_data`,`country`,`province`,`city`,`street`,`house`,`apartment`)
VALUES ( '12','".$row[$j][0]."','".$row[$j][1]."','".$row[$j][2]."','".$row[$j][3]."','".$row[$j][4]."','".$row[$j][5]."') ");
var count = query['id']; // just an example of what i need to push
}
echo "ok";
}
js
(function(){
function changeData(){
var name = d.getElementById('new_name').value,
surname = d.getElementById('new_surname').value,
email = d.getElementById('new_email').value,
telephone = d.getElementById('new_phone').value,
robot = d.getElementById('spam_change').value,
xml = eventsObj.getXmlHttp();
var arr = [].map.call(document.querySelectorAll('.parent_clone'), function(block) {
return [].map.call(block.querySelectorAll('.left_info_address'), function(inp) {
return inp.value;
});
});
for (var i = 0; i<arr.length-1;i++){
arr[i].push('/');
}
console.log(arr);
if(name === "" || surname === "" || email === "" || (telephone === "")){
alert("fill the fields");
}
else {
xml.open("POST",path_ajax_files+"edit_personal_data.php",true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("name="+encodeURIComponent(name)+
"&surname="+encodeURIComponent(surname)+
"&email="+encodeURIComponent(email)+
"&telephone="+encodeURIComponent(telephone)+
"&robot="+encodeURIComponent(robot)+
"&arr="+encodeURI(arr));
xml.onreadystatechange = function(){
if(xml.readyState === 4){
if(xml.status === 200){
if(xml.responseText !== ""){
alert(xml.responseText);
if(xml.responseText === "ok"){
alert("data will be changed");
}
} else {
alert('try again later');
}
}
}
};
}
}
eventsObj.addEvent(saveData, "click", changeData, false);
})();

Ajax code doesn't work inside of jquery form validation

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')

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.

Javascript alert box and confirmation after

I want to create a javascript for checking value of textbox so if the textbox blank, it won't proceed to next page. AND after checking (if all condition is true) it will return the result of textbox.
I've created this javascript:
function cekdata(myform)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (document.myform.clientid.value == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
return false;
}
else
if (document.myform.nama.value == "")
{
alert("Please Fill Passenger Name");
myform.nama.focus();
return false;
}
else
if (document.myform.lokasi.value == "")
{
alert("Please Fill Origin Location");
myform.lokasi.focus();
return false;
}
else
if (document.myform.tujuan.value == "")
{
alert("Please Fill Your Destination");
myform.tujuan.focus();
return false;
}
else
if (document.myform.tglb.value == "")
{
alert("Please Fill Departure Date");
myform.tglb.focus();
return false;
}
else
if (document.myform.novehicle.value == "")
{
alert("Please Fill Vehicle Number");
myform.novehicle.focus();
return false;
}
else
if (document.myform.driverid.value == "")
{
alert("Please Fill Driver ID");
myform.driverid.focus();
return false;
}
else
if(document.getElementById('twoway').checked)
{
if (document.myform.tglp.value == "")
{
alert("Please Fill Return Date");
myform.tglp.focus();
return false;
}
else
if (document.myform.tglb.value > document.myform.tglp.value)
{
alert("Return date must bigger than departure date");
myform.tglp.focus();
return false;
}
}
else
{
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
if (a==true)
{
return true;
}
else
{
return false;
}
}
}
And I called this function like this:
<form name="myform" onsubmit="return cekdata(this);" method="POST" action="<?php $_SERVER["PHP_SELF"]; ?>">
But what I got is the confirm box never show up, and it returns true (and go to next page). So, how to change this condition so my confirmation box showed up first, then after click OK, it go to next page, and if CANCEL, do nothing?
*Just make slight changes in your javascript just passevent on form submit*
<input type="submit" value="Submit" name="submit" onClick="return cekdata(this,event);" />
and when your textbox is empty or null write event.preventDefault() instead of return false;
function cekdata(myform,evt)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (document.myform.clientid.value == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
evt.preventDefault();
}
Try this:
Remove your last else part and paste below lines at the end of your javascript function.
Remove below lines :
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
instead use this,
var a = window.confirm("Are you sure?");
if (a==true)
{
return true;
}
else
{
return false;
}
I would better suggest you to place that cekdata(this) in your submit tag rather than form tag. Like
<input type="submit" value="Submit" name="submit" onClick="return cekdata();" />
And also when you have done this
var id = document.myform.clientid.value;
Then why you are using again the same
if (document.myform.clientid.value == "")
Better use
var id = document.myform.clientid;
if (id.value == "")
{
alert("Please Fill Your ID");
id.focus();
return false;
}
Changing code like this:
function cekdata(myform)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (id == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
return false;
}
else
if (nama == "")
{
alert("Please Fill Passenger Name");
myform.nama.focus();
return false;
}
else
if (ori == "")
{
alert("Please Fill Origin Location");
myform.lokasi.focus();
return false;
}
else
if (desti == "")
{
alert("Please Fill Your Destination");
myform.tujuan.focus();
return false;
}
else
if (tpergi == "")
{
alert("Please Fill Departure Date");
myform.tglb.focus();
return false;
}
else
if(document.getElementById('twoway').checked)
{
if (tplg == "")
{
alert("Please Fill Return Date");
myform.tglp.focus();
return false;
}
else
if (tpergi > tplg)
{
alert("Return date must bigger than departure date");
myform.tglp.focus();
return false;
}
}
else
{
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
if (a==true)
{
return true;
}
else
{
return false;
}
}
}
then it works...
I would recommend using Jquery insead of Javascript.
Here is the short & sweet code I have made just for you, feel free to use it!
JQUERY CODE
$(document).ready(function() {
$('#submit').click(function(){
var id = $('#id').val();
var dataString = 'id='+ id;
if(id==''){
alert("Please Fill Your ID");
$('#id').focus();
return false;
}
else if(confirm("Are you sure? Your id = "+id))
{
$.ajax({
type: "POST",
url: "ajxRegistration.php",
data: dataString,
cache: false,
success: function(e)
{
e.stopImmediatePropagation();
}
});
return false;
}
});
})
Try this -
if(confirm('Are you sure?'))
return true;
else
return false;

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