I'm trying to make a function that uses jquery's ajaxfunction to get some info from my ajax.php file.
code:
function ajaxIt(dataLine){
$.ajax({
type: "POST",
url: "ajax.php",
data: "ajax=true&"+dataLine,
success: function(msg){
console.log("[AjaxIt]: "+dataLine+" returned "+msg);
return msg;
}
});
}
if(ajaxIt("action=loggedIn")=="1"){
console.log("Logged In");
loggedIn=true;
initiate2();
}
The problem is that I can't get the success function to return all the way to the ajaxIt function. Could anyone shed some light onto how I could do something like that?
Thanks.
You need to invoke a callback function to process data that way:
function ajaxIt(dataLine, cb){
$.ajax({
type: "POST",
url: "ajax.php",
data: "ajax=true&"+dataLine,
success: function(msg){
if($.isFunction(cb))
cb.apply(null, [msg]);
}
});
}
ajaxIt("action=loggedIn", function(data){
if(data === "1"){
console.log("Logged In");
loggedIn=true;
initiate2();
}
});
$.ajax is asynchronous. This means that it will return right away, instead of waiting for the AJAX query to execute and retrieve a result from the server. By the time the message from the server arrives, your ajaxIt function has already finished working.
What you should use here is a continuation-passing style. Provide ajaxIt with a continuation: a function that explains what should be done once ajaxIt has finished working.
function ajaxIt(data, continuation) {
data.ajax = true;
$.post("ajax;php", data, function(msg) {
console.log("[AjaxIt]: returned "+msg);
continuation(msg);
});
}
ajaxIt({action:"logged-in"}, function(result) {
if (result == "1") {
console.log("Logged In");
loggedIn=true;
initiate2();
}
});
Related
I know there are many question like this but i didn't found a proper solution for me.
I am calling API using ajax so my problem is my web page gets unresponsive so some where I have found that this is just because of the improper ajax handling can you please help to know where do I put my ajax.I need ajax to be called on the load of the page.
I have tried calling ajax without any function like..
show('ajax Call start for player');
$('#loading').show();
$.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
// show(playerData);
showPlayers(1);
show('ajax Call complete for player');
flag = 1;
}
});
show('ajax Call start for loadplayeronpitch');
$.ajax({
url: '/home/checkUserTeam',
success: function (data) {
while (true) {
if (flag) {
loadUserTeampitch(data);
break;
}
}
show('ajax Call complete for loadplayeronpitch');
}
});
This is not working which cause the unresponsive page.
then from other questions I have tried calling the ajax in following functions
$(document).load(function(){
});
$(function(){
});
$(document).bind("load", function () {
});
but this all are also not working properly can you help me for this?
Thank you.
The unresponsiveness is caused by your while(true) loop, so never ever do this again :-)
What you want to do is: Run the second ajax call only after the first one finishes. So you should put both ajax calls into separate functions, then call the first function on page load.
In the success part of the first ajax (inside the first function), call the second function. Done.
function firstAjax() {
$.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
//show(playerData);
showPlayers(1);
show('ajax Call complete for player');
secondAjax();
}
});
}
function secondAjax() {
$.ajax({
url: '/home/checkUserTeam',
success: function (data) {
loadUserTeampitch(data);
}
});
}
$(function() {
firstAjax();
});
This should work like you want to, but I can't test it right now.
$('#loading').show();
var deferedA = $.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
// show(playerData);
showPlayers(1);
show('ajax Call complete for player');
}
});
show('ajax Call start for loadplayeronpitch');
var deferedB = $.ajax({
url: '/home/checkUserTeam'
});
//wait until both request are finished
$.when(deferedA, deferedB)
.done( function (dataA, dataB) {
loadUserTeampitch(dataB);
show('ajax Call complete for loadplayeronpitch');
});
EDIT I would suggest to use Promise instead $.when (the Promise like implementation of jQuery is a bit strange), but the problem with Promise is that it is only available with the newer browser, for older one you need a library like bluebird or when
EDIT : If you want to go simple than you can use below approach..
<script type="text/javascript">
$(function() {
var flag = 0;
var data1;
$('#loading').show();
$.ajax({
beforeSend: function() {
show('ajax Call start for player');
},
url: '/home/getPlayers',
success: function(data) {
flag++;
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
showPlayers(1);
show('ajax Call complete for player');
checkFlag();
}
});
$.ajax({
beforeSend: function() {
show('ajax Call start for loadplayeronpitch');
},
url: '/home/checkUserTeam',
success: function(data) {
flag++;
data1 = data;
show('ajax Call complete for loadplayeronpitch');
checkFlag();
}
});
function checkFlag()
{
if (parseInt(flag) == parseInt(2))
{
loadUserTeampitch(data1);
}
}
});
</script>
Hi i currently having a problem with firing .ajaxComplete function, whereby it should be working on a demo site. I'm refer to this function from here http://www.bitrepository.com/a-simple-ajax-username-availability-checker.html
Here are my code :
<SCRIPT type="text/javascript">
<!--
/*
Credits: Bit Repository
Source: http://www.bitrepository.com/web-programming/ajax/username-checker.html
*/
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#userID").change(function() {
var usr = $("#userID").val();
if(usr.length >= 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check.php",
data: "userID="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == "OK")
{
$("#userID").removeClass('object_error'); // if necessary
$("#userID").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
}
});
});
//-->
</SCRIPT>
I had try to alert the msg , the check.php able to return back the msg value, but it stop on the .ajaxComplete() there where it does not trigger the function after the .ajaxComplete(). Please guide me through this. Thanks
From the document
As of jQuery 1.8, the .ajaxComplete() method should only be attached
to document.
So
$(document).ajaxComplete(function(event, request, settings){
});
But in your code, there is no need to use ajaxComplete, the success callback will be called only when the ajax call is finished, so you can just check the value of msg directly in it.
$.ajax({
type: "POST",
url: "check.php",
data: "userID=" + usr,
success: function (msg) {
if (msg == "OK") {
$("#userID").removeClass('object_error'); // if necessary
$("#userID").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
} else {
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
$(this).html(msg);
}
}
});
In my app, a displays available timeslots (for appointment). I want to add a class 'taken' to the slots () which are already taken. For this I wrote the following code.
$("td").each(function(){
var send = $(this).text();
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get',
success: function(result){
console.log(result);
if (result.status === "taken") {
$(this).addClass('taken');
};
}
});
});
It's supposed to perform an ajax call, and if the result for a slot is 'taken', add the class 'taken' to corresponding . It does the ajax call part, but adds the class to all td elements in the table, not just the taken ones.
the check-availability.php, returns 'taken' when called it in browser but nothing happens. Also, when the condition is changed into result.status === "notTaken", all the s are added the class 'taken'
How do I fix this?
$("td").each(function(){
var that = this;
var send = $(this).text();
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get',
success: function(result){
console.log(result);
if (result.status === "taken") {
$(that).addClass('taken');
};
}
});
});
see this for more reference:
$(this) inside of AJAX success not working
Ajax jquery success scope
instead of success, try using .done()
example
`
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get'
}).done(function(result) {
console.log(result);
if (result.status === "taken") {
$(this).addClass('taken');
};
});
`
Hi I'm trying to do something with ajax.
function DoSomething(url){
$.ajax({
type: "GET",
url: url,
success: function(data) {
if(data.SessionExpired === true)
alert('SessionExpired');
else{
//DO Something
}
}
});
DoSomething else;
}
before clicking on alert box 'OK' "DoSomething else" is getting executing.
I want that this will execute only after clicking on alert ok or after "Do Something" block.
Could you please guide me ??
$.ajax calls are async be default, your code 'DoSomething' is executing because the ajax call doesnt hault execution until it returns.
Put your DoSomething() inside the ajax callback
function DoSomething(url){
$.ajax({
type: "GET",
url: url,
success: function(data) {
if(data.SessionExpired === true)
alert('SessionExpired');
DoSomething();
else{
DoAnotherThing();
}
}
});
}
Hello fellow programmers. I am newbie to jquery ajax.
How do i call function checkreturn() from if block or is it possible to access msg outside the success if yes then please let me know how. I need it because only if condition proves true i have to enable the subsequent textbox. Here is my code.Thanks in advance for your time and reply.Rajesh.
<script type="text/javascript" >
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e){
var uname= $("#<%=Username.ClientID%>").val();
var sq=$("#<%=SecQuest.ClientID%>");
var sqtn = $("#<%=SecQuest.ClientID%> option:selected").text();
var sans=$("#txtAns");
var msgbox = $("#Dstatus");
$.ajax({
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
}
else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
});
}
</script>
You have a typo in your checkreturn function. You want to use removeAttribute, instead of removeAtrribute (double t,not double r).
Also, you can use jQuery functions:
function checkreturn(){
$('#txtAns').prop('disabled',false);
}
, instead of native DOM functions (document.getElementById, setAttribute):
not sure what why the normal way is not working but you could try forcing what the browser is supposed to do,
function checkreturn(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Becomes
window.checkreturn = function(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Then try calling via window.checkreturn(); or checkreturn(); you can also so try this the other way arround so you can leave your function and try calling window.checkreturn();
If none of these are working it would say your function is not entering the window(Global) scope for your page use Firebug or Inspector and try to all checkreturn(); see what exception you get back,
if you get a not found your not showing us some thing in your code maybe a closure or some thing
I'll look into it further but try setting async for the ajax call to false:
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e) {
var uname= $("#<%=Username.ClientID%>").val(),
sq=$("#<%=SecQuest.ClientID%>"),
sqtn = $("#<%=SecQuest.ClientID%> option:selected").text(),
sans=$("#txtAns"),
msgbox = $("#Dstatus");
$.ajax( {
async: false,
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
} else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
} );
}
Now, when the ajax call is made, the rest of the script will wait til it completes instead of how everything continues when async is true.