Can I use jquery's .done() more than once? - javascript

I have 2 JS literals:
var obj1 = {
Add: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/add",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
var obj2 = {
List: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/list",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
And this is my document.ready:
$(document).ready(function () {
obj1.Add(1).done(function (data) {
alert('you added ' + data);
});
obj2.List().done(function (data) {
$.each(jQuery.parseJSON(data), function (i, item) {
// fill a combo box
});
});
});
jQuery just executes the first call and obj2.List() ain't called at all.
How to properly use the deffered objects in this case?

Change your Add and List function to RETURN the ajax object.
Add: function (id) {
return $.ajax({..
and
List: function (id) {
return $.ajax({...
This way - it will return the jqXHR obj which will return the deferred object.
This implement the Promise interface which has : the callbacks you are looking for.
edit :
look at this simple example which does work :
var obj1 = {
Add: function (id) {
return $.ajax({
type: "get",
data: JSON.stringify({
"id": 1
}),
url: "http://jsbin.com/AxisAmi/1/quiet",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("at success --"+data.data)
}
});
}
};
obj1.Add(2).done(function (a){alert("at done --"+a.data);});

Related

How do i split ajax return values using jquery

I want to split the ajax returned values using jQuery.
Here is my code:
var url = "/StudentProgress/GetStudProgDet/";
$.ajax({
url: url,
data: { currentAcadYr: iAcademicYearText, currentSem: iSemesterText },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (data) {
var result = $(data).text().split(':');
var ProgAcadYearCode = result[0].ProgAcadYearCode;
var productSize = result[1];
// alert(data.ProgAcadYearCode);
//$("#ToProgressAcademicYearId option").filter(function () {
// return this.text == testsem;
//}).attr('selected', true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
I got a result like this:
data = {
success: true,
progAcadYearCode: 20172018,
progAcadYearId: 17,
progressSemId: 47,
progressSemNo: 2
}
How do I extract the desired values from the JSON using jQuery?
Based on data what you shown,you have to directly fetch it's properties like below:-
success: function (data) {
console.log(data.success);
console.log(data.progAcadYearCode); //and so on
},

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

How to pass param between ajax calls

I am trying to pass param between two different ajax calls, the params only exist inside the ajax scope but not outside of it.
i saw the option of calling from the first ajax success section to another ajax and i don't want this, is their any other way?
my code
jQuery.ajax({
url: '/modules/products/ajax.php',
data: {
prod_id: prod_id,
act: 'get_selected_values_for_sub_cat'
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {
var res = JSON.stringify(data);
res = jQuery.parseJSON(res);
var selected_array = [];
jQuery.each(res, function(key1, value1) {
selected_array[key1] = jQuery.parseJSON(value1);
})
}
});
console.info("selected_array", selected_array);
i try this
function ajax_get_selected_values_for_sub_cat() {
return jQuery.ajax({
url: '/modules/products/ajax.php',
data: {
prod_id: 123,
act: 'get_selected_values_for_sub_cat'
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {
}
});
}
var re = ajax_get_selected_values_for_sub_cat();
res = JSON.stringify(re);
res = jQuery.parseJSON(res);
var selected_array = [];
jQuery.each(res, function(key1, value1) {
selected_array[key1] = jQuery.parseJSON(value1);
})
console.info("selected_array", selected_array);
what am i missing ?
thanks
ajax function returns an object that implements the promise interface. You can implement it like this:
function ajax_get_selected_values_for_sub_cat(id) {
return jQuery.ajax({
url: '/modules/products/ajax.php',
data: {
prod_id: id,
act: 'get_selected_values_for_sub_cat'
},
type: 'POST',
async: false,
dataType: 'json'
});
}
var promise = ajax_get_selected_values_for_sub_cat(123);
promise.done(function(re){
res = JSON.stringify(re);
res = jQuery.parseJSON(res);
var selected_array = [];
jQuery.each(res, function(key1, value1) {
selected_array[key1] = jQuery.parseJSON(value1);
})
console.info("selected_array", selected_array);
});
http://api.jquery.com/jQuery.ajax/#jqXHR
You can use callback methods as below-
function ajax_get_selected_values_for_sub_cat(successCallback)
{
jQuery.ajax({
url : '/modules/products/ajax.php',
data : {prod_id:123,act:'get_selected_values_for_sub_cat'},
type : 'POST',
async: false,
dataType: 'json',
success:function(data){
successCallback(data);
}
});
}
ajax_get_selected_values_for_sub_cat(function(re){
res =JSON.stringify(re);
res = jQuery.parseJSON(res);
var selected_array =[];
jQuery.each( res, function( key1, value1 ) {
selected_array[key1]=jQuery.parseJSON(value1);
})
console.info("selected_array",selected_array);
});

Passing array to function - array is empty inside function

I tried almost everything, I have two codes:
First one, pokaz_ofe, calls correct function - "generuj_oferte" in ajaxQuery() function, but I cant access postTab array in ajaxQuery(). Without delete postData it was using old array from another call (other that in "pokaz_ofe" function).
function ajaxQuery(postData, func_var) {
$.ajax({
type: "POST",
url: "ajax/pokaz_lst.php",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: func_var
})
postData = [];
delete postData;
}
function pokaz_ofe(id,tab) {
if(!tab) {
var postTab = [
{ "id": id }
]
}
else {
var postTab = [
{ "id": id },
{ "listaId": tab}
]
}
ajaxQuery(postTab, generuj_oferte);
}
function generuj_oferte(res) {
$(document).ready(function(){
$('#modal-oferta').html( res );
});
}
And this is the different code which works, but I want it more flexible:
function pokaz_ofe(id,tab) {
if(!tab) {
var postData = [
{ "id": id }
]
}
else {
var postData = [
{ "id": id },
{ "listaId": tab}
]
}
$.ajax({
type: "POST",
url: "ajax/pokaz_ofe.php",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: generuj_oferte
})
}
It was rly stupid one mistake... now it is:
function ajaxQuery(filename, postData, func_var) {
$.ajax({
type: "POST",
url: "ajax/" + filename + ".php",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: func_var
})
postData = [];
delete postData;
}
It was all about filename.

Revealing module ajax

I have this code:
my.data = function () {
var getAuth = function (userName, password) {
var model = JSON.stringify({ "UserName": userName, "Password": password });
var result;
$.ajax({
url: my.baseUrl + "api/AD",
type: "POST",
data: model,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
result = data;
return result;
}
});
}
return {
getAuth: getAuth
}
}();
when I call getAuth , i can see data returns "true" but the the calling function -
var result = my.data.getAuth(username,password); returns undefined.
any idea?
Sure, it will return undefined, the returned value is of the success function. Not the value of the getAuth function. You should change to:
my.data = function () {
var getAuth = function (userName, password) {
var model = JSON.stringify({ "UserName": userName, "Password": password });
var result;
$.ajax({
url: my.baseUrl + "api/AD",
type: "POST",
data: model,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
result = data;
}
});
return result;
}
return {
getAuth: getAuth
}
}();
Even though this solution works, the use of async: false is not recommended.
Two reasons:
1. When you switch ajax to async: false, you shouldn't pass success: function(){...} property to options hash. Instead of this you should to use chain.
2. When you use return in success function you return from success function only, not from getAuth.
Try this:
$.ajax({
url: my.baseUrl + "api/AD",
type: "POST",
data: model,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
}).success: function (data) {
result = data;
};
return result;
And couple of notes. As you know switching to async: false can cause long delay. This is bad practice and it is deprecated in last JQuery versions. Instead of this you should to use callbacks. Third argument of your getAuth method can be a function, that you should run when query is success:
var getAuth = function( userName, password, callback ){
$.ajax({
url: my.baseUrl + "api/AD",
type: "POST",
data: {userName: userName, password: password},
success: function (data) {
callback( data );
}
});
}
And use this like here:
my.data.getAuth( 'someusername', 'somepassword', function( data ){
alert( 'It looks like your authorized successfully' );
});

Categories