when to use callbacks in ajax calls - javascript

why use the first method and the call to it. (call back functions). and why not use the last one? http://pastebin.ca/2683261
one method is using success: success line 8 . and the caller of that method actually puts up the method on success (line 16)
someone told me that the last method wont do anything since the reply from server (success/failure) would come later. and I need to use the callbacks like the first method
*I did remember that I got an issue with traditional one. I just cant remember what it was. I think some thing that I didnt got the response when it was intended to. Some one told me that you wont get the response right away as its async. you need call backs. he was correct. But I dont remember the use case
*
with success:success (callback at method call)
function ajaxEditBox(box, boxType, boxTitle, boxDescription, success, error){
var boxId = box.attr('id').split("-")[1];
alert("box id to be sent to edit by ajax call: "+boxId +" type:"+boxType+" title:"+boxTitle+" desc"+boxDescription);
$.ajax({
url: "${pageContext.request.contextPath}/box/edit/"+boxId+"/"+boxType+"/"+boxTitle+"/"+boxDescription,
cache: false,
success: success,
error: error
});
}
callback at method call
ajaxEditBox(window.box, boxType, boxTitle, boxDescription, function(){
alert("boo");
$(window.box).removeClass("box-vertical");
$(window.box).removeClass("box-horizontal");
$(window.box).addClass("box-"+boxType);
$(window.box).find(".box-title-text").first().html(boxTitle);
//description change/edit is pending.
},
function(){
alert("ooh");
});
traditional ajax
function ajaxCreateBox(parent){
$.ajax({
url: "${pageContext.request.contextPath}/box/create/"+parentType+"/"+parentId+"/"+boxType+"/"+boxTitle+"/"+boxDescription,
cache: false,
//data:'firstName=' + $("#firstName").val() + "&lastName=" + $("#lastName").val() + "&email=" + $("#email").val(),
success: function(response){
$('#result').html(fetchedBoxId+" "+fetchedBoxType+" "+fetchedBoxTitle+" "+fetchedBoxDescription);
// createBoxInDom();
$("#"+parentElementId+" > ."+parentType+"-body").append(
'<div id="boxid-'+fetchedBoxId+'" class="box box-'+fetchedBoxType+'" >'+
' <div class="box-title" title="'+fetchedBoxDescription+'">'+
...
..
..
..
some logic
...
..
' <div class="box-body">'+
' </div> '+
'</div>');
},
error: function(){
alert('Error while request..');
}

Related

Why am I getting a '$' is not defined when running an AJAX query?

Possibly a dumb question, but I have a page where I'm trying to load list data into a customer table to display as a front-end. I'm retrieving this list from a SharePoint list using an AJAX call in a Javascript function, however when I'm using this function my console returns a SCRIPT5009: '$' is not defined error. Previously, I've used an AJAX call successfully using very similar code, but to return a single item from the list using the list ID to search for a specific item, and I've run the query successfully directly from the URL that returns the data I'm after - I'm just not sure what's happening with this one.
function getIncidents(){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$select=Title,Id,Priority,IncidentStart,IncidentStatus,IncidentTitle,UpdateResolution",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
var dResponse = data.d.results;
var results = document.getElementById('Results');
results.innerHTML += "<tr><td>Incident<br>Reference</td><td style='width:20px'></td><td>Priority</td><td style='width:20px;'></td><td>Start Time</td><td style='width:20px'></td><td style='width:170px'>Issue</td><td style='width:20px'></td><td style='width:170px'>Latest Update</td><td style='width:20px'></td></tr>";
for(var obj in dResponse){
results.innerHTML += "<tr style='font-size:10pt'><td>"+dResponse[obj].Title + "</td><td></td><td>" + dResponse[obj].Priority + "</td><td></td><td>" + dResponse[obj].IncidentStart + "</td><td></td><td>" + dResponse[obj].IncidentTitle + "</td><td></td><td>" + dResponse[obj].UpdateResolution + "</td></tr>";
}
}
});
}
Previous example where I have this call working:
function getIncident() {
var listName="Incident List";
var incidentID = $("#incidentReference").val();
if(incidentID!=""){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$filter=Title eq '" + incidentID + "'&$select=Title,Id,SystemOrService,Priority,IncidentStatus,IncidentTitle,UpdateResolution,IncidentStart,ImpactedArea,IncidentEnd",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
if(data.d.results.length>0){
var item=data.d.results[0];
$("#systemImpacted").val(item.SystemOrService);
$("#incidentPriority").val(item.Priority);
$("#incidentState").val(item.IncidentStatus);
$("#incidentTitle").val(item.IncidentTitle);
$("#incidentUpdate").val(item.UpdateResolution);
$("#startTime").val(item.IncidentStart);
$("#impactedAreas").val(item.ImpactedArea.results);
$("#endTime").val(item.IncidentEnd);
updateImpact();
getStartTime();
getEndTime();
actionsFormat();
}
},
error: function (data) {
alert("Incident Reference incorrect or not found");
}
});
}
}
The issue is that jQuery ($) is not yet loaded to the page. If you used it before, this means that loading is already setup, so you don't need to add more references to the jQuery.
In most of the cases, when you working with jQuery, you will subscribe on DOM event ready event and do your code there.
So, all you need is to find the
$(document).ready( ...
statement and insert your code there.
If you want to separate your code from already existed, you may write your own $(document).ready subscription.
If you will not find this $(document).ready function, you can search in html for the reference to the jQuery, and insert your script after it. But, than you need to be sure, that reference doesn't include async or defer attribute.
As mentioned in comments, if you decide to add your own subscription, you also need to place it after jQuery reference, because it will not work, if $ isn't available.

Google Recaptcha Ajax response strange checking order

I am making my registration page for my service. I need to check either Google's Recaptcha successfully verified or not. I decided to use an jquery.ajax.
I have created a function "checkCaptcha()" which sets isCAPT (if captcha valid or not) either true (FLD_VALID) or not (FLD_EMPTY):
function checkCaptcha() {
alert("1");
var captcha_response_text = grecaptcha.getResponse();
var request = $.ajax({
url: "ajax/registrationA.php",
type: "post",
data: { captcha: true, captcha_response: captcha_response_text }
});
request.done(function (response, textStatus, jqXHR) {
alert("2");
if(response) {
isCAPT = FLD_VALID;
}
else {
isCAPT = FLD_EMPTY;
}
});
}
I have to say that "registrationA.php" works fine. No problems there.
After this function, I am checking my submit button handling "onclick" event:
apply_button.onclick = function () {
checkCaptcha();
alert("3");
//alert("Капча " + isCAPT + " Логин " + isLOGIN + " Почта " + isMAIL + " Пароль " + isPASS + " Соответствие " + isPAS2);
return false;
};
You can see three "alert(...)" operators. The problem is that when I press submit button (apply_button) I get three alerts: 1, 3, 2. How can I fix this problem. I need to wait until "requiest.done" executes and only than go to "alert("3")". It is essential because now this function checks fields before checking captcha state which leads to an error because in this case isCAPT equals false.
Please help me with this problem. Maybe there is a better way to check if captcha verified or not (maybe there is a function like "grecaptcha.isVerified").
You need to check deferred.promise() method to work with asynchronous data. Check JQ documentation for that. In a few words it does exactly what you need. It allows to wait until the 2nd asynchronous request is finished and starts the 3d function.

Button Doesn't Work After Second Click

I have a button that calls a function in javascript. The javascript in turn runs two consecutive ajax calls. After the first one finishes, it does some extra work, then runs the second ajax call.
The button works upon first clicking it. However, when I want to click it again the following error pops up...
Uncaught TypeError: object is not a function
It is in reference to my function that is being called 'onclick' from the button.
I am pretty new to ajax but I'm sure that this shouldn't be happening. Other buttons are working just fine, and they all call functions from the same script. It just seems to be this one function. I would have expected there to be a semicolon missing or something, but then the first time wouldn't have worked... Also, I do know that the function finished executing, since I debugged the function and it reaches the bottom...
Here are my ajax calls in case you're interested...
var $response = $.ajax({
url: $abs_filename,
type: 'HEAD',
async: false,
success: function () {
console.log('done');
}
}).status;
($response != "200") ? $exist = false : $exist = true;
....lots of extra code here
....
var response = $.ajax({
type: 'POST',
url: '/SERT/includes/file_operations.php',//url of receiver file on server
data: {saves: $save_data}, //your data
dataType: 'text', //text...
success: function(res) {
alert(res);
},
async: false
}).status;
EDIT:
My function is called by
<input type="button" .... onclick="save_session()">
You've not actually shown the code that is causing the error.
However...
Don't do this; it doesn't do what you think it does.
($response != "200") ? $exist = false : $exist = true;
Do this:
$exist = $response == "200";
And just DON'T use synchronous XHR.
I was able to figure it out...
So I had a jQuery append operation going on inside of the save_session() function. This operation was as such...
$bottom_section.append('<input type="hidden" name="save_session" value="' + $total + ' ' + $paragraph + '">');
When I took this out then the whole thing worked as expected. My guess is that by naming the input "save_session" messed with the function definition of save_session() in memory. Now there wasn't a definition conflict, then it was okay.

ajax success callback not working

So I have this JavaScript which works fine up to the $.ajax({. Then it just hangs on the loader and nothing happens.
$(function() {
$('.com_submit').click(function() {
var comment = $("#comment").val();
var user_id = $("#user_id").val();
var perma_id = $("#perma_id").val();
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
if(comment=='') {
alert('Please Give Valid Details');
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
alert('This works');
$("ol#update").append(html);
$("ol#update li:first").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
Try replacing:
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
with:
var dataString = { comment: comment, user_id: user_id, perma_id: perma_id };
in order to ensure that the parameters that you are sending to the server are properly encoded. Also make sure that the commentajax.php script that you are calling works fine and it doesn't throw some error in which case the success handler won't be executed and the loader indicator won't be hidden. Actually the best way to hide the loading indicator is to use the complete event, not the success. The complete event is triggered even in the case of an exception.
Also use a javascript debugging tool such as FireBug to see what exactly happens under the covers. It will allow you to see the actual AJAX request and what does the the server respond. It will also tell you if you have javascript errors and so on: you know, the kinda useful stuff when you are doing javascript enabled web development.

How to check if javascript function is ready/done (jQuery)

I am working on a learning planner which gets its data (languagekeys, tasks, activities, etc.) from a database. Because I need a JSON string, I encode it with json_encode to work with it in JavaScript.
I have a different function (for keys, tasks, activities, etc.) which gets this data and writes it into an array.
function get_tasks(start_date,end_date){
maxsubtasks=0;
maxtasks=0;
$.getJSON(json_data+"?t_startdate="+start_date+"&t_enddate="+end_date, function(data) {
tasks=new Array();
$.each(data.tasks, function(i,item){
tasks[i]= new Object();
tasks[i]["t_id"]=item.t_id;
tasks[i]["t_title"]=item.t_title;
tasks[i]["t_content"]=item.t_content;
. . .
if ( i > data.tasks.length) return false;
maxtasks = data.tasks.length;
if(item.t_parent > 0){
maxsubtasks++;
}
});
});
return true;
}
Everything is working just fine. I need some help, because I now have to call this function in $(document).ready(). I want to build my learning planner only once the function get_tasks() is complete (the array is filled with data). Otherwise, I will get errors.
How can this be solved?
Here is what I have in $(document).ready():
if(get_tasks(first_day,last_day) && get_tmp_data()){ // If this function is done
// This function should be fired -- just like a callback in jQuery
init_learnplanner();
}
You can add a callback to the function:
function get_tasks(start_date, end_date, callback) {
Then after populating the array in the function, call the callback function:
if (callback) callback();
Now you can use the callback parameter to initialise the learning planner:
get_tasks(first_day, last_day, function() {
init_learnplanner();
});
You should be able to specify a callback in $.getJSON, which gets executed as soon the request is completed.
EDIT:
You're already doing this, but why don't you just call the second code block from the end of the callback funciton in $.getJSON?
Other answers haven't worked for me because I have 5 functions which use my data with $.getJSON, and I need to have collected all information to even start init_learnplanner().
After several hours of searching, I've discovered the jQuery function ajaxComplete, which works like a charm for me. jQuery tracks all ajax calls that have been fired and triggers anything assigned .ajaxComplete() when one is complete.
What I'm doing is usually something like this:
simple, looks like beginner but it works :) :D
<script type="text/javascript">
var isBusy = true;
$(document).ready(function () {
// do your stuff here
isBusy = false;
});
function exampleajax() {
if(isBusy) return false;
isBusy=true;
$.ajax({
async: true,
type: 'POST',
url: "???.asp",
dataType: "jsonp",
data: qs,
error: function(xhr, ajaxOptions, thrownError){
//console.log(xhr.responseText + " AJAX - error() " + xhr.statusText + " - " + thrownError);
},
beforeSend: function(){
//console.log( "AJAX - beforeSend()" );
},
complete: function(){
//console.log( "AJAX - complete()" );
isBusy = false;
},
success: function(json){
//console.log("json");
}
});
}
</script>
hope this help you

Categories