Retrieve POST JSON response - javascript

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);
}
});

Related

Cant browse through Dictionary in Javascript

I am using Ajax to send data and as a success, it sends some data back.
$.ajax({
method: "POST",
url: "{% url 'upload-prop-images' %}",
processData: false,
contentType: false,
mimeType: "multipart/form-data",
data: fileData,
success: function (data) {
console.log(data);
console.log(data.newCard);
console.log(data.newCard.prop_name);
}
}
})
views.py :
def uploadPropImages(request):
prop_obj = list(Property.objects.filter(user=request.user).values())
new_card = {}
for obj in prop_obj:
if obj['prop_name'] == prop_name:
new_card['prop_name'] = obj['prop_name']
new_card['prop_address'] = obj['prop_address']
new_card['prop_type'] = obj['prop_type']
new_card['prop_images'] = '/media/' + obj['prop_images']
return JsonResponse({'status': 'Done', 'newCard': new_card})
In the first code block where success: function(data) {}, console.log(data) prints the data I am sending, that is {'status': 'Done', 'newCard': new_card}, but when I print, console.log(data.status) or console.log(data.newCard), I get undefined value. I cant understand why it prints undefined because I used AJAX may times earlier and It seem to work. It is how we can browser through the value of a dictionary in JAVASCRIPT, which in PYTHON is print(data['status']). Is the error anything related to the keys defined inside the AJAX function: processData, mimeType, contentType?
you need to call this
$.parseJSON();
Like this
success: function (response) {
var data= $.parseJSON(response);
console.log(data);
console.log(data.newCard);
console.log(data.newCard.prop_name);
}

Make an API call inside of another API call?

I basically need to combine data from two different API calls. Here is what I have right now:
var url= "https://website.com/api.json";
$.ajax({
url: url,
type: "GET",
dataType: 'json',
headers: {'X-API-Key': 'xxxxxx'},
success: function(data){
var api = data.results[0].api;
for (var i=0;i<api.length;++i)
var api2url = api[i].api2url;
{
$('tbody').append('<tr><td>'+api[i].thing+'</td></tr>');
}
}
});
The above works.
The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:
$('tbody').append('<tr><td>+api[i].thing+'</td></tr>');
Easiest way forward would be to make that API call in the success callback of your first API call. Might look something like:
var url= "https://website.com/api.json";
$.ajax({
url: url,
type: "GET",
dataType: 'json',
headers: {'X-API-Key': 'xxxxxx'},
success: function(data){
// now you have closure over results from api call one
$.ajax({
url: 'apiURL2', // or something
type: "GET",
dataType: 'json',
headers: {'X-API-Key': data.results.apiKey // or something },
success: function(moreData){
var api = data.results[0].api;
for (var i=0;i<api.length;++i)
{
$('tbody').append('<tr><td>'+api[i].thing+ moreData.thing'</td></tr>');
}
}
})
});
const getDataFromApi = (endpoint) => {
return new Promise((resolve, reject) => {
$.ajax({
url: url,
type: "GET",
dataType: 'json',
headers: {'X-API-Key': 'xxxxxx'},
success: (data) => {
return resolve(data);
}
});
});
};
Promise.all([
return getDataFromApi('https://website.com/api.json');
]).then((data) => {
return Promise.all([
data,
getDataFromApi('https://website.com/api2.json')
]);
// here your business logic (for loop in your code)
}).then((data) => { // with bluebird it's easier use spread
const dataApi1 = data[0];
const dataApi2 = data[1];
})
.catch((err) => {
console.error(err);
});
You can make the second ajax call on the success of the first. Then perform your DOM updates as needed. But the idea is to run the second ajax call once the first has completed and was successful.
function callApi2(aip1) {
$.ajax({
//params for the call
url: api1.api2url,
success: function(data) {
var api2 = data.results[0].api; // or whatever the property is
$('tbody').append('<tr><td>'+api1.thing+'</td></tr>');
},
});
}
var url= "https://website.com/api.json";
$.ajax({
url: url,
type: "GET",
dataType: 'json',
headers: {'X-API-Key': 'xxxxxx'},
success: function(data){
var api1 = data.results[0].api;
for (var i=0; i<api1.length;++i){
callApi2(api1[i]);
}
}
});

How to address data from external url?

Now I have that code:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Factory%20New%29",
data: {},
dataType: "jsonp",
crossDomain: true,
success: function(data) {
console.log(data)
} });
});
and get this error:
Uncaught SyntaxError: Unexpected token :
I can see the right response from the url in my console and tried different dataTypes. What could be wrong?
Please try this. On my end this works.
$.ajax({
type: "POST",
url: "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Factory%20New%29",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// an example of using result
var myVar1 = result.lowest_price;
var myVar2 = result.median_price;
var myVar3 = result.success;
var myVar4 = result.volume;
alert(result.success);
},
error: function (result) {
},
fail: function (arg1, arg2, arg3) {
}
});

Returning values from Get function of Jquery

Hi I am trying to get a return value from a get function from a jquery Get request on success.
I have tried many ways already but with no success. Two forms which i have tries are:
1)
GetResultOutput = function () {
var outPut = "No Data Found";
var test = test();
return test["outPut"];
}
test = function()
{
outPut = "No Data Found";
**return** $.ajax({
type: "GET",
url: serviceUrl,
dataType: "xml",
success: function (xml) {
outPut = "done";
}
});
}
2)
GetResultOutput = function () {
outPut = "No Data Found";
$.ajax({
type: "GET",
url: serviceUrl,
dataType: "xml",
success: function (xml) {
outPut = "done";
}
});
return outPut;
}
But both of them is not giving me any result..
2nd one outputs me as no data found. and 1st one which is preferred one when googled...results as undefined
Instead of trying to get the output and then process it like:
var output = GetResultOutput();
process(output);
You could pass process as a callback like:
var GetResultOutput = function (callback) {
$.ajax({
type: "GET",
url: serviceUrl,
dataType: "xml",
success: function (xml) {
callback(xml);
}
});
};
// usage:
GetResultOutput(process);
You can also make your ajax call synchronous by using:
$.ajax({
type: "GET",
url: serviceUrl,
async: false,
dataType: "xml",
success: function (xml) {
outPut = "done";
}
});
Ajax request are asynchronous, which means you cannot immediately "return" data from the call. That is why all forms of $.ajax take one or more callbacks to be called when data is received, or an error occurs etc.
Which means your method must look like:
GetResultOutput = function (callback) {
$.ajax({
type: "GET",
url: serviceUrl,
dataType: "xml",
success: callback
});
}
with callback looking like:
function callback(xml)
{
console.log('done: ' + xml);
}

How do I extract a foursquare access_token saved to DOM as a link so I can use it for API calls?

The code looks like:
var jsonUrl = url +"&callback=?";
// $("#getJSON").click(function(){
$.getJSON(
jsonUrl,
{
dataType: "JSONP"
},
function(json){ var items = [];
var items = JSON.parse(json);
alert(items);
$("#result").html("<h3>" + result + "</h3>");
}
);
also tried
$.ajax({
type: 'GET',
url: url,
key: $('#access_token'),
dataType: 'jsonp',
success: function(data){ $('.result').html(data);
processData: false,
alert(jQuery.data( document.access_token ));
alert(data[0].text);},
error: function() {
console.log('Uh Oh!'); },
jsonp:'onJSONPLoad'
});
Essentially if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
// do something with your access_token ?
Did i understand your question right? You can assign the the access_token to a variable and then do what you want with it in your code, can't you?
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
}
});

Categories