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);
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I've built a function to handle a request that I intend to use in various pages. But I can't find a way to access it's return! Here is what my code looks like:
function buscaIdEmpresa() {
var jsonEmail = { "email": emailCurrentUser };
var jsonEmailString = JSON.stringify(jsonEmail);
var test = $.ajax({
url: "https://localhost:44326/test",
type: "post",
async: false,
crossDomain: true,
data: jsonEmailString,
contentType: "application/json",
dataType: "json",
complete: function (data) {
var id = data.responseText;
alert(id)
//this returns id as expected
return id;
}
});
alert(test)
//this returns object Object
return test;
}
function carregaConfigList() {
var id = buscaIdEmpresa()
alert(id)
//this returns object Object
}
Also I am not entirely sure that this is the correct way to tackle the problem. I'm open to suggestions, but I would not like to write the entire ajax function every single time the request needs to be done. How can I access the object value? Is there a more 'correct' way of doing this?
Couple ways you could do this, my preferred method is using async/ await
function buscaIdEmpresa() {
return new Promise(resolve => {
var jsonEmail = { "email": emailCurrentUser };
var jsonEmailString = JSON.stringify(jsonEmail);
$.ajax({
url: "https://localhost:44326/test",
type: "post",
async: false,
crossDomain: true,
data: jsonEmailString,
contentType: "application/json",
dataType: "json",
complete: function (data) {
var id = data.responseText;
resolve(id);
}
});
})
}
async function carregaConfigList() {
var id = await buscaIdEmpresa()
alert(id)
}
But you could also use a callback pattern
function buscaIdEmpresa(callback) {
var jsonEmail = { "email": emailCurrentUser };
var jsonEmailString = JSON.stringify(jsonEmail);
$.ajax({
url: "https://localhost:44326/test",
type: "post",
async: false,
crossDomain: true,
data: jsonEmailString,
contentType: "application/json",
dataType: "json",
complete: function (data) {
var id = data.responseText;
callback(id);
}
});
}
function carregaConfigList() {
buscaIdEmpresa(function(id){
alert(id)
})
}
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
},
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)
}
});
}
I'm writing my first Ajax request, on a Groovy/Grails platform.
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
data: {source:"${source}"},
success: function (response) {
jsonData = response;
var res = JSON.parse(jsonData);
alert(res);//
}
});
Here is the response of my controller "url"
def result = [ value: 'ok' ]
render result as JSON
But it does not work and i get an error message in my browser
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var res = JSON.parse(jsonData);
I don't understand , the response seems to be a nice formatted JSON ?
EDIT i did a print as Paul suggests :
If i execute
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
console.log(response)
console.log(response.value)
jsonData = response;
}
});
The first print is :
Object { value="ok"}
The second print is
ok
If i want to get the result, how is the proper way ?
Do i have to assign the value inside the statement "success: function (response) { "
doing something like
var result
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
result = response.value
}
});
console.log("result : "+result);
This code works for me !!
Or perhaps there is a way to get the result, doing something like
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
}
});
var result = newDataB.response.somethingblablabla
or
var result = OneFunction(newDataB.response)
??????
You can make object stringified before passing it to parse function by simply using JSON.stringify().
var newDataB = $.ajax({
method: 'post',
url: "${createLink(controller: 'util',action: 'test')}",
async: false,
data: {source: "abc"},
success: function (response) {
jsonData = response;
var res = JSON.parse(JSON.stringify(jsonData));
console.log(res);//
}
});
Hopefully this may help.
You shouldn't need to parse it, if your server is providing json.
You can use dataType though to force jQuery to use a particular type:
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
console.log(response);
}
});
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);});