How do I alert my json results? - javascript

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"

Related

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

Getting json array to create products index problems using Php, json, JS and JSON

Having a few problems creating a products index.
It looks like you're pushing down html as well in the products.php page. Make sure the output of the php that you're retrieving from only returns JSON.
Also, check the syntax on your script:
$.get({
type: "GET",
url: "products2.php",
data: 'id=' + userid,
dataType: "json",
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("decription").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
document.getElementById("stock").innerHTML = data[3];
}
});
You were using $rows but attempting to access data. Adding a simple console.log(data); in the success function will dump the results to the console in chrome/firefox so you can see what is being returned. (Be sure to check the network tab as well, as it can give you some tips as to why the data isn't being properly fetched.)
I've done something similar and this worked fine for me:
<?php
$array['status'] = 0;
...
echo json_encode($array);
Populate the array with whatever you need.
And then:
$.ajax({
type: "type",
url: "url",
data: {
data: data
},
success: function (data) {
console.log(data.status);
}
});

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/

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