jQuery. Assign JSON as a result to a variable - javascript

I use this helper function to receive JSON results for my requests:
function getData(url) {
$.get(url,
function(data) {
response = data;
return response;
}, 'application/json');
}
I give it some string as a part of url from my web application, like '/api/getusers', so it looks like getData('/api/getusers'). Now I need that string result containing JSON data that I receive from the url to be assigned to my variable, so it would look like this: var result = getData('/api/getusers'). Then I will process this JSON data. The problem is with the returning the response variable. It's undefined. Thanks!

try this
function getData(url) {
var data;
$.ajax({
async: false, //thats the trick
url: 'http://www.example.com',
dataType: 'json',
success: function(response){
data = response;
}
});
return data;
}

It's an asynchronous operation, meaning that function(data) { ... } runs later when the response from the server is available, long after you returned from getData(). Instead, kick off whatever you need from that function, for example:
function getData(url, callback) {
$.get(url, callback, 'application/json');
}
Then when you're calling it, pass in a function or reference to a function that uses the response, like this:
getData("myPage.php", function(data) {
alert("The data returned was: " + data);
});

Use $.ajax
$.ajax({
url: 'http://www.example.com',
dataType: 'json',
success: function(data){
alert(data.Id);
}
});

Related

Ajax callback to check variables as global

I'm trying to implement a function that after consulting a service brings the variables as global.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
callback(data);
}
});
}
and I'm trying to call like this:
ajax_test("str", function(url) {
//do something with url
console.log(url);
});
Now, if I just call ajax_test() it returns an error, saying that callback is not a function.
How would be the best way to simply call the function and get the results to use global variables?
Edit:
I think a good question is: what is a good alternative to async: false? How is the best way to implement synchronous callback?
Edit 2:
For now, I'm using $.post() with $.ajaxSetup({async: false}); and it works how I expect. Still looking a way I could use with a callback.
Have to set the scope inside the success method. Adding the following should work.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
this.callback(data);
}.bind(this)
});
}
As an argument of the ajax_test function, callback is in the scope of the ajax_test function definition and can be called anywhere there, particularly in the successcase. Note that calling ajax_test() without arguments will as expected make your code call a function that does not exist, named callback.
The following sends an Ajax request to the jsFiddle echo service (both examples of callback as anonymous or global function are given in the jsFiddle), and works properly :
function ajax_test(str1, callback){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars':$('form').serialize(),
'test':123
})
},
success: function(data, status, xhr){
callback(data);
}
});
}
ajax_test("unusedString", function(data){
console.log("Callback (echo from jsFiddle called), data :", data);
});
Can you check that the webservice you're calling returns successfully ? Here is the jsFiddle, I hope you can adapt it to your need :
https://jsfiddle.net/dyjjv3o0
UPDATE: similar code using an object
function ajax_test(str1) {
this.JSONFromAjax = null;
var self = this;
function callback(data) {
console.log("Hello, data :", data);
console.log("Hello, this :", this);
$("#callbackResultId").append("<p>Anonymous function : " + JSON.stringify(data) + "</p>");
this.JSONFromAjax = JSON.stringify(data);
}
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars': $('form').serialize(),
'test': 123
})
},
success: function(data, status, xhr) {
console.log("Success ajax");
// 'self' is the object, force callback to use 'self' as 'this' internally.
// We cannot use 'this' directly here as it refers to the 'ajax' object provided by jQuery
callback.call(self, data);
}
});
}
var obj = new ajax_test("unusedString");
// Right after the creation, Ajax request did not complete
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
setTimeout(function(){
// Ajax request completed, obj has been updated
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
}, 2000)
You cannot expect the Ajax request to complete immediately (don't know how it behaves with async: false though, this is why you need to wait for a while before getting the actual response.
Updated jsFiddle here : http://jsfiddle.net/jjt39mg3
Hope this helps!

How to pass a variable from ajax to nested ajax

I'm sending ajax call and getting an answer that I need from the first ajax then I want to pass my result to my nested ajax, my var (result) is null in the nested ajax/settimeout fun, can I pass it ? Am I missing something ?
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
contentType:'json' ,
dataType:'text',
success: function (result) {
alert(result);**-> is fine - not null**.
// a or result is null when I hit the getCurrentDoc- function althought I get the data I need from getCustomerGuidId function
var a = result;-> tried to pass it to a new var..IDK.. I
thought it will help... it didn't.
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,-> here it's null
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});
You can try something like this will help to pass value to nested ajax call
function test(){
var myText = 'Hello all !!';
$.get({
//used the jsonplaceholder url for testing
'url':'https://jsonplaceholder.typicode.com/posts/1',
'method':'GET',
success: function (data) {
//updating value of myText
myText = 'welcome';
$.post({
'url':'https://jsonplaceholder.typicode.com/posts',
'method':'POST',
//data.title is the return value from get request to the post request
'data':{'title':data.title},
'success':function (data) {
alert(data.title +'\n' + myText);//your code here ...
}
});
}
});
}
An old question and you've likely moved on, but there's still no accepted answer.
Your setTimeout takes an anonymous function, so you are losing your binding; if you have to use a Timeout for some reason, you need to add .bind(this) to your setTimeout call (see below)
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,
success: function (data) {
}
});
}.bind(this), 2000);
At a guess you're using a Timeout because you want to ensure that your promise (i.e. the first ajax call) is resolving prior to making the nested call.
If that's your intention, you can actually scrap setTimeout completely as you have the nested call in the first ajax success call, which only runs once the promise has been resolved (providing there isn't an error; if so, jQuery would call error rather than success)
Removing setTimeout means you won't lose your binding, and a should still be result (hopefully a is an object, otherwise your second call is also going to experience issues...)
Lastly, after overcoming the binding issue you wouldn't need var a = result; you should be able to pass result directly to your nested ajax call.
Good luck!
In the nested ajax you send a as a param name, not as a param value.
So you can try the following (change param to actual param name which your server expects):
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
dataType:'text',
success: function (result) {
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
data: {param: result},
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});

Get parameter from JSON

In data from server I get the following JSON:
{
"response": {
"upload_url": "http:\/\/cs9458.vk.com\/upload.php?act=do_add&mid=6299927&aid=-14&gid=0&hash=73e525a1e2f4e6a0f5fb4c171d0fa3e5&rhash=bb38f2754c32af9252326317491a2c31&swfupload=1&api=1&wallphoto=1",
"aid": -14,
"mid": 6299927
}
}
I need to get upload_url. I'm doing:
function (data) {
var arrg = JSON.parse(data);
alert(data.upload_url);
});
but it doesn't work (alert doesn't show).
How do I get parameter upload_url?
It looks like you need to access arrg, not data. Also you need to access the 'response' key first.
function (data) {
var arrg = JSON.parse(data);
alert( arrg.response.upload_url);
}
There are several correct answers here, but there is one trigger that decides how you should handle your returned data.
When you use an ajax request and use JSON data format, you can handle the data in two ways.
treat your data as JSON when it returns
configure your ajax call for JSON by adding a dataType
See the following examples:
returned data string:
{"color1":"green","color2":"red","color3":"blue"}
ajax call without dataType:
$.ajax({
method: "post",
url: "ajax.php",
data: data,
success: function (response) {
var data = JSON.parse(response);
console.log(data.color1); // renders green
// do stuff
}
});
ajax call with dataType:
$.ajax({
method: "post",
url: "ajax.php",
dataType: "json", // added dataType
data: data,
success: function (response) {
console.log(response.color1); // renders green
// do stuff
}
});
In your case you probably used JSON.parse() when the call was already configured for JSON. Hope this makes things clear.
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
Your code has a small error. try:
function (data) {
var arrg = JSON.parse(data);
alert(arrg.response.upload_url);
});

Piping Value: Ajax + JQuery

I have a function in which I execute an ajax request and wait till I get a response and return a value but the value returned is undefined. What is wrong?
function GetVMData(url_s){
return $.ajax({
url: url_s,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
}
}).pipe(function(data) { return data[4]; });
}
If I print the value of data[4] within the ajax callback it prints the right value, therefore i know the request is going through but when I try this:
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord)
the value of cord is wrong.
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord)
This code runs asynchronously. So you need to perform everything in the callback, like:
GetVMData(url).done(function(cpu_USG) {
alert(cpu_USG);
});
Here:
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord);
cord contains object, not the value. And by the way, you don't know where ajax calling will be finished, so you should be familiar with idea of callbacks..
As an example:
function makeRequest(url, callback) {
$.ajax({
url: url,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
},
success: callback
});
}
var do_something = function (data) {
alert(data[4]);
};
cord = makeRequest(url, do_something);

function dont see JSON object (java script, jQuery)

function json (url){
$.getJSON(url, function(data) {
return data;
})
}
this function don't see "data"
function MakeAlert(){
data = json('action.php');
window.alert(data.name);
}
this work:
function json (url){
$.getJSON(url, function(data) {
window.alert(data.name);
})
}
That's because the $.getJSON is asynchronous. It sends the request and returns immediately. Once the server responds (which might be a few seconds later) it invokes the success callback and that's why the data is accessible only inside this callback.
If you want to block the caller you could send a synchronous request (note that this might freeze the UI while the request is executing which defeats the whole purpose of AJAX):
function json(url) {
var result = null;
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
function json (url){
$.getJSON(url, function(data) {
return data;
})
}
You cannot use return here. You would return data the to anonymous closure function.
Your best shot is to use a callback function which should be applied when the getJSON success handler is executed.
function json (url, cb){
$.getJSON(url, function(data) {
cb.apply(null, [data]);
})
}
usage
json('action.php', function(data){
alert(data);
});

Categories