I am having a problem setting a value to a variable. My code is as below.
function fpform(){
var response_new = '';
var password_reset = "";
var fpemail = $('#frgtpwd').val();
//var fpemail = document.getElementById('frgtpwd').value;
if (fpemail == ""){
$('span#fperror').text("insert your emal address");
//document.getElementById('fperror').innerHTML = "Insert your email address";
password_reset = 'no';
} else {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(fpemail)==false) {
$('span#fperror').text("Email address is not in valid format");
//document.getElementById('fperror').innerHTML = "Email address is not in valid format";
password_reset = 'no';
} else {
$("#loader").html('<img src="images/ajax-loader.gif" />');
$.post("forgot_password_process.php", {
email:fpemail
}, function(response){
response_new = response.trim();
}).success(function () {
if (response_new == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").empty();
password_reset = 'yes';
} else {
$("#loader").empty();
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
password_reset = 'no';
}
});
}
}
if (password_reset == "yes"){
alert(password_reset);
return true;
} else {
alert(password_reset);
return true;
}
}
The last if condition is checking if the password_reset variable is set to yes or not and returns true or false depending on that. But the alert displays blank value of the password_reset variable. I can't seem to find a problem behind this as the password_reset variable should get assigned before reaching the last if. can anyone please suggest a solution.
Kind Regards
$.post() is asynchronous, therefor the request hasn't completed when you alert the data. For this to work, you need to call the alert within the success-callback as well, to make sure that you have the data before you try to alert it. Another option would be to use a synchronous AJAX-call (this is rarely a good option though).
Update
Not sure why your function return true/false, but for that to work, you would have to make a synchronous AJAX-call, otherwise the outer function will return long before the AJAX-call completes, and at that point you don't know what the response is.
You should probably try to restructure your code to make the code that depend on the response of your outer function callable by the success-callback instead.
I was gonna post the same thing as as Christofer. Here's a fixed code sample. Just remove the last code block too.
.success(function () {
if (response_new == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").empty();
password_reset = 'yes';
alert 'yes';
return true;
} else {
$("#loader").empty();
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
password_reset = 'no';
alert 'no';
return false;
}
Related
So I'm running a script from my page using the Jquery post wrapper, and in chrome debugger the below cases happening:-
1) if the username is taken i'm getting `"taken"`
2) else it echo's nothing.
However, I cannot get to the alert('im here'); line it seems that if(data=="taken") statement is never run or always evaluating to false, which is not the case. What am I doing wrong?
Jquery
var flag;
$.post('welcome/check_username',{childname: $('#name').val()}, function(data){
if(data=="taken")
{
alert('im here');
return flag = true;
//tell user that the username already exists
}else{
return flag = false;
//username doesn't exist, do what you need to do
}
});
PHP
if ($this->Form_builder->check_unique_username($username, $childname))
{
echo "taken";
}
its always good to trim things. try
if(data.trim()=="taken")
Try this:
var flag;
var result = $.post('welcome/check_username',{childname: $('#name').val()});
result.done(function( data )
{
if(data=="taken")
{
alert('im here');
return flag = true;
//tell user that the username already exists
}else{
return flag = false;
//username doesn't exist, do what you need to do
}
});
Looking at the code, here are the sections I would check:
On the PHP side, check whether the function is properly getting the proper values in $username and $password. You can do this by modifying the PHP file like this:
if ($this->Form_builder->check_unique_username($username, $childname))
{
echo "taken";
}
else
{
echo $username." and ".$childname." is not taken";
}
Then on the jQuery side, before the if statement, do console.log(data) or alert(data) to see what is being returned. Perhaps, you are sending data by the POST method but the server side script expects the parameters via the GET method.
Hy I'm trying to validate the email address in a registration form. I want to check if the address exists in the database;
i have the following function:
function validateEmailRepeat(){
// check if email exists in the database;
var emailVal = $('#email').val();
// assuming this is a input text field
$.post('check_email.php', {'email' : emailVal}, function(data) {
if(data==1)
{
email.addClass("error");
emailInfo.text("Adress exists");
emailInfo.addClass("error");
dataExist=1;
}
else {
email.removeClass("error");
emailInfo.text("Valid adress");
emailInfo.removeClass("error");
dataExist=0;
}
});
if(dataExist==1)
return false;
else
return true;
}
the check_email.php looks like this:
require_once('db.php');
if (isset($_POST['email'])){
$email=mysqli_real_escape_string($con,$_POST['email']);
$sql = "SELECT * FROM users WHERE `username`='".$email."'";
$select=mysqli_query($con,$sql) or die("fail");
$row = mysqli_num_rows($select);
if ($row >0) {
echo 1;
}else echo 0 ;
}
else
echo "post error";
i'm new at this . So don't be to tough. thanks in advance.
LE:Sorry ! i forgot the question...
the problem is that my function returns true if I define var dataExist outside of the function form $.post
and if i let it like it is now in the function I get "dataExist is not defined " error and returns true
Le: the PHP returns the expected 1 and 0 just the way i wanted..
LE:
seems like defining the
var dataExist=0;
outside the function validateEmailRepeat() resolved the issue.
if there's another way more elegant please tell me because this seems a little stupid to me.
The problem is you cannot return the value into the called function, because ajax work asynchronously.
function validateEmailRepeat(){
// check if email exists in the database;
var emailVal = $('#email').val();
// assuming this is a input text field
$.post('check_email.php', {'email' : emailVal}, function(data) {
if(data==1){
email.addClass("error");
emailInfo.text("Adress exists");
emailInfo.addClass("error");
dataExist=1;
}else{
email.removeClass("error");
emailInfo.text("Valid adress");
emailInfo.removeClass("error");
dataExist=0;
}
$('#some_input').val(dataExist);
validateUserName();
});
}
function validateUserName() {
var input = $('#some_input').val();
if (input) {
alert("This username is already taken");// whatever
} else {
// whatever
}
};
You are comparing the username with the email address. Is this how your DB works?
$sql = "SELECT * FROM users WHERE username='".$email."'";
I bet you have a field in your database for the email itself, otherwise i suggest you do this. The query should look like this:
$sql = "SELECT * FROM users WHERE email = '".$email."'";
Without the single quotes for the column.
I hope this isn't a duplicate; the other similar questions I read didn't help me solve my problem.
I'm receiving a blank response (i.e. data = "") from a jQuery Ajax call to my PHP script, used to validate a user's submitted CAPTCHA value. I'm using Cryptographp for my CAPTCHA, and it works as expected, so I'm thinking it's most likely an error either in my Ajax call or the PHP script.
Firebug showing correct POST values ('code' is the submitted CAPTCHA value to test):
code a
email a#a.com
emailtext a
firstname a
lastname a
phone
Ajax function called onsubmit to determine whether or not to submit the form:
function validateCaptcha()
{
// Assume an invalid CAPTCHA
var valid = false;
// The form containing the CAPTCHA value
var data_string = $('form#emailform').serialize();
// Make the Ajax call
$.ajax({
url: "captcha.php",
data: data_string,
type: "POST",
async: false,
success: function (data) {
if (data == "true")
{
valid = true;
}
alert ("data: " + data);
}
});
return valid;
}
captcha.php
<?
$cryptinstall="crypt/cryptographp.fct.php";
include $cryptinstall;
// Begin the session
session_start();
//Check if CAPTCHA values match
if(chk_crypt($_POST["code"]))
return true;
else
return false;
?>
My expectation is that the above snippet should return a response of simply "true" or "false," but perhaps this is not the case.
Any help pointing out my error would be greatly appreciated!
You need to use "echo" instead of "return" and write is as a string. return is for returning results of functions.
<?
$cryptinstall="crypt/cryptographp.fct.php";
include $cryptinstall;
// Begin the session
session_start();
//Check if CAPTCHA values match
if(chk_crypt($_POST["code"]))
echo "true";
else
echo "false;
?>
From your captcha.php you are not echoing/printing anything so it's returning nothing. Just replace your return true; and return false; with echo.
Browser can only receive something when you'll print something from the script.
if(chk_crypt($_POST["code"])) echo true; // 1
else echo false;// 0
or
if(chk_crypt($_POST["code"])) echo 'true'; // true
else echo 'false';// false
A new problem emerged from this thread: jquery form validator never makes ajax call, in that the data returned from the ajax request is accurate, but it always fails on a comparison. This is the code that makes the ajax request:
var pass_form = $('#pass_form');
pass_form.submit( valid_pass_sett );
function valid_pass_sett() {
//remove old errors - snipped
pass_old = $('input[name=pass_old]').val();
pass_new = $('input[name=pass_new]').val();
pass_confirm_new = $('input[name=pass_confirm_new]').val();
if (pass_old === "") {
//display error on form - snipped
return false;
} else if (pass_new === "") {
//display error on form - snipped
return false;
} else if (pass_new != pass_confirm_new) {
//display error on form - snipped
return false;
} else if (pass_new.length < 8) {
//display error on form - snipped
return false;
} else {
$.post("http://www.example.com/ajax/validate.php",{ // async validation
type: 'valid_old_change_pass',
pass_old: pass_old,
pass_new: pass_new
}, valid_pass_combo_callback);
alert('after the ajax call...');
}
return false; // cancel form submission
}
this is the code that the request is submitted to:
$username = $_SESSION['username'];
$pass_old = $_POST['pass_old'];
$pass_new = $_POST['pass_new'];
if (empty($pass_old) || empty($pass_new)) {
echo "invalid";
} else if (!User::valid_user_pass($username, $pass_old)) {
echo "invalid_old";
} else if (!Sanitize::is_legal_password($pass_new)) {
echo "invalid_new";
} else {
echo "valid";
}
and this is the callback function that processes it; the callback function is the one where the comparison always fails.
function valid_pass_combo_callback( data ) {
//breakpoint is set here
if (data == 'valid') {
//only if the form is valid!
pass_form[0].unbind('submit').submit();
}
else if (data == "invalid_old") {
//display error on form - snipped
}
else if (data == "invalid_new") {
//display error on form - snipped
}
else {
//it always jumps to here..., even though data *is* the correct value
}
}
I debugged this code, and validate.php is returning "invalid_old" which is correct (based on the test data I'm entering). So, data is storing "invalid_old" according to Firebug; however, the code always jumps down to the last else statement. Why is the comparison always failing?
Try placing an alert(data.toString()); above your checks temporarily to see what it returns. If it's not the string itself, then it's not returning the data you're expecting.
As stated in the comment, adding JQuery's trim function fixed the problem, as shown:
function valid_pass_combo_callback( data ) {
trimmed_data = $.trim(data);
if (trimmed_data == 'valid') {
//only if the form is valid!
pass_form[0].unbind('submit').submit();
}
else if (trimmed_data == "invalid_old") {
//display error on form - snipped
}
else if (trimmed_data == "invalid_new") {
//display error on form - snipped
}
else {
//it always jumps to here..., even though data *is* the correct value
}
}
I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.