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){
}
Related
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
So I have script that is for a Bingo game. I'm having a problem running one of my functions inside another function. The idea was to have my checkBingo() function be defined outside of a .click() function. There's some ajax at work, so I'm not sure if that's coming into play here too. Looks something like:
$(document).ready(function(){
function checkBingo() {
$.ajax({
url: '/check-bingo',
type: 'GET',
success: function(data){
return data;
}
}):
}
$('#div').click(function() {
// Some stuff gets done here
$.ajax({
url: '/tile',
type: 'GET',
success: function(data){
// Does some stuff with data, then needs to check if there's a bingo.
var isBingo = checkBingo();
if (isBingo == 'something') {
// Displays something specific on the page.
} else {
// Displays other things on the page.
}
}
}):
});
Where I'm getting hung up, is that isBingo is never getting assigned the returned info. I thought it might have been because the query wasn't running fast enough, so I've tried sticking the variable in a loop until it got something assigned to it and then the console told me that my checkBingo() inside the .click function wasn't defined. I'm not sure if it's just a stupid syntax error on my part or if what I'm doing isn't possible.
Can someone verify that this is indeed possible and that I've probably just got to scour it for the syntax error?
Because this line:
var isBingo = checkBingo();
...is calling an function (checkBingo) which makes an asynchronous call and does not return anything, isBingo will be undefined.
One way to approach this would be to pass a callback function to checkBingo since JavaScript allows functions to be passed around like data, and the function will be called by jQuery when the data is obtained from the server:
function checkBingo(callback) {
$.ajax({
url: '/check-bingo',
type: 'GET',
success: function(data){
callback(data);
}
// or you could just do:
// success: callback,
});
}
// ....
success: function(data){
checkBingo(function (isBingo) {
if (isBingo == 'something') {
// Displays something specific on the page.
} else {
// Displays other things on the page.
}
});
Another approach, which would allow you to continue using your synchronous style (i.e., where checkBingo could return something and you could immediately use it) even though the code is not executed synchronously is by taking advantage of the fact that the later versions of jQuery's Ajax API return a promise object which allows this style of coding:
$(document).ready(function(){
function checkBingo() {
return $.ajax({
url: '/check-bingo.txt',
type: 'GET'
});
}
$('#div').click(function() {
// Some stuff gets done here
$.ajax({
url: '/tile.txt',
type: 'GET',
success: function(data){
var checkingBingo = checkBingo();
checkingBingo.done(function (isBingo) {
if (isBingo == 'something') {
alert('a');
// Displays something specific on the page.
} else {
alert('b');
// Displays other things on the page.
}
});
}
});
});
});
Besides the need to convert a couple of your colons into semi-colons, and add the jQuery $ in front of your "#div" code, two other aspects to note:
I added the ".txt" extension to the Ajax calls in case the extension was merely hidden on your system.
The code $('#div') presumes that there is an element on your page with the ID set to "div". If you want all div elements to be clickable, you would simply need to do $('div').
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 ..
}
I have several ajax call on my page and I want to consolidate them into one function.
For now I have this type of function in several places:
function AjaxCallOne () {
//do something
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: TheURL,
data: "{'TheData':'" + JsonData + "'}",
dataType: "json",
cache: "false",
success:...
error:...
});
}
I want to write a single function that'll be used for all ajax calls like this:
function MyGeneralAjaxCall(TheData, TheURL, TheSuccessFunction, TheErrorFunction) {
$.ajax({ .... });
}
My question is this: if I do that and the user send two ajax calls, almost simultaneously, to the point where the second ajax call is made before the returning data of the first call comes back, will the success or error functions trigger for the the correct call. I'm worried that the success function that'll be executed won't be for the proper ajax call if the user triggers a second call before the first one is returned.
Thanks.
Your approach will work as you expect. Each success function, etc., that you pass in will be used individually by each associated AJAX call. (All of your parameters will be kept together.)
First, There's no single, global set of callbacks for ajax requests. Each ajax invocation gets it's own set of callbacks.
Secondly: $.ajax({...}) is your MyGeneralAjaxCall... if you are thinking you need a set of default options, a better way would be to set up a
var defaultoptions = { type: "POST", ...} //put default options, mimetypes, etc, here
(or something that returns that) and then wherever needed do:
var myajaxoptions = $.extend({},defaultoptions,myoverrides);
$.ajax(myajaxoptions);
That's much more extensible. No need to make up "men in the middle". Your approach will work, but I could easily see more than one MyGeneralAjaxCall being created. If you can manage not creating 5 or more methods like that MyGeneralAjaxCall, I suppose you'll be doing ok, but it could get nasty real quick.
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?