How to synchronize $.each(); function with called function in it? - javascript

I kept one function in $.each() function and sending an array of elements to that function by using $.each() function. But the $.each() function doesn't care about the function and itself running.
Please solve my problem
This is the code
$.each(addrArray, function(i, item) {
alert(addrArray[i].ActualAddress);
getLatLang(addrArray[i].ActualAddress, addrArray[i].BusinessEntityID);
});

Assuming that you have Ajax call written in getLatLang() function; i will suggest to make that Ajax call synchronous like follows:
$.ajax({
url: 'your url for getting lat-long',
type: 'POST',
data: {your address},
async: false,
success: function() {}
});
Here async: false will do the job. Your program execution will remain in this function till the time you get back your lat-long from server. Once returned from this function; your .each loop will get incremented.

each(function() {
if (something)
return false;
});
For Documentation : Link

Related

Return a controller method values using ajax

I have a function, that call a controller method using ajax
function CallService(data) {
$.ajax({
url: '#Url.Action("MyMethod", "MyController")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'serializedMessage': data }
});
MyMethod() returns a complex object and I need to display some properties on the page.
<script>
$(function(){
// create inputData
function (inputData) {
var myItem = CallService(inputData);
$('#name').text(myItem.Name);
};
});
</script>
As ajax returns nothing, I get an error message 'myItem is undefined' on the page. Can anyone explain how to return a variable and use it in JS functions, please?
I'm surprised you couldn't find an example of this anywhere already, but here goes:
There are a few different ways of defining callbacks which can run when the ajax call completes, as shown in the docs at http://api.jquery.com/jquery.ajax/. Here is one, based on the promises API:
function (inputData) {
$.ajax({
url: '#Url.Action("MyMethod", "MyController")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'serializedMessage': inputData }
}).done(function(result) {
console.log(JSON.stringify(result)); //just for debugging, to see the structure of your returned object
$('#name').text(result.Name);
});
}
One thing you need to grasp is that ajax calls run asynchronously, so the structure you had before will not work - you can't return anything directly from your "CallService" wrapper, which kind of makes it redundant. You have to wait until the ajax call completes, and run any code which depends on the result within (or within a function called from) the "done" callback.
As per the docs I linked to you can also define other callbacks for tasks such as handling errors, if you so desire.
You must use success:function(response){
}

Success callback is executing after all cordova.exec functions have ended

I am building a phonegap application and my current native platform is android. I have a problem. I have a array list built in java. And I have to compare the array with a service that i called from javascript. But issue is that when i call cordova.exec inside for loop, first entire for loop executes and then the control shifts to callbacksuccess for all cordova.exec.
My code is-
$.ajax({
url : ...,
type: "GET",
data: null,
setTimeout:1,
dataType:"JSON",
success: function(response)
{
var mydata='';
for(var i=0;i<response.length;i++)
{
alert('inside for '+i);
obj=response[i];
var testpackage=obj.PackageName;
cordova.exec(callbacks,callbacke,'MyPlugin','plugin2',[testpackage]);
}
},
error: function()
{
alert('Failed to fetch list.Try again later.');
}
});
function callbacks(e)
{
alert('success');
}
My callbacks() function is called after the whole for loop executes.
The output that I am receiving is-
inside for 0
inside for 1
inside for 2
success
success
success
My expected output is-
inside for 0
success
inside for 1
success
inside for 2
success
I have tried many things. Still I am not finding the solution.
Thanx in advance.
cordova.exec call is asynchronous. Therefore you should change your code such that you call the consecutive cordova.execs inside the callback itself or implement something similar; simply wait for each exec call to complete before calling the next one.

How to extract ajax response data from the success callback

Sorry if this is a duplicate but I couldn't find any satisfying answers in the previous posts.
$(function() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
// Data received here
}
});
});
[or]
someFunction() {
return $.ajax({
// Call and receive data
});
}
var myVariable;
someFunction().done(function(data) {
myVariable = data;
// Do stuff with myVariable
});
The above code works just fine. However, this ajax request is made on page load and I want to process this data later on. I know I can include the processing logic inside the callback but I don't want to do that. Assigning the response to a global variable is not working either because of the asynchronous nature of the call.
In both the above ways, the 'data' is confined either to the success callback or the done callback and I want to access it outside of these if possible. This was previously possible with jQuery 'async:false' flag but this is deprecated in jQuery 1.8.
Any suggestions are appreciated. Thank you.
You can "outsource" the callback to a normal function, so you can put it somewhere, you like it:
$(function() {
$.ajax({
url: 'ajax/test.html',
success: yourOwnCallback
});
});
somehwere else you can define your callback
function yourOwnCallback(data) {
// Data received and processed here
}
this is even possible with object methods as well
This solution might not be idea but I hope it helps.
Set the variable upon callback.
Wherever you need to process the data, check if variable is set and if not wait somehow.
Try:
$(document).ready(function(){
var myVar = false;
$.ajax({
url: 'ajax/test.html',
success: function(data) {
myVar=data;
}
});
someFunction(){ //this is invoked when you need processing
while(myVar==false){}
... do some other stuff ..
}
});
Or
someFunction(){
if(myVar==false){
setTimeout(someFunction(),100); //try again in 100ms
return;
}
.. do some other stuff ..
}

jQuery Async Issue, Variable Assignment After GET Request

I'm sure the solution is staring me right in the eyes, but I just cannot see it. I am trying to load an object from an outside file source. I've tried it several which ways using jQuery's built in methods, but keep returning undefined. Is my issue the scope? I need partnerData right where it is because of other dependent methods in my script. I don't want to operate the rest of my site's functions from within the $.get callback. Any help is greatly appreciated, here's the code:
$(function() {
var partnerData;
$.get('data/partners.json', function(file) {
partnerData = $.parseJSON(file);
});
console.log(partnerData); /* returns undefined instead of object */
});
EDIT:
Thanks for all the feedback everyone. This is the solution I went with:
var partnerData;
$.ajax({
url: 'data/partners.json',
dataType: 'json',
async: false,
success: function(data) {
partnerData = data;
}
});
The reason why you're seeing undefined is because ajax requests are asynchronous by default. This means your get method gets invoked and the code flow moves down to the next statement while the request executes in the background. Your callback function is later invoked when the request completes.
Using callback functions is a common pattern used in situations like this. But you seem to be saying you don't want to do or can't do that. In that case, you could use async: false which would force the request to be synchronous. Keep in mind however, that your code will be blocked on the request and if it's a long-lived request, the user experience will degrade as the browser will lock up.
P.S. You shouldn't need to parseJSON - if response has the correct mime-type set, jQuery will intelligently guess the type and parse the JSON automatically. And in case the server isn't sending back the correct mime-type, you can also explicitly tell jQuery what the expected return data type is; see the dataType argument to $.get() .
One way you might modify your code, to force synchronous requests:
$.ajax({
type: 'GET',
url: 'data/partners.json',
success: function(file){
partnerData = $.parseJSON(file);
//ideally you would perform a callback here
//and keep your requests asynchronous
},
dataType: 'json',
async: false
});
function is proccessed to the end event when ajax is still being proccessed. insert it into callback function
$(function() {
var partnerData;
$.get('data/partners.json', function(file) {
partnerData = $.parseJSON(file);
console.log(partnerData);
});
});
I would say that your problem is the same of the one that I just solved, if $.get is AJAX! and it is setting a variable, to read that variable outside the callback you need to wait the response! So you have to set async=false!
console.log in synchronous and get is async.
try:
$(function() {
var partnerData;
$.get('data/partners.json', function(file) {
partnerData = $.parseJSON(file);
test();
});
function test(){
console.log(partnerData);
}
});

Javascript - local scope objects not accessible from nested function

I am trying to have a function grab an object from a php file on another page. I'm using the jQuery ajax function to to do the json grab, which is working correctly. The issue is when I try to return that object from the function.
The first time I log the object (from within the success function) it is correct in the console, but the returned object from the function getGantt() logs as "undefined".
How do I get this object out of the function?
My code:
function getGantt(requestNumber){
var ganttObject;
$.ajax({
type: "POST",
url: "get_gantt.php",
data: {request_number: requestNumber},
success: function(returnValue){
ganttObject = $.parseJSON(returnValue);
console.log(ganttObject); //this logs a correct object in the console
}
});
return ganttObject;
}
$(function(){ //document ready function
var requestNumber = $('#request_number').text();
var ganttObject = getGantt(requestNumber);
console.log(ganttObject); //this logs "undefined"
}); //end document ready function
The A in Ajax is an important part of the acronym. Asynchronous JavaScript and XML is asynchronous.
$.ajax({success:someFunction}) means Make an HTTP request and when the response arrives, run someFunction
return ganttObject runs before the response arrives.
You should do anything you want to do with the data inside someFunction and not try to return data to the calling function.
The A in AJAX stands for asynchronous. So the call immediately returns and as soon as it finishes, the success callback is called.
So, simply change your code to use a callback:
function getGantt(requestNumber, callback) {
var ganttObject;
$.ajax({
type: "POST",
dataType: 'json',
url: "get_gantt.php",
data: {request_number: requestNumber},
success: function(returnValue){
callback(returnValue);
}
});
}
$(function() {
var requestNumber = $('#request_number').text();
var ganttObject = getGantt(requestNumber, function(ganttObject) {
console.log(ganttObject);
});
});
Btw, I've also removed this parseJSON stuff - setting dataType to json does the job and is less dirty.
I know why it's not returning it at least. The ganttObject may be in the same scope, but the success function is ultimately running in the readyState callback from the XMLHTTP object, so it's on a different thread than the getGantt function. Can you make the $(function(){... code apart of your success function?

Categories