please check this:
var scripts = {};
require = function(src){
var id = Math.round(+new Date()/1000);
$.ajax({
url: src + '.json',
type: 'GET',
dataType: "json",
cache: false,
async: false,
success : function(data){
scripts[id] = data;
}
});
return scripts[id];
}
return undefined :/ What is the problem!? i don't know...
EDIT! 'async : false' and run!
It is because $.ajax is asynchronous in your call.
return scripts[id];
The above line is executed even before the success callback is triggered.
it is a asynchronous call. scripts is empty when you return.
to verify the cause,
window.scripts = {};
require = function(src){
var id = Math.round(+new Date()/1000);
$.ajax({
url: src + '.json',
type: 'GET',
dataType: "json",
cache: false,
success : function(data){
window.scripts[id] = data;
alert(window.scripts)
}
});
//return scripts[id];
}
after alert, see the value of window.scripts
its async issue .. Ajax call is called asynchrnously.
return scripts[id];
is executed before ajax call return.s
Your problem is that the call is asynchronous. This means that your method is returning before the call is finished.
Instead of returning the scripts[id] try this instead:
require = function(src){
var id = Math.round(+new Date()/1000);
$.ajax({
url: src + '.json',
type: 'GET',
dataType: "json",
cache: false,
success : function(data){
scripts[id] = data;
DoStuff(scripts[id]);
}
});
}
DoStuff(data) {
// do whatever it is you were going to do after the return.
}
Related
Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.
When I return the value it always comes up undefined when I alert() inside it shows the proper values.
function getItemInfo(itemHashPass) {
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
return data.Response.data.inventoryItem.itemName;
}
});
}
I've also tried
function getItemInfo(itemHashPass) {
var tmp = null;
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
tmp = data.Response.data.inventoryItem.itemName;
}
});
return tmp;
}
Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like
function yourBusinnesLogicFunction() {
...
getItemInfo("password_hash_value").done(
function(data){
alert(data.Response.data.inventoryItem.itemName);
}
)
}
function getItemInfo(itemHashPass) {
var tmp = null;
return $.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
})
}
I am working on a real estate web app in ASP.NET MVC. My problem is in my Reservations section.
I am using AJAX to post in a Controller which returns a JSONResult. Here is my code:
Controller
[HttpPost]
public JsonResult SubmitReservation(ReservationViewModel rvm)
{
return Json(rvm, JsonRequestBehavior.AllowGet);
}
Main AJAX
var rvm = new ReservationViewModel();
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
$.ajax({
url: "/Reservations/SubmitReservation",
data: JSON.stringify(rvm),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function () {
console.log(clientData);
console.log(siteData);
console.log(unitData);
//Assignment of data to different output fields
//Client Data
$('#clientName').html(clientData.FullName);
$('#clientAddress').html(clientData.Residence);
$('#clientContact').html(clientData.ContactNumber);
//Site Data
$('#devSite').html(siteData.SiteName);
$('#devLoc').html(siteData.Location);
////House Unit Data
$('#unitBlock').html(unitData.Block);
$('#unitLot').html(unitData.Lot);
$('#modelName').html(unitData.ModelName);
$('#modelType').html(unitData.TypeName);
$('#lotArea').html(unitData.LotArea);
$('#floorArea').html(unitData.FloorArea);
$('#unitBedrooms').html(unitData.NumberOfBedrooms);
$('#unitBathrooms').html(unitData.NumberOfBathrooms);
$('#unitPrice').html(unitData.Price);
$('#reservationDetails').show();
alert("Success!");
},
error: function (err) {
alert("Error: " + err);
}
});
Functions for fetching data
function getBuyerInfo(id, cb) {
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getSiteInfo(id, cb) {
$.ajax({
url: "/Sites/GetSiteByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getUnitInfo(id, cb) {
$.ajax({
url: "/HouseUnits/GetUnitByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function ReservationViewModel() {
var buyerId = $('#SelectedBuyerID').val();
var siteId = $('#SelectedSiteID').val();
var unitId = $('#SelectedUnitID').val();
var rsvDate = $('#ReservationDate').val();
var me = this;
me.ReservationDate = rsvDate;
me.SelectedBuyerID = buyerId;
me.SelectedSiteID = siteId;
me.SelectedUnitID = unitId;
}
function clientCallback(result) {
clientInfo = result;
clientData = clientInfo[0];
}
function siteCallback(result) {
siteInfo = result;
siteData = siteInfo[0];
}
function unitCallback(result) {
unitInfo = result;
unitData = unitInfo[0];
}
The whole code WORKS well for the second time. However, it does not work for the FIRST time. When I refresh the page and I hit Create, it returns undefined. But when I hit that button again without refreshing the page, it works well. Can somebody explain to me this one? Why does AJAX returns undefined at first but not at succeeding calls? Thanks in advance.
You are calling several ajax requests in your code, inside these functions:
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
and finally $.ajax({...}) after them, where you use results from pervious ajax calls.
Your problem is that the first ajax calls do not necessarily return results before your start the last ajax because they are all async. You have to make sure you get three responds before calling the last ajax. Use promises or jQuery when, like this:
var rvm = new ReservationViewModel();
$.when(
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + rvm.SelectedBuyerID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/Sites/GetSiteByID/" + rvm.SelectedSiteID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/HouseUnits/GetUnitByID/" + rvm.SelectedUnitID,
type: "GET",
contentType: "application/json",
dataType: "json"
})
).done(function ( clientResponse, siteResponse, unitResponse ) {
clientInfo = clientResponse;
clientData = clientInfo[0];
siteInfo = siteResponse;
siteData = siteInfo[0];
unitInfo = unitResponse;
unitData = unitInfo[0];
$.ajax({ ... }) // your last ajax call
});
AJAX calls are asynchronous. You last ajax call will not wait until your above 3 ajax calls finishes its work. so you can make use of $.when and .done here as below..
$.when(
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
).done(
$.ajax({
//Ajax part
})
);
I am making a simple ajax request using jquery . Below is my ajax function .
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
return data;
}
}
});
}
here is my function calls :
var items = {
"type" : 'POST',
"url" : ajaxGetUrl,
"data" : arrParam['data'],
"data_type" : 'html'
};
var msg = makeJqueryAjaxRequest(items);
Now don't know why my makeJqueryAjaxRequest function always returns the null value. If I alert the data in the success : I'm getting the data perfect . But when I try to return it gives me the null value
You can't return value from an Asynchronous callback function.
Because success is a async callback which is called by jQuery when a ajax Event(success in this case) fires. So returning something from this functions will not have any effect as they will be returned to jQuery code.
You can use the following
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type']
});
return request;
}
Then do
makeJqueryAjaxRequest(items).done(function(data){
if(data){
var msg = data;
// do whatever you like with msg now
}
});
Alternative Callback Approach:
var makeJqueryAjaxRequest = function(arrParam,callback) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
callback(data);
}
}
});
}
Then use it like
makeJqueryAjaxRequest(items,function(data){
// do whatever you like with data
});
Doc on $.ajax()
Note
And with either of these approach async: false is not necessary. You can remove that. As the doc says
As of jQuery 1.8, the use of async: false is deprecated
I want to set an variable in the function after i send an ajax request.
What is the reason why the function alert outside the getjson function undefined and inside the good value? Is there some solution?
function gettextlabel(txtvar){
var v = '';
$.getJSON('http://192.168.0.92/visuals/support/text_handler.php?txtvar=' + txtvar , function(data) {
v = data;
alert(v);
});
alert(v);
}
Because by default jQuery send ajax request asynchronously.
You can set the option async to false to force it work synchronously, like:
$.ajax({
type: 'GET',
url: 'http://192.168.0.92/visuals/support/text_handler.php?txtvar=' + txtvar,
dataType: 'json',
success: function(data) { v = data; alert(v); },
async: false
});
This should work:
function gettextlabel(txtvar){
var v = '';
$.ajax({
url: 'http://192.168.0.92/visuals/support/text_handler.php',
data: 'txtvar=' + txtvar,
type: 'GET',
dataType: 'json',
async: false,
success: function (data) {
v = data;
alert(v);
}
});
alert(v);
}
in my code i have the following
var response = "";
function send_ajax(){
if(response == ""){
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
success: function(data){
response = data;
}
});
}
}
my problem is that send_ajax function is called several times in my script, and sometimes alot of ajax calls is send together and no need for that. so i'm searching for a solution in which if one ajax request is send other calls should wait until that function saves the data in the response var and use it.
how can i do that ?
If you set the async flag to false, no other calls are made until the first call is done.
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
async: false,
success: function(data){
response = data;
}
});
if(response == ""){
response = 'waiting';
will do the trick, no ?
Another solution if you want the $.ajax to be async, but only allow one ajax request at any time. You could take a look at $.ajaxStart and $.ajaxStop global event
var ajaxLock = false;
$.ajaxStart(function(){ajaxLock = true;});
$.ajaxStop(function(){ajaxLock = false;});
var ajaxRequest = function(url, data) {
if (!ajaxLock) {
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
async: false,
success: function(data){
response = data;
}
});
}
}