I have a very limited jQuery experience and I was wondering if you can help me with a function that has to check, with an AJAX request, if an email address exists or not.
Until now I have this piece of code for email checking:
$('input#email').bind('blur', function () {
$.ajax({
url: 'ajax/email.php',
type: 'GET',
data: 'email=' + $('input#email').val(),
cache: false,
success: function (html) {
if (html == 1) alert('Email exists!');
}
});
});
How can I make a function out of this and use it like this:
if (!email_exists($('input#email').val())) {
$('#error_email').text('Email exists').show();
return false;
}
My PHP code looks like this:
$email = ($_GET['email']) ? $_GET['email'] : $_POST['email'];
$query = "SELECT `id` FROM `users` \n"."WHERE `users`.`email` = '".mysql_real_escape_string($email)."'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo '1';
} else {
echo '0';
}
Thank you.
If you really must have an answer returned from the function synchronously, you can use a synchronous XMLHttpRequest instead of the normal asynchronous one (the ‘A’ in AJAX):
function email_exists(email) {
var result= null;
$.ajax({
url: 'ajax/email.php',
data: {email: email},
cache: false,
async: false, // boo!
success: function(data) {
result= data;
}
});
return result=='1';
}
However this is strongly discouraged as it will make the browser hang up whilst it is waiting for the answer, which is quite user-unfriendly.
(nb: also, pass an object to data to let jQuery cope with the formatting for you. Otherwise, you would need to do 'email='+encodeURIComponent(email) explicitly.)
You can't have a function that synchronously returns a value from an asynchronous action, or vice versa (you would need threads or co-routines to do that, and JavaScript has neither). Instead, embrace asynchronous programming and have the result returned to a passed-in callback:
$('#email').bind('change', function() {
check_email($('#email').val(), function(exists) {
if (exists)
$('#error_email').text('Email exists').show();
});
});
function check_email(email, callback) {
$.ajax({
url: 'ajax/email.php',
data: {email: email},
cache: false,
success: function(data) {
callback(data=='1');
}
});
}
You've already made it a "function" by attaching it to the blur event of your input. I would just
success: function(html) {
if (html == 1)
$('#error_email').text('Email exists').show();
else
$('#error_email').hide();
}
Related
I have a code that checks if the username is available if you want to change. But now I saw that if you update something else such as your password, you can assume to save as the user name already exists.
Listed below are the code I use, as you see, I have tried to think of something but did not go well at all.
PHP
$sql = "Select * FROM table WHERE Slug = '$slug' AND ID ='$id' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0){
echo 'true';
}else{
$e_sql = "Select * FROM table WHERE Slug = '$slug'";
$e_query = mysql_query($e_sql);
if(mysql_num_rows($e_query)>0){
echo 'false';
}else{
echo 'false';
}
}
Jquery/Javascript
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "User.php",
data: {
'slug': value,
'id': <?php echo $id; ?>
},
dataType:"html",
success: function(msg)
{ console.log(msg);
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"This Name is already used!"
);
$("#addSurvey").validate({
rules: {
name: {
required: true,
uniqueUserName: true
},
}
});
Basically problem is in your $.ajax request.
As you know $.ajax by default perform an asynchronous HTTP (Ajax) request.
Easiest solution for you is to make request synchronous.
To make request synchronous you should set option async: false - in this case code will be executed linearly and you will get return response; only when ajax request is completed.
So basically change part of ajax call to:
$.ajax({
type: "POST",
url: "User.php",
async: false,
data: {
'slug': value,
'id': <?php echo $id; ?>
},
dataType:"html",
success: function(msg){
response = msg === 'true';
}
});
May be useful:
jQuery.ajax() Documentation
set
response = (( msg == 'true' ) ? true : false);
updated my question below
I made a script where a user can import large amounts of data. After the form is submitted and the data validated I add 2 background tasks: 1 is a script that imports all the data. This script also lets the databases know how many in total and how many he has done. The second is a script that reads how much is done from the database and displays it in a nice progress bar.
Code:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {}
});
var process = 0;
var checkPercentage = function() {
$.ajax({
type: "GET",
url: "get-process-status.php",
data: "importcode=123456",
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
}
}
});
if (process != 100) {
setTimeout(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
checkPercentage();
Both scripts, work fine. Except that the second script (getting the status of the process) isn't started after the first (importing the data) is finished. Which makes the complete thing kinda useless.
Any ideas how to solve this?
update:
I found out that the background process gets called only once. That's the problem. I'm just not sure how to fix it..
var checkPercentage = function() {
alert("Is this function getting called every second?");
$.ajax({
type: "GET",
async: true,
url: "required/get-process-status.php",
data: "importcode=123456",
success: function(data) {
alert(data);
}
});
setTimeout(checkPercentage, 1000);
}
The code above alerts "Is this function getting called every second?" every second. Like it should. However, the value 'data' is called only once. That's not what I expected.. Any ideas?
You mean like this?:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {
checkPercentage();
}
});
var process = 0;
var checkPercentage = function() {
$.ajax({
type: "GET",
url: "get-process-status.php",
data: "importcode=123456",
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
}
}
});
if (process != 100) {
setTimeout(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
I just moved checkPercantage function call from end of script to success function of first ajax. You can also move it to complete function if you wish to run it despite of errors.
Set your callback function to be:
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
if (process != 100) {
setInterval(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
}
Firstly, the if statement has to be in a callback function to work the way you want it. Secondly, you should use setInterval() instead of setTimeout() because it will recheck it every interval time.
Also, yabol is right saying that the top of your code should look like this:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {
checkPercentage();
}
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 years ago.
Trying to run a script, (test.al();) and inside test.al, its called getcrypt.php();, the php script is on a webserver, and it is working. Currently, these are my scripts
JS
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
return v;
}
});
}
}
var test = {
al: function () {
a = getcrypt.php();
alert(a);
}
}
PHP
<?php
$id = $_POST['id'];
if ('getit' == $id){
$value = 'VALUE';
echo $value;
}else{
echo 0;
}
?>
In this way, it will show an alert with 'unidefined', and if i add a alert(v); right before return v, it will show me 'VALUE', but not able to use it outside the variable...
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
return v;
}
});
}
}
This will give me an alert with the correct value (AFTER THE 'undefined')
This is because of the asynchronous call you're making. The return is only for the success function and not for the php function.
To get the value out you would need to write:
var value;
var getcrypt = {
php: function (callback) {
$.ajax({
url: "",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
callback(v);
}
});
}
}
getcrypt.php(function(v) {
alert(v);
// This happens later than the below
value = v;
});
// The below will still not work since execution has already passed this place
// alert will still return undefined
alert(value);
The problem is jQuery ajax works with callbacks and does not work with return value's so you need to add an callback to your getcrypt function so say
var getcrypt = {
php: function (callback) {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
callback(v);
}
});
}
}
so now if you call
getcrypt.php(function(returnVar){
alert(returnVar)
});
you will get an alert with VALUE
$.ajax returns immidiately (well, almost :)) upon calling, before the response is received. You should rewrite your code to accomodate to this fact, something like this;
var getcrypt = {
php: function(){
$.ajax({
//..other params ..//
success: function(msg){
var v = msg.match(/^.*$/m)[0];
alertResponse(v);
}
});
},
alertResponse: function(processedResponse) {
alert(v);
}
}
var test = {
al: function(){
getcrypt.php();
}
}
If you need your response in test object, you move alertResponse to that object and call it from success method. I think this tutorial might be useful for you to learn javascript event-driven programming model.
$.ajax calls are async. So what you get is the return value of $.ajax (when the request is sent, before a response is received). It is only when the browser receives a response to the ajax call that the success callback is run, as a seerate process from the $.ajax call. In other words the return value of $.ajax will always be null. I'm not sure it's possible to do anythging with the return value of the success callback, you need to put your logic (or a call to another function with the logic) in the success callback itself, in the same way you did with the alert in your final example
The code I want to work:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
dataType: "json",
processData: false,
success: function(html) {
$("#srchFrm").append(html);}
});
The code that works:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
success: function(html) {
$("#srchFrm").append(html);}
});
Unfortunately when I send the first one my post data looks like this "Array ()" and when I use the later I get this "Array ( [sndJson] => [\"8\",\"3\",\"6\",\"7\"] )".
I know that there has to be a simple explanation but I haven't been able to figure it out.
Help please!
Try sending your data in a query string...
$.ajax({
type:"POST",
url:"_Source/ajap/ajap.nlSrch.php?json="+jsonData,
dataType:"json",
success: function(data) {
$("#srchFrm").append(data);}
error: function(xhr, ajaxOptions, thrownError)
{alert("Error!");}
});
You can use shorthand $.post instead of using low level ajax class --- because you don't need to advanced handling. So, this one will be great enough.
$(document.ready(function(){
$("#submit_button").click(function(){
$.post('php_script.php', {
// here's what you want to send
// important -- double quotes, 'cause It's evals as valid JSON
"var1" : "val1"
"var2" : "val2"
}, function (respond){
try {
var respond = JSON.parse(respond);
} catch(e){
//error - respond wasn't JSON
}
});
});
});
PHP code:
<?php
/**
* Here you can handle variable or array you got from JavaScript
* and send back if need.
*/
print_r($_POST); // var1 = val1, var2 = val2
?>
Back to your question,
Why my .ajax request doesn't work?
This is because JavaScript throws fatal error and stops further code execution.
You can catch and determine the error occasion, simply by adding
try {} catch(){} block to the statement you think may occur any error
When you specify dataType: json, jQuery will automatically evaluate the response and return a Javascript object, in this case an array. You're taking the result and adding it as html to #srchForm, so it does not make sense to convert it to a javascript object. Use dataType: html, or none at all.
http://api.jquery.com/jQuery.ajax/
The following examples above are not reusable. I am a huge fan of reuseable code. here is my solution.
Software design 101:
DRY Don't repeat your self. You should wrap your code into an object. This way you can call it from anywhere.
var Request = {
version: 1.0, //not needed but i like versioning things
xproxy: function(type, url, data, callback, timeout, headers, contentType)
{
if (!timeout || timeout <= 0) { timeout = 15000; }
$.ajax(
{
url: url,
type: type,
data: data,
timeout: timeout,
contentType: contentType,
success:function(data)
{
if (callback != undefined) { callback(data); }
},
error:function(data)
{
if (callback != undefined) { callback(data); }
},
beforeSend: function(xhr)
{
//headers is a list with two items
if(headers)
{
xhr.setRequestHeader('secret-key', headers[0]);
xhr.setRequestHeader('api-key', headers[1]);
}
}
});
}
};
Usage:
<script type="text/javascript">
var contentType = "applicaiton/json";
var url = "http://api.lastfm.com/get/data/";
var timeout = 1000*5; //five seconds
var requestType = "POST"; //GET, POST, DELETE, PUT
var header = [];
header.push("unique-guid");
header.push("23903820983");
var data = "{\"username\":\"james\"}"; //you should really deserialize this w/ a function
function callback(data)
{
//do logic here
}
Request.xproxy(requestType, url, data, callback, timeout, header, contentType);
</script>
I want to have a javascript function such as this:
function isUsernameAvailable(username)
{
//Code to do an AJAX request and return true/false if
// the username given is available or not
}
How can this be accomplished using Jquery or Xajax?
The big win when using AJAX is that it is asynchronous. You're asking for a synchronous function call. This can be done, but it might lock up the browser while it is waiting for the server.
Using jquery:
function isUsernameAvailable(username) {
var available;
$.ajax({
url: "checkusername.php",
data: {name: username},
async: false, // this makes the ajax-call blocking
dataType: 'json',
success: function (response) {
available = response.available;
}
});
return available;
}
Your php-code should then check the database, and return
{available: true}
if the name is ok.
That said, you should probably do this asynchronously. Like so:
function checkUsernameAvailability(username) {
$.getJSON("checkusername.php", {name: username}, function (response) {
if (!response.available) {
alert("Sorry, but that username isn't available.");
}
});
}