I know that similar questions have been posted many times, however I've read many of them and can't find an answer to my problem.
I have a function that waits for an ajax request response. Many of you will ask why? Well, I'm using a Wizard Jquery Plugin which executes a function onLeaveAStepFunction when a step is left, then the wizard goes to the selected step if the return value from onLeaveAStepFunction is true; else it remains in the same step.
I'm doing this async: false for waiting and it works, but this is a bad design. Also, I can't use a blockUI plugin.
How can I do this?
Some code:
Initializing the wizard:
$("#wizard").smartWizard({
onLeaveStep : onLeaveStepFunction,
});
Calling the ajax request:
function onLeaveStepCallback(obj, context) {
nextStep = sendForm();
}
The ajax request:
var nextStep = false;
$.ajax({
url : path,
type : "POST",
async : false,
data : $("#" + idForm).serialize(),
success : function(data) {
$("#" + idDiv).html(data);
nextStep = !$("#" + idHiddenErrores).val())
}
});
Omitting the attributes. Please help me.
You could use the jQuery wait method. I took an example from docs page to highlight how you'd do it:
$.when( $.ajax( "/request.php" ) ).done(function( response ) {
// response argument resolved from ajax requests
// process any work after ajax call finishes
}
A link to docs page:
http://api.jquery.com/jquery.when/
I'm doing this async: false for waiting and it works, but this is a bad design also I can't use a blockUI plugin.
Unless your wizard is better designed and supports async callbacks (e.g., promise-returning ones), async:false is your only choice.
Consider switching to a different wizard, and don't forget to file a bug for the plugin that you're currently using.
One hackish work-around is to do it before leaveStep. Perhaps on showStep:
var wizard_next_step;
$("#wizard").smartWizard({
onShowStep : function (obj, context) {
onLeaveStepFunction(obj, context, function(nextStep){
wizard_next_step = nextStep;
});
},
onLeaveStep : function () {
return wizard_next_step;
}
});
You'd also need to modify your onLeaveStepFunction to accept a callback:
function onLeaveStepCallback(obj, context, callback) {
nextStep = sendForm(callback);
}
And your ajax function should then be:
$.ajax({
url : path,
type : "POST",
async : false,
data : $("#" + idForm).serialize(),
success : function(data) {
$("#" + idDiv).html(data);
callback( !$("#" + idHiddenErrores).val()) );
}
});
Now, it looks like you're drawing into the wizard window with this:
$("#" + idDiv).html(data);
I'm entirely sure if this is the case. But if it is then you cannot do this here (obviously because it's onShowStep which would overwrite current content). If this is so you should pass the data in the callback:
success : function(data) {
callback( data , !$("#" + idHiddenErrores).val()) );
}
Write the wizard like this:
var wizard_next_step;
var wizard_data;
$("#wizard").smartWizard({
onShowStep : function (obj, context) {
onLeaveStepFunction(obj, context, function(data, nextStep){
wizard_data = data;
wizard_next_step = nextStep;
});
},
onLeaveStep : function (obj, context) {
$("#" + idDiv).html(wizard_data);
return wizard_next_step;
}
});
The key is to call all the asynchronous functions and get the data long before you call all your synchronous functions.
Note: I don't know smart-wizard at all and not a serious jQuery user. The answer above is based on my 2 minutes reading smart-wizard documentation on github and my understanding of javascript. You will definitely need to modify my examples to make it work.
Related
I am trying to accomplish the following:
1) Get data some source and "do something with it".
2) Get data some other source and "do something with it".
3) The datafetching should preferrably run asynchronous (at the same time ie. the second one should not wait for the first one to complete).
4) When both are completed, some business logic runs - but ONLY when they are completed.
I have created a small JSFiddle to show how I thought this could work - but unfortunately it does not:
a) The datafetching calls are executed sequentially.
b) The business logic from step 4 above executes before the datafetching has even begun...
Fiddle here: https://jsfiddle.net/LeifFrederiksen/emttmhm7/
$.when(
getOneThing(),
getAnotherThing()
).done(
function() {
console.log("Got it all");
$("#Output").append("<BR>Got it all");
}
);
function getOneThing() {
commonFunctionToGetStuff("oneKindOfThings",renderOneKindOfThings);
}
function getAnotherThing() {
commonFunctionToGetStuff("anotherKindOfThings",renderAnotherKindOfThings);
}
function commonFunctionToGetStuff (listTitle,successFunction) {
var url = "https://httpbin.org/get";
$.ajax({
url: url,
type: "GET",
headers: { "accept": "application/json;odata=verbose" }
}).success(function (data) {
console.log("Calling renderfunction for " + listTitle);
$("#Output").append("<BR>Calling renderfunction for " + listTitle);
successFunction(data);
console.log("Back from renderfunction for " + listTitle);
$("#Output").append("<BR>Back from renderfunction for " + listTitle);
});
}
function renderOneKindOfThings(data) {
// Do something with the data...
console.log("Doing oneKindOfThings.");
$("#Output").append("<BR>Doing oneKindOfThings.");
}
function renderAnotherKindOfThings(data) {
// Do something with the data...
console.log("Doing anotherKindOfThings.");
$("#Output").append("<BR>Doing anotherKindOfThings.");
}
Any help clearing up how the structure should be is highly appreciated.
I need to maintain the structure where the function that performs the actual Ajax call is kind of generic, and can be called by simple wrapper functions with parameters controlling what datasource to use - like it is in the example :-)
Regards
Leif
You need to return the promise from your commonFunctionToGetStuff-method and the methods that call it. Otherwise, you're passing in undefined into your when-function which will immediately execute the done-callback. Also you have a few erroneous callback names (it's done or then, not success).
function getOneThing() {
return commonFunctionToGetStuff("oneKindOfThings",renderOneKindOfThings);
}
function getAnotherThing() {
return commonFunctionToGetStuff("anotherKindOfThings",renderAnotherKindOfThings);
}
function commonFunctionToGetStuff (listTitle,successFunction) {
var url = "https://httpbin.org/get";
return $.ajax({...})
.then(function (data) { ...});
}
The thing:
I have a page, which has to display undetermined number of images, loaded through AJAX (using base64 encoding on the server-side) one by one.
var position = 'front';
while(GLOB_PROCEED_FETCH)
{
getImageRequest(position);
}
function getImageRequest(position)
{
GLOB_IMG_CURR++;
$.ajax({
url: urlAJAX + 'scan=' + position,
method: 'GET',
async: false,
success: function(data) {
if ((data.status == 'empty') || (GLOB_IMG_CURR > GLOB_IMG_MAX))
{
GLOB_PROCEED_FETCH = false;
return true;
}
else if (data.status == 'success')
{
renderImageData(data);
}
}
});
}
The problem is that images (constructed with the renderImageData() function) are appended (all together) to the certain DIV only when all images are fetched. I mean, there is no any DOM manipulation possible until the loop is over.
I need to load and display images one by one because of possible huge number of images, so I can't stack them until they all will be fetched.
Your best bet would be to restructure your code to use async ajax calls and launch the next call when the first one completes and so on. This will allow the page to redisplay between image fetches.
This will also give the browser a chance to breathe and take care of its other housekeeping and not think that maybe it's locked up or hung.
And, use async: 'false' is a bad idea. I see no reason why properly structured code couldn't use asynchronous ajax calls here and not hang the browser while you're fetching this data.
You could do it with asynchronous ajax like this:
function getAllImages(position, maxImages) {
var imgCount = 0;
function getNextImage() {
$.ajax({
url: urlAJAX + 'scan=' + position,
method: 'GET',
async: true,
success: function(data) {
if (data.status == "success" && imgCount <= maxImages) {
++imgCount;
renderImageData(data);
getNextImage();
}
}
});
}
getNextImage();
}
// no while loop is needed
// just call getAllImages() and pass it the
// position and the maxImages you want to retrieve
getAllImages('front', 20);
Also, while this may look like recursion, it isn't really recursion because of the async nature of the ajax call. getNextImage() has actually completed before the next one is called so it isn't technically recursion.
Wrong and wrong. Don't user timers, don't chain them. Look at jQuery Deferred / when, it has everything you need.
var imgara = [];
for (image in imglist) {
imgara[] = ajax call
}
$.when.apply($, imgara).done(function() {
// do something
}).fail(function() {
// do something else
});
Try using setInterval() function instead of while().
var fetch = setInterval(loadImage, 2000);
function loadImage(){
position= new position; //Change variable position here.
getImageRequest(position);
if(!GLOB_PROCEED_FETCH){
clearInterval(fetch);
}
}
I'm using backbone and I have this code:
render: function() {
var displayData = this.model;
fetchData('checkComplete', this.model.id, function(checkCompleteData) {
displayData.complete = checkCompleteData; // Value is true
});
fetchData('showGraphicAssets', this.model.id, function(showGraphicsData) {
$.each(showGraphicsData, function(index, value) {
if (value.type === "GRAPHIC_A") {
displayData.assetId = value.id; // Value is 808
}
});
});
console.log(displayData.complete); // Valus is undefined
console.log(displayData.assetId); // Value is undefined
var html = this.template.tmpl(displayData.toJSON());
$(this.el).html(html);
}
fetchData = function(dataRequest, id, callback) {
request = '/show/' + id + '/completed.json';
$.ajax({
url: '/app' + request,
type: 'GET',
dataType: 'json',
success: function(data) {
callback(data);
}
});
};
As you can see, I have the variable displayData defined outside of the fetchData functions. When I try to add properties inside the fetchData context, it works, and when I try to use it outside the fetchData context, it results to undefined. How can I fix this?
It is the most common problem people have with JavaScript. You do not honor the asynchronous nature of your callbacks.
You can not set a value in a callback function (like you do with displayData.assetId) and assume that it must be available a few lines later. It's not. It will never be.
It will be available when the callbacks are done. Since you have two of them, use jQuery's $.when()function (and its companions .then(), .fail() and .always()) which have been made specifically for handling multiple asynchronous calls:
render: function () {
var self = this, model = self.model, template = self.template;
$.when(
$.get('/app/show/checkComplete/' + model.id + '/completed.json'),
$.get('/app/show/showGraphicAssets/' + model.id + '/completed.json')
)
.then(function (checkCompleteData, showGraphicsData) {
// this will receive the response data in the correct order
model.complete = checkCompleteData;
$.each(showGraphicsData, function (index, value) {
if (value.type === "GRAPHIC_A") {
model.assetId = value.id;
return false; // break the $.each()
}
});
$(self.el).html( template.tmpl(model.toJSON()) );
})
.fail(function () {
// this will be called if either HTTP request fails
// also check out the arguments and react accordingly to errors
});
}
Note how the code also gets shorter as you need less boilerplate.
If you've made sure that your views use the correct Content-Type (application/json) then $.get() is enough; avoiding $.ajax() is visually much cleaner.
Ive been struggling to pass my parameters from a functions but I just really can't figure out where did I go wrong. I have a function that have a parameters that I want to pass to my postData to display datas in my jQgrid. Here's my function code with parameters:
function getTID(hdrID){
var selected = $('#editTallyHdr').val();
var hdrID = '';
var hdrNo = '';
var nameFlag=0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/tallyHdr',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'transaction_id'){
hdrID = rowArrayValue;
}
if (fldName == 'transaction_num'){
hdrNo = rowArrayValue;
if(selected == hdrNo){
nameFlag =1;
};
}
});
});
}
}
});
return (hdrID);
}
and here is my jQgrid code where I call that function to get it's parameter:
$("#tblPlank").jqGrid({
url: '',
datatype: 'local',
jsonReader : {
.
.
.
serializeGridData: function(postData) {
var ctr =0;
var filt=[];
var c=[];
var jsonParams = {
'SessionID': $.cookie("SessionID"),
'dataType': 'data',
'transaction_id':getTID(hdrID),
'filters': c,
'lines':plank_data,
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
.
.// some code here
.
.
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:[...],
colModel:[
........................
],
.
.
.
caption: "Tally Transaction Details/Lines"
I also have another code where I want to get that parameter. Here's the last code:
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data",
"transaction_id": getTID(hdrTID)
}
$('#tblPlank').setGridParam({
url:'processjson.php?path=' + encodeURI('getData/tallyLnDtl') + '&json=' + encodeURI(JSON.stringify(par_ams)),
datatype: primeSettings.ajaxDataType,
});
$('#tblPlank').trigger('reloadGrid');
Those codes below that function getTID(hdrID) cant retrieve the parameter, it shows empty. This maybe simple to anyone, but I really need help on this.. been working with this for quite long hours.
This is a very common misunderstanding. I've probably answered 15 of these questions in the last two weeks alone. An ajax call is an asynchronous call. That means that when you make the ajax call, it just STARTs the request. Then, while that request goes in the background, your code immediately keeps executing. That means that your function getTID() returns before the ajax call has even completed and it's value is not yet known. Thus, there is no way to return the response value from the ajax function when you return from getTID() as it is simply not known yet.
To work with asynchronous function calls (like ajax calls), you have to change your programming style to something that works asynchronously. In this case, the response to your ajax call is ONLY known in the success handler for the ajax all. So, you have to restructure your code to continue on with the execution of your processing and the handling of the ajax response from the success handler. If you have only a little bit of work to do, then you can put it all in the success handler. If you have a lot of work to do, then you can put all the rest of that work in a function call and call it from the success handler.
The problem is that you're doing an ajax-request (asynchronous request). Then the function does not wait for an answer to arrive, but just continues and returns hdrID (which isn't set at the time). After that a response comes in, and the success-method is called, which sets hdrID to the appropiate value.
The common way to solve this is to execute a specific function with the desired values when the success-method is executed. It's too much code to look into, but it could go something like this:
function fetchContent(continueFunction) {
$.ajax(params).success(function(reply) {
// retrieve desired params from reply
continueFunction(retrievedParameters);
}
}
What you could do is define getTID to take in a callback to execute once it has the id, for instance
function getTID(hdrID, callback) {
//ajax stuff....
success: function (data) {
// Error checks, etc
hdrID = //something dependent on data
callback(hdrID); // THIS IS THE IMPORTANT PART
}
the callback will execute after the request has returned, when it is safe to use the data returned from the ajax request that will be needed in the callback. You could wrap all of the code that needs the return value of the request in the callback, for example
getTID(hdrID, function (ID) {
var params = {
"SessionID": $.cookie("SessionID"),
"dataType": "data",
"transaction_id": ID //USE ID
}
$('#tblPlank').setGridParam({
url:'processjson.php?path=' + encodeURI('getData/tallyLnDtl') + '&json=' + encodeURI(JSON.stringify(par_ams)),
datatype: primeSettings.ajaxDataType,
});
$('#tblPlank').trigger('reloadGrid');
};
});
I have this function that embeds flash :
function embedswfile(target, swf, base, width, height) {//dosomething}
And I want to call the function like this
embedSwf("flashgame",decode("<?=base64_encode($path['location'])?>"),decode("<?=base64_encode($path['base_directory'])?>"),"800","600" )
The idea is that whenever someone looks for any swf inside my website,he wont find anything clean.I will change the encoding algorithm,but this is just temporary. In order for that function to work,whenever I call the function 'decode' it must return a single value. PHP contains
<?php
echo base64_decode($_POST['s']);
?>
I tried this but it still wont work
var globvar;
function processdata(newmsg) {
globvar = newmsg;
}
function decode(s){
$.ajax({type: "POST",
url: "includes/decode.inc.php",
data: "s=" + s,
success:function(newmsg){
processdata(newmsg);
}
});
return globvar;
}
Important:
Forget about using Ajax and encoding, decoding the path. What do you think you gain from it? Security? No. One can figure out that this is bas64 encoded or he just monitors the network traffic and reads the response from the Ajax call.
Just do
embedSwf("flashgame","<? =$path['location']?>"),"<?=$path['base_directory']?>","800","600" )
Really, you cannot prevent someone else seeing the data and are just making things more complicated for you.
(Or you have to decrypt the data with JavaScript.)
(original answer is still correct nevertheless)
Ajax is asynchronous so something like var test = decode(s); will never work. The decode function will return before the Ajax call finishes.
Instead, put your logic into the callback handler. For example, if your code was this before:
var retdata = decode('s');
// here comes code that handles retdata
put the code into a function and call it from the success handler:
function process(retdata) {
// here comes code that handles retdata
}
function decode(s){
$.ajax({type: "POST",
url: "includes/decode.inc.php",
data: "s=" + s,
success:function(newmsg){
process(newmsg);
}
});
}
This seems to be a very common problem to all beginners. You will find a lot of questions here that deal with the same problem.
Update:
It is not nice, but you could change the function to
function decode(s, cb){
$.ajax({type: "POST",
url: "includes/decode.inc.php",
data: "s=" + s,
success:function(data){
cb(data);
}
});
}
and do
decode("<?=base64_encode($path['location'])?>", function(location) {
decode("<?=base64_encode($path['base_directory'])?>", function(dir) {
embedSwf("flashgame",location,dir,"800","600" );
});
});
Update 2:
For completeness, you can make the Ajax call synchronous, by using async: false. Then this will work:
function decode(s){
var ret;
$.ajax({type: "POST",
url: "includes/decode.inc.php",
data: "s=" + s,
async: false,
success:function(newmsg){
ret = newmsg;
}
});
return sync;
}
var val = decode(s);
However, this will block the browser until the Ajax call finished. You have to test whether this matters in your case or not.
Update 3:
You could also change your PHP script to not only accept one parameter but several and process both strings in one go.