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.");
}
});
}
Related
I've recently used lots of Ajax methods in one of my projects, since in every $.ajax call you have to write many of the same codes, like:
{
type:'POST', // Default value is 'GET'
beforeSend: function(xhr){
// Usually do some Page Loading Animation stuff here
},
error:function(){
// Handling the Exceptions here
}
}
So I've encapsulated the Ajax call into a class, called JAjax, like this :
(function ($) {
// More details, see: http://api.jquery.com/jquery.ajax/
var defaults = {
data: {},
url: '',
type: 'POST',
dataType: 'JSON',
isOverlay: true,
async: true,
cache: true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: true,
overlayTarget: $(document.body),
dealyClean: 500,
f_before: function () {},
f_done: function () { },
f_always: function () { },
f_fail: function (xhr) {
if (xhr.status !== 200) {
// Handling the Exceptions
}
}
};
function JAjax(_options) {
this.options = $.extend({}, defaults, _options);
this.execute();
}
function createOverLayer(options) {
// Create a page loading animation layer
}
JAjax.prototype = {
execute: function () {
var parent = this;
var response = $.ajax({
data: parent.options.data,
url: parent.options.url,
type: parent.options.type,
dataType: parent.options.dataType,
contentType: parent.options.contentType,
async: parent.options.async,
cache: parent.options.cache,
processData: parent.options.processData,
beforeSend: function (xhr) {
parent.options.f_before();
if (parent.options.isOverlay) {
createOverLayer(parent.options);
}
}
});
response.done(parent.options.f_done);
response.always(parent.options.f_always);
response.fail(parent.options.f_fail);
}
};
jQuery.extend({
jajax: function (_options) {
_options = _options || {};
if (typeof _options === 'object') {
return new JAjax(_options);
}
}
});
})(jQuery);
For most Ajax requests (GET, POST), it works fine. But when I use it to upload some files, The file will successfully upload to the server and back to me a filename(string) as an execution result. But somehow, it doesn't trigger the f_done function, below is how I use it to upload the files:
var url = '/ajax_common_file_upload';
var file_data = new FormData();
for (var i = 0; i < _files.length; i++) {
var file = _files[i];
file_data.append('input_files[]', file);
}
$.jajax({
url: url,
data: file_data,
cache: false,
contentType: false,
processData: false,
f_done: function (result) {
// Never to be executed :-(
alert('show me something, please!');
}
});
I spend days to try to figure it out why it doesn't 'SHOW ME SOMETHING' but all failed, will be very appreciated that someone can help me out and explain why the f_done() method cannot be triggered when I use it to upload files.
Update:
I made some screenshots for both JAjax and original $.ajax on Request Headers and merge them together like below:
I used the same parameters to make the request for both JAjax and $.ajax, but I don't know why they have a different Accept value!
ANYONE?
Still can not trigger the f_done() function!!! but since I can do the same thing at f_always(), I'm gonna skip this and moving on. I will keep this post open and always appreciate for any suggestions!
I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3
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>
Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>
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();
}