Retrieve all 'data' properties of json data with ajax - javascript

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

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

To get value from Json Object

In the below code i am passing json object it is in the format {"Table":[{"FAMin":0,"FAMax":40,"FAGrade":"C"}]}.How to get the value from it i tried the below code it results undefined .Pls help me to overcome this issue.
function UpdateGrade(GradeID) {
alert(GradeID);
$.ajax({
type: "POST", //HTTP method
url: "MarkorGradeSettings.aspx/GetGrade", //page/method name
data: "{'GradeID':'" + GradeID + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);// I get values
var parsedJson = jQuery.parseJSON(msg.d);
alert(parsedJson.Table.FAMin);//undefined
//handle the callback to handle response
if (msg != 'error') {
//$('#messages').addClass('alert alert-success').text(response);
// OP requested to close the modal
$('#myModal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
//Now add the new items to the dropdown.
}
});
}
Table is an array but you are treating as an object
Try:
alert(msg.d.Table[0].FAMin)
Also as noted in comments there is no need to call jQuery.parseJSON when dataType:'json' is set. jQuery will parse the response internally and return object/array in callback
It looks like you missed that the data under Table is an array.
This should at least fix this particular case:
alert(parsedJson.Table[0].FAMin);

Grabbing JSON data with AJAX

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

Assign ajax request result to variable in the jquery function

I am trying to assign value I receive from the php file to the jquery variable. The php file runs a loop and echos out a value. I am trying then to store the value in the jquery variable but I am getting NaN result back. How can I assign the value echoed from the php file into the variable in the jquery function?
var increment;
event.preventDefault();
$.ajax({
type: 'POST',
url: 'increment.php',
data: $(this).serialize(),
dataType: 'text',
success: function (data) {
//console.log(data);
data = increment;
}
});
You should be using
increment = data;
instead of
data = increment;
Also one more thing to note here is the request nature. Since the ajax request is asynchronous accessing the variable outside might show unexpected result. You have to access the variable once the ajax request is successful (inside success callback).
do like so,you should assign data recieved to increment var:
var increment;
event.preventDefault();
$.ajax({
type: 'POST',
url: 'increment.php',
data: $(this).serialize(),
dataType: 'text',
success: function (data) {
//console.log(data);
increment = data ;
}
});

Reusing 'data' passed in the jquery-ajax call

I'm using jquery's .ajax() method on a button click.
I wanted to know if there a way in whcih I can use the data that I passed in the data-part of the AJAX call in my success() function.
This is my code,
$.ajax({
url: //my URL here..
type: 'POST',
data:{
projDets : projDetailsArray,
},
datatype:'html',
error: function(){
alert('Error loading Project Information');
},
success: function(html){
//I wanted to re-use 'projDets' that I'm passing in the
//'data' part of my code..
}
});
Any help will be appreciated.
Thanks
You could wrap the $.ajax parameter in a closure, set up the "data" value as a local variable, and then reference it both for the "data" value and inside the "success" function:
$.ajax(function() {
var data = {
projDets: projDetailArray
// ...
};
return {
url: // your URL here..
type: 'POST',
data: data,
datatype:'html',
error: function(){
alert('Error loading Project Information');
},
success: function(html){
// just reference "data" here!
}
};
}());
Pritish - a quick and dirty way would be to store the json array in a jquery .data() object and then retrieve it as required.
1st, set the data: element to a named array:
// set 'outside' of the $ajax call
var projDetailsData = {projDets : projDetailsArray};
// now store it in a div data object
$("#targetDiv").data("myparams", projDetailsData);
// the data part of the $ajax call
data: projDetailsData,
to retrieve it again:
// get the value stored and call the $ajax method again with it
var projDetailsDataCopy = $("#targetDiv").data("myparams");
worth a try maybe!!
jim
[edit] - also, you could of course store the array in a module level vaiable -yuk!! :)

Categories

Resources