Heres the issue. I have an an ajax function that is just checking if an email that a user inputs is already used.
The php script that it uses either sends back "true" or "false" strings depending on the result. When i get the response text back, or the "data" variable in the below function, and see if its == to "true" it never passes and always evaluates to false.
This is odd, because when I have printed out the data variable on
screen it shows as "true" when it should, but its just not being shown
as equal to "true" in the if statement. No idea what is happening
here.
AJAX FUNCTION:
function check_email() {
var email = document.sign_up_form.email_first.value;
document.getElementById("email1").innerHTML = ' <img src="loading.gif" width="15">';
$.ajax({
type: "GET",
url: "java_check_email.php",
data: "email="+email,
success: function(data){
if(data == "true"){
document.getElementById("email1").innerHTML = ' <img src="check.png" width="15">';
document.getElementById("email4").innerHTML = '';
}
else {
document.getElementById("email1").innerHTML = ' <img src="xmark.png" width="15">';
document.getElementById("email4").innerHTML = 'Email is already in use<br>';
}
}
});
}
UPDATE:
PHP script looks like this
<?php
include('functions.php');
$email = $_GET['email'];
$query_check = "removed for obvious reasons...";
$result_check = mysql_query($query_check);
if(mysql_num_rows($result_check) == 0){
echo 'true';
}
else{
echo 'false';
}
?>
Also, after calling console.log(data) when the ajax response is received i got a value of "true" in the js console.....
For debugging, try
if (data.replace(/\s+/g, '') == "true") {
...my money is on whitespace outside the <?php ?> tags. Note that if this solves the problem it should not considered the solution - the real solution is to remove the additional whitespace from the PHP script.
The < of the opening <?php tag should be the very first character in the file. For example:
This empty line will be output directly
<?php
^^^^ This whitespace will be output directly
Note also that the closing ?> tag is often unnecessary (as it seems to be in this case) and omitting it completely can help avoid problems like this.
If you want to return a boolean to JS you should simply echo 1 or 0, so you can just do this in the receiving Javascript:
if (data) {
I know this is old but I've had the exact same problem and couldn't fix it. I am realy sure it wasn't a white-space issue but I was able to solve it in a different way.
Maybe it's not the best way (I still want to know why it doesnt work in the usual way), but what I did was echo a 0 (for false) and a 1 (for true)
Then I parsed the data to an Integer, so my code looks like this:
function(data){
var result = parseInt(data);
if (result === 1){
$('#loginresult').html('OK');
} else {
$('#loginresult').html('NOT OK');
}
I hope I can help anyone with this workaround (but a good solution would be better)
Related
I have been using php and ajax to validate if an email inserted in my form exists in my database.
I am using jquery to send the email value to my php file and return a message if the email is found. My code is working fine but I want if an email is found the cursor be on focus on the #usu_email field until the email be changed. After this, it should allow me to continue to next field.
This is the jquery code I am using:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
success: function(data, textStatus) {
if (data !== null) {
$("#eresult").html(data);
$("#usu_email").focus();
}
},
});
};
My problem is that if and email does not exist in my database the cursor keeps doing focus on my #usu_email field and does not allow me to continue to next field.
I will appreciate any help about this problem because I know very little about jquery.
First... Your condition if (data !== null) always will be true since there always will be a data provided... Be it an empty string.
The only case where there will be no data is on Ajax error... And the condition won't even be evaluated because the success callback won't execute.
Next, I assume that your Ajax request is triggered on $("#usu_email") blur... Else, I don't know how you achieve «does not allow me to continue».
Modify it in this way to compare a response:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
datatype: "json",
success: function(data) { // There is only one argument here.
// Display the result message
$("#eresult").html(data.message);
if (data.email_exist == "yes") {
$("#usu_email").focus();
}
if (data.email_exist == "no") {
// Something else to do in this case, like focussing the next field.
}
},
});
};
On the PHP side, you have to provide the json response. It would look like something like this:
<?php
// You have this variable to compare against the database
$email = $_POST[usu_email];
// You say it is working.
// ...
// Then, you certainly have a result... Say it's $found (true/false).
// Build an array of all the response param you want to send as a response.
if($found){
$result[email_exist] = "yes";
$result[message] = "The submitted email already exist.";
}else{
$result[email_exist] = "no";
$result[message] = "A success message about the email here.";
}
// Add this header to the returned document to make it a valid json that doesn't need to be parsed by the client-side.
header("Content-type:application/json");
// Encode the array as a json and print it. That's what is sent in data as an Ajax response.
echo json_encode($result);
?>
Be carefull not to echo anything else. Not even a blank space or a line return.
Depends on what type of data you're expecting (simple text response or JSON), but at first i would start to replace your if(data !== null) with if(typeof data != "undefined" && data !== null && data != "") because the returned response might just be empty and not NULL.
If it doesn't work you should consider adding your php code to the question so we can figure out exactly what it returns when no matching email is found.
I'm trying to make a contact form with PHP and AJAX. The email sends and all but it always says "Failed to send!" even in the console it says "true" which should result in the html "Message Sent!"
So I wrote this in the end of my PHP script:
if (!$mail->send()) {
echo $mail->ErrorInfo;
} else {
echo "true";
}
and that should mean that via AJAX the output data I get should be one of those, correct?
ajax.SetText("Sending...");
$.post("sendmail.php", {
name: userName, email: userEmail, comments: userComments, business: currentBusiness, website: currentWebsite
}, function(data) {
if(data == "true") {
ajax.SetText("Sent!");
console.log(data);
$.get("sent.html", function(sentData){
$("#content").html(sentData);
});
} else {
ajax.SetText("Send mail");
console.log(data);
$.get("unsent.html", function(sentData){
$("#content").html(sentData);
});
}
ajax.isSubmiting = false;
});
This is the jQuery^
So basically if the email is sent I want the return to be "true" so then I could put the appropiate information on the page like "The message was sent!" But in this case, whether it fails to send or succeeds, it never returns true. I have also tried, in the php file, print_r("true") and die("true") but it still doesnt work. Does anyone know why? Any thing would be appreciated, thanks.
Looks like the system is taking "true" to be a keyword. Try putting OK or something. Also check if you aren't outputting an extra line. You can do this by checking with .trim().
if (data.trim() == "true") {
To check such kind of issues, try on the console using encodeURI() function:
console.log(encodeURI(data));
This might give you something similar to:
I created an Enter line on the output. This might not match if you check with:
data == "true"
So you might need to use the trim() function here. Look at the below for more information:
I strongly believe this would be the case. :)
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
All,
I have an AJAX function, that calls a PHP URL through html data type. I cannot use other datatypes for my AJAX requests due to server constraints. I am trying to print a message and also handle scenarios based on the return code. The following code doesn't seem to work. Can you advise?
Here's a simple AJAX call:
$.ajax({
type: "POST",
url: "validateUser.php",
dataType: html,
success: function(msg, errorCode){
if(errorCode == 10)
{
callAFunction();
}
else if(errorCode == 20)
{
callSomething();
}
else
{
doSomethingElse();
}
}
});
PHP CODE:
---------
<?php
function validateUser()
{
$username = 'xyz';
if (!empty($username) && strlen($username)>5)
{
echo 'User Validated';
return 10;
}
else if (empty($username))
{
echo 'Improper Username';
return 20;
}
else if (strlen($username)<5)
{
echo 'Username length should be atleast 5 characters';
return 30;
}
exit;
}
?>
Thanks
Your PHP is a just a function. It is not being called.
Also, you are not sending any data to your PHP file.
what you can do is print them in div something like this.
<div class="errorcode">30</div><div class="errormessage">Username length should be atleast 5 characters</div>
and then in your success function in ajax you can use jquery to parse the response text and use selectors like $(".errorcode").html() and $(".errormessage").html() and get the response. this makes things easy
also looks like you are not posting anything
Remove exit; at the end of validateUser(). It causes the execution of the entire script to stop immediately.
Since this is the last line of validateUser(), there is no need to add return.
Documentation: exit, return
My Ajax application was working fine, until I implemented an if statement in the PHP script... then like a contagious disease it seems that if I do anything to the data in PHP it returns nothing back to the Javascript layer.
All I can do is echo the data back...
For instance the query string I'm sending to the PHP reads...
index.back3.php?form=login&json={"email":"mo#maurice-campobasso.com","password":"asdasdfas"}
and I know its getting there because in the simplest debugging PHP file (index.back3.php) that I created all I have is a simple echo statement... and it never fails to send back the data to the Javascript file.
when index.back3.php reads
<?php echo $_GET[json]; ?>
the alert that I have triggering off in the javascript reliably spits out the json string.
also when it reads
<?php echo $_GET[form]; ?>
when I get any more complicated than that nothing comes back to the javascript. Even a simple concatenation...
<?php echo ($_GET[form] . $_GET[json]); ?>
...returns nothing!
A simple if...else statement also returns nothing.
<?php
if(!isset($_GET[form]) {
echo "no!";
} else {
echo "yes!";
}
?>
And this important operation also...
<?php
$array = json_decode($GET[json], true);
var_dump($array);
?>
returns nothing.
OK... so just to make sure everything is above board here is my Ajax output function in the Javascript layer.
function responseAjax() {
if (myRequest.readyState == 4) {
if(myRequest.status == 200) {
var foo = myRequest.responseText;
alert(foo);
} else {
alert("An error has occured: " + myRequest.statusText);
}
}
}
Can someone please explain what's going on? I'm truly stumped.
if(!isset($_GET[form]) {
echo "no!";
} else {
echo "yes!";
}
?>
you are missing a closing parenthesis in the if statement. And as said a few times before, put quotes around your array keys.
While in development, you should also maybe turn on error_reporting to E_ALL. it helps find out what a small error might be.
$_GET['form'] is the right way.
and using form as variable name is not at all good.
use anyother variable and pass $_GET['formname'].
Try to access the php page directly through url and pass the parameters , check first the php
return error or its working propelry.
You can use PHP , jquery and ajax in simple ways.
try to find .post or .get methods in jquery
http://api.jquery.com/jQuery.post/
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
I managed to sort it out, it had to do with a line of code which I omitted from this post, because I thought it was reduntant. The full version of the function went like this.
function responseAjax() {
if (myRequest.readyState == 4) {
if(myRequest.status == 200) {
var foo = myRequest.responseText;
var cookieData = eval("(" + foo + ")"); //this was the problem!!
alert(foo);
document.cookie = 'email =' + cookieData.email + '; path=/';
document.cookie = 'firstname =' + cookieData.FirstName + '; path=/';
} else {
alert("An error has occured: " + myRequest.statusText);
}
}
}
It was the 'var cookieData' line... though I'm not sure why.