To get value from Json Object - javascript

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

Related

Jquery.ajax GET not ending parameters

I am creating a UI for a content production area on a company intranet. I created the middleware API in a previous project. This is my first time using RESTful methods (and I'm fairly new to Javascript and jquery in the first place)
When I call my debugging local api from the jquery.ajax the JSON object is not being passed properly on my GET method.
In the C# API
[ActionName("THING")]
[HttpGet()]
public string GetThing(object json)
{
GetData getData;
if (json == null)
return null;
else if (json is string && (json as string).StartsWith("{"))
getData = JsonConvert.DeserializeObject<GetData>(json as string);
else
return null;
ItemReturn retVAl = new ItemReturn();
[logic to use JSON]
return retVal;
in the web page
loadThings: function (thingNumber, showBool) {
showBool = (showBool === true);
$.ajax({
type: "GET",
dataType: "json",
data: '{ "GetData" : {"ThingNumber":"' + thingNumber + '","Show": ' + showBool + '}}',
url: "http://localhost:11422/api/THING/THING/GetThing",
contentType: "application/json; charset=utf-8",
success: function (result) {
[logic to display things]
}
I can hit my breakPoint in GetThing fine, have it all working, but I can't seem to figure out why the object (json) in my overload is coming in null. I know it's something in the javascript, my unit tests work fine and my JavaScript is getting me to my breakpoint in the method, I just need to overload JSON object to actually be passed in
UPDATE
It is on the api side. I changed the overload of GetThing from (object json) to ([FromUri()] object json). This fixed the immediate issue but it is currently just translating the JSON object into a blank object
++Note: I had to change my post method overload to [FromBody()] rather than [FromUri()], I am yet to update the DELETE method to see which one that uses
So problem no1, you can't do this with GET. Two options
Use POST
stringify and use GET
1) So this is how you use POST
Fix your ajax request as follows:
$.ajax({
type: "POST",
dataType: "json",
data: { "GetData" : {"ThingNumber": thingNumber ,"Show": showBool }}, // JS object not string
url: "http://localhost:11422/api/THING/THING/GetThing",
contentType: "application/json; charset=utf-8",
Please read the $.ajax post documentation for instructions https://api.jquery.com/jquery.post/
2) Use GET
var obj = JSON.stringify({ "GetData" : {"ThingNumber": thingNumber ,"Show": showBool }}),
url = "http://localhost:11422/api/THING/THING/GetThing?json=" + encodeURIComponent(obj);
$.ajax({
type: "GET",
dataType: "json",
url: url, // Here we encode the obj for server
contentType: "application/json; charset=utf-8",
If you use this method you must change your controller to get json parameter as String and then parse it to JSON using your library of choice. How can I parse JSON with C#?
Could you try adding in the ajax settings: traditional:true,?

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

Display search results from API

Hello there I'm trying to create an app to search for recipes. I've tried using the Yummly API and BigOven api, but I can't get either to work.
here is the code i have for bigOven. I can't get any search results to appear in the "results".
$(function() {
$('#searchform').submit(function() {
var searchterms = $("#searchterms").val();
// call our search twitter function
getResultsFromYouTube(searchterms);
return false;
});
});
function getResultsFromYouTube (searchterms) {
var apiKey = "dvxveCJB1QugC806d29k1cE6x23Nt64O";
var titleKeyword = "lasagna";
var url = "http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="+ searchterms + "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
alert('success');
console.log(data);
$("#results").html(data);
}
});
}
Can anyone give me instructions on how to do this?? Thank you very much.
The API is returning JSON data, not HTML. I checked the API docs, and JSONP isn't necessary.
However, when you run this code:
$('#results').html(data);
Your code is going to just put the JSON into your HTML, and that isn't going to get displayed properly. You didn't say whether console.log(data) outputs the data correctly, but I'll assume it is.
So, you'll need to transform your JSON into HTML. You can do that programmatically, or you can use a templating language. There are a number of options, including underscore, jquery, mustache and handlebars.
I recommend handlebars, but it's not a straightforward bit of code to add (the main difficulty will be loading your template, or including it in your build).
http://handlebarsjs.com/
It would depend on you which key and values you have to show to your user's and in which manner... For ex. there is even an image link, you could either show that image to your user's or could just show them the image link...
Simple <p> structure of all the key's with there value's
jQuery
$.each(data.Results, function (key, value) {
$.each(value, function (key, value) {
$("#result").append('<p>Key:-' + key + ' Value:-' + value + '</p>');
});
$("#result").append('<hr/>');
});
Your ajax is working, you just need to parse the results. To get you started:
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
// Parse the data:
var resultsString = "";
for (var i in data.Results){
console.log( data.Results[i] );
resultsString+= "<div>"+data.Results[i].Title+ " ("+data.Results[i].Cuisine+")</div>";
}
$("#results").html(resultsString);
// If you want to see the raw JSON displayed on the webpage, use this instead:
//$("#results").html( JSON.stringify(data) );
}
});
I had created a little recursive function that iterates through JSON and spits out all of the values (I subbed my output for yours in the else condition) -
function propertyTest(currentObject, key) {
for (var property in currentObject) {
if (typeof currentObject[property] === "object") {
propertyTest(currentObject[property], property);
} else {
$('#results').append(property + ' -- ' + currentObject[property] + '<br />');
}
}
}
Then I called it within your AJAX success -
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
console.log(data);
propertyTest(data); // called the function
}
});
It spits out all of the data in the JSON as seen here - http://jsfiddle.net/jayblanchard/2E9jb/3/

How do I alert my json results?

I get these results via php to alert in my ajax alert
[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}]
How do I do $('#divid').html(message); ?
I want only specified value from the json array.
Here is the code
function showMessage(id){
var dataString = 'id=' + id;
$.ajax(
{
type: "POST",
url: "/inbox/instshow",
data: dataString,
success: function(results)
{
if(results == "error")
{
alert('An error occurred, please try again later. Email us with the issue if it persists.');
}
if(results != "notallowed" && results != "error" && results != "login")
{
alert(results);
alert(results[0].message);
}
}
});
}
data = [{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}]
$('#divid').html(data[0].message);
DEMO
You might have to parse a JSON string using jQuery.parseJSON.
// results is your JSON string from the request
data = jQuery.parseJSON(results);
$('#divid').html(data[0].message);
If you ajax you should include:
dataType: 'json'
code
$.ajax(
{
type: "POST",
url: "/inbox/instshow",
data: dataString,
dataType: 'json', // here
success: function(results) {
}
.........
Including this jQuery will parse the returned data as JSON for you automatically (don't need any manual parsing effort) and you'll get your result that you're trying now.
use JSON.stringify() function
var data=[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}] ;
alert(JSON.stringify(data));
Here's your data broken down by levels:
[
{
"message_id":"3",
"box":"0",
"from_id":"3",
"to_id":"1",
"title":"Hello sir!",
"message":"how are you?",
"sender_ip":"",
"date_sent":"",
"status":"0"
}
]
You would use data[0].message because the first level indicates an array, hence the need of [0] to reference the first and only element, and the second is an object, which properties can be accessed by the object.member syntax.
for debugging purposes
console.log(data, data.message, "whatever")
You need to open firebug or safari's inspector and look in the "console"

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