Grabbing JSON data with AJAX - javascript

I have a JSON URL that I need to grab the variables from and use them as jQuery stings. I've tried several different approaches and all of them are unsuccessful.
Approach 1
$.getJSON('http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get', function(data) {
alert(JSON.stringify(data))
});
Resilt
I receive an 200 OK message, but I do not get any data returned.
Approach 2
$.ajax({
url:"http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType:'jsonp',
success:function(data){
var obj = jQuery.parseJSON(data);
alert(obj.title);
}
});
Result
I receive on 200 OK but the obj value is NULL
Approach 3
$.getJSON("http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",function(ajaxresult){
window.artist = ajaxresult.track.artist;
});
Resilt
I receive an 200 OK message, but I do not get any data returned.

You didn't look with attention at the JSON object returned by the service.
What you're looking for is the data property of the returned object which is an array.
Something like this do work :
$.ajax({
url: "http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType: 'jsonp',
success: function (data) {
console.log(arguments);
alert(data.data[0].title);
}
});
JSFiddle to demo

Related

Print JSON string from URL

I'm using ajax to parse JSON data from a URL. I need to capture the parsed array into a variable. How would I go about this? Thanks
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also don't need to pass any data, as you're performing a GET request.
Hope this helps! :)
So I guess you are not sure about the ajax call, so lets break it..
Ajax call is a simply method to make a request to remote resource (Get/post/put...) the type of request (GET/POST) depends upon your need.
so if you have an endpoint that return simply data as in your case a simple get/post request is sufficient.
You can send addition data with request to get the data from endpoint (say id of resource (say person) whose other fields you want to get like name, age, address).
here is link for ajax request in jQuery
here is jQuery parse json parse json in jQuery
So for example:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can try something like: -
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});

Retrieve all 'data' properties of json data with ajax

I'm trying to figure out how to access to all the data from a json provided by movie database api, but I don't understand how to retrieve it.
The console log give me an "data is not defined" error.
So here is my code:
$(document).ready (function(){
var key = 'api key provided';
$.ajax({
type: 'GET',
url : 'http://api.themoviedb.org/3/search/movie'+key+'&query=Minions',
dataType: 'jsonp',
data: {
format:'json'
},
error: $('#result').append("errore"),
success: function(data){$('#result').append("ok")}
});
var jsonData=data.results.original_title;
//this give me a data is not provided
});
Here a portion of json:
Let's assume that I only want to access to the release_date propriety, how can I achieve this?
data not is defined out of $.ajax() closure, you need to move the code to success handler like, then loop through the JSON data.results.
success: function(data){
$('#result').append("ok");
console.log(data);
$.each(data.results, function(i, result) {
console.log('Release date is' + result.release_date);
});
}
alternatively, you can define a variable, then update that variable in success handler of $.ajax()
var ajaxResponse;
$.ajax({
/* skipped lines*/
success: function(data){
ajaxResponse = data
}
});

Can I use jquery ajax response for Autocomplete

It's 3am. I've been banging my head against the wall for hours on this and just don't get it.
I'm trying to use jQuery autocomplete with the source data coming from an ajax request.
Ajax seems to be working great, but I can't seem to use the response for the source data.
Anonymous function fetches data on ready. Success calls test(response) passing the data to the function with autocomplete. The response looks exactly like the sample code. And when I paste my response from the console it works perfectly. But it will not let me use the variable 'albums' for the source.
$(function(){
$.ajax({
dataType: 'text',
type: 'POST',
url: '/albums/fetch_albums',
success: function(response){
console.log(response); // logs ["Italy","Hawaii"] -as expected
test(response);
}
});
});
function test(data){
var albums = data;
console.log(albums); // logs ["Italy","Hawaii"] - as expected
console.log(typeof albums); //logs string - as expected
$('#autocomplete').autocomplete({
source: albums, //this is what I want... errors out.
//source: ["Italy","Hawaii"] // pasted response if un-commented works fine.
});
}
Here is the error message.
GET http://journal.localhost.com/[%22Italy%22,%22Hawaii%22]?term=h 403 (Forbidden)jquery-2.1.1.min.js:4 n.ajaxTransport.k.cors.a.crossDomain.sendjquery-2.1.1.min.js:4 n.extend.ajaxjquery-ui.min.js:7 e.widget._initSource.e.isArray.string.options.source.sourcejquery-ui.min.js:7 e.widget._searchjquery-ui.min.js:6 (anonymous function)jquery-ui.min.js:7 e.widget.searchjquery-ui.min.js:6 (anonymous function)jquery-ui.min.js:7 (anonymous function)jquery-ui.min.js:6 i
There has to be a way to fetch data from the database and feed it to this function.
Help me Obiwan!
$(function(){
$.ajax({
dataType: 'text',
type: 'POST',
url: '/albums/fetch_albums',
success: function(response){
console.log(response); // logs ["Italy","Hawaii"] -as expected
var arrResponse = JSON.parse(response); //convert json object to array
test(arrResponse);
}
});
});

JSON Data returned from Ajax on Safari is converted into a javascript list

This is something I recently found out, I have the following piece of code in JS:
$.ajax({
type: 'POST',
url: '/requestHandle',
data: data,
success: function(data) {
var places = JSON.parse(data);
// do something
},
error: function(data) {
// do something else
}
});
The data returned from my backend is indeed in JSON format, and var places = JSON.parse(data); this line works perfectly in Chrome and Firefox, it parses my JSON data into a JS list; however, in Safari, var places = JSON.parse(data); gives me error, because data is already a JS list. Instead of doing var places = JSON.parse(data), just changing to var places = data solved the error, I am wondering why it is converted automatically?
Thanks in advance
Your best solution would be to tell jQuery that the response is json so that you will always receive it as js object
$.ajax({
type: 'POST',
url: '/requestHandle',
data: data,
success: function(obj) {
// do something
},
error: function(data) {
// do something else
},
dataType: 'json' // reponse is json so it will always be pre-parsed
});

Jquery JSON response handling

I have an ajax query written in jQuery that is returning valid JSON in this format
$.ajax({
type : 'POST',
url : 'ajax/job/getActiveJobs.php',
success : function(data){
if(data[''] === true){
alert('json decoded');
}
$('#waiting').hide(500);
$('#tableData').html(data['content']);
$('#message').removeClass().addClass((data.error === true)
?'error':'success').text(data.msg);
if(data.error === true)
$('#message')
},
error : function(XMLHttpRequest, textStatus, errorThrown){
$('#waiting').hide(500);
$('#message').removeClass().addClass('error').html(data.msg);
} })
I take it this is not correct as it is not displaying the data, if I use
$('#mydiv').html(data);
I get all of the data back and displayed.
any help is really appreciated
Set the dataType to be json so jQuery will convert the JSON to a JavaScript Object.
Alternatively, use getJSON() or send the application/json mime type.
Either set dataType to json or use var json = JSON.parse(data) to do it manually.
EDIT:
I'm adding this because somebody else suggested eval, don't do this because it gets passed straight into a JSON object without any sanitation first, allowing scripts to get passed leading straight into an XSS vulnerability.
The data is the Json so you will want to do this:
success: function (data) {
var newobject = eval(data);
alert(newobject.msg);
}
or do this:
$ajax({
url: url,
data: {},
dataType: "json",
success: function (newObject) {
alert(newobject.msg);
}
});

Categories

Resources