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.
Related
The return data for this one as I investigated is "authenticated" which means the if statement should take effect. However, to reasons I know not it goes directly to the else part of the statement making the data false even if it's true. Like "authenticated"=="authenticated". It ignores the if part and I don't know why.
function login_admin_user() {
username = $("#ad-username").val();
password = $("#ad-password").val();
$("#button-login").val("Logging in...");
$.post("ajax-login.php", {
username: username,
password: password
}, function (data) {
if (data == "authenticated") {
/* Execute if authenticated */
$("#box-login-confirmed").fadeIn("slow", function () {
$("#button-login").val("Login");
})
.delay(1000)
.fadeOut(400, function () {
window.location = "home.php";
});
} else {
/* Execute if invalid login */
$("#box-login-error").fadeIn("slow", function () {
$("#button-login").val("Login");
$("#ad-password").val("");
})
.delay(3000)
.fadeOut(400);
}
});
}
"authenciated"!="authenticated". You are missing a 't'. Also probably your response may contain spaces. So check what is coming in the response.And its better to trim your response before doing the checking. You can use jquery trim function to remove spaces.
Try like
if($.trim(data) == "authenticated"){
//Some code
}
else{
//Some code
}
Why the response contain spaces. You can find the answers here
Space Before Ajax Response (jQuery, PHP)
strange thing, ajax response includes whitespace
Trailing spaces in Ajax response
I have encountered that problem as well. Using $.trim() from the response data would help strange whitespaces to be altered.
The default return type of the $.post method is HTML. So, if you set the return type as JSON and in your PHP file you return a JSON ENCODED value as "authenticated" .. that might work
I am able to the js file to fire which does do the first alert but i cannot get the 2nd alert to happen, php file is there and working returning 0 but the alert('finished post'); is not coming up. I think its some syntax I am missing.
$(function () {
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password },
function (result) {
alert('finished post');
//if the result is not 1
if (result == 0) {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
});
});
});
Here is the php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['username'];
$mypassword= $_POST['password'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$sql = $sql->fetch();
$admin = $sql['admin'];
$password_hash = $sql['UserPass'];
$salt = $sql['salt'];
/*** close the database connection ***/
$dbh = null;
if(crypt($mypassword, $salt) == $password_hash){
// Register $myusername, $mypassword and redirect to file
$_SESSION['myusername'] = $myusername;
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 1;
if($admin == 1){
$_SESSION['admin'] = 1;
}
header("location:search.php");
}
else {
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 0;
echo 0;
}
Ok so I'll take a stab at this, see if we can work this out. First, let's clean up your code a little bit - clean code is always easiest to debug:
$(function () {
$("#login_form").on('submit', function(){
console.log('form submitted');
// get the username and password
var login_info = { username: $('#username').val(), password: $('#password').val() }
// use ajax to run the check
$.ajax({
url: '../php/checklogin.php',
type: 'POST',
data: login_info,
success: loginHandler
error: function(xhr, status, err){ console.log(xhr, status, err); }
});
return false;
});
function loginHandler(loggedIn){
if (!loggedIn) {
console.log('login incorrect');
} else {
console.log('logged in');
}
}
});
...ok great, we're looking a little better now. Let's go over the changes made quickly.
First, swapped alerts for console.logs - much less annoying. Open up your console to check this out -- command + optn + J if you're using Chrome.
Second, we compressed the login info a bit - this is just aesthetics and makes our code a little cleaner. Really you should be using variables when they need to be used again, and in this case you only use them once.
Next, we swapped the $.post function for $.ajax. This gives us two things -- one is a little finer control over the request details, and the second is an error callback, which in this case is especially important since you almost certainly are getting a server error which is your original problem. Here are the docs for $.ajax for any further clarification.
We're also pointing the success handler to a function to minimize the nesting here. You can see the function declared down below, and it will receive the data returned by the server.
Finally we're returning false so that the page doesn't refresh.
Now, let's get to the issue. When you use this code, you should see a couple things in your console. The first will probably be a red message with something like 500 internal server error, and the second should be the results of the error callback for the ajax function. You can get even more details on this in Chrome specifically if you click over to the Network Tab and look through the details of the request and response.
I can't fix your PHP because you didn't post it, but I'll assume you'll either follow up with an edit or figure that out yourself. Once you have the server issue ironed out, you should get back a clean console.log with the response you sent back, and you can move ahead.
Alternately, this will work because of the lack of page refresh in which case you can ignore the previous 2 paragraphs and declare victory : )
Hope this helps!
Ah, so damned obvious. You aren't cancelling the default submit action so the form is submitting normally. Add this
$("#login_form").submit(function (e) {
e.preventDefault();
// and so on
See http://api.jquery.com/event.preventDefault/
you need to change 2nd line and add the e.preventDefault to prevent the form from refreshing the whole page.
$("#login_form").submit(function (e) {
e.preventDefault();
Also I would change the AJAX request to use GET and change the code in PHP to read variables from GET so you can easily test the PHP page is working by running it in the browser like this
checklogin.php?username=x&password=y
try this:
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password }, function (result) {
alert('finished post');
//if the result is not 1
if (result == '0') {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
}, 'text');
});
}, 'text');
maybe the server does not give the right data format. for example, if you request for json, and the jQuery cannot convert result sting to json. then the function would not be executed and then you would not able to get 'alert('got 0');' thing.
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;
}
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
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.