Parsing json in jquery - javascript

I have a php file somejson.php that echos a json encoded array
{"jsonone":"first json","jsontwo":"second json"}
I'm trying to access the response with jquery ajax to use this data outside the score of the ajax call. It keeps giving me all kinds of object(Object) or undefined errors.
I'm guessing it's something as easy as wrong syntax, but it's bugging me I thought I'd ask
var mydata = {};
$.ajax({
url: 'somejson.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json;
mydata[jsonone] = json.jsonone;
mydata[jsontwo] = json.jsontwo;
alert(json[jsonone] . json[jsontwo]);
alert(mydata[jsontwo] . mydata[jsontwo]);
}
});
//later will do some stuff with mydata jsonone and jsontwo
What are all the things I'm doing wrong here?

Yep, simple syntax errors :-)
You need to put quotes around your hash keys and use the '+' operator to concatenate strings:
var mydata = {};
$.ajax({
url: 'somejson.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json;
mydata['jsonone'] = json.jsonone;
mydata['jsontwo'] = json.jsontwo;
alert(json['jsonone'] + json['jsontwo']);
alert(mydata['jsontwo'] + mydata['jsontwo']);
}
});

I think your problem comes from the dots in your alert statements.
String concatenation in javascript is done using + not . like in php.
alert(json['jsonone'] + json['jsontwo']);
alert(mydata['jsontwo'] + mydata['jsontwo']);
Also, the array indexes should be strings (enclose in single or double quotes).

Related

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON

I need to append this div to another div , but it give me this error :
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
the JSON data
This is my javascript code:
var str = {'message': message,'text': text};
$.ajax({
type: "POST",
url: "api/reply",
data: str,
dataType: "json",
cache: false,
success: function(response)
{
var respons = jQuery.parseJSON(response);
var type = respons.status
if (type == 'success') {
$("<div></div>").html(respons.message).appendTo("#messages");
}
else
{
toastr.error(respons.message)
}
}
})
Simply change
var respons = jQuery.parseJSON(response);
to
var respons = response;
Explanation:
If the configuration of your AJAX call is having dataType: json you'll get a JavaScript object so it's no longer necessary to use JSON.parse().
This is a hackish and unorthodox way of parsing JSON, but if you still want to use JSON.parse() from an AJAX call or simply on JSON that is already parsed and isn't a string, you can use JSON.stringify() inside it:
var respons = JSON.parse(JSON.stringify(response));
Problem is you're not parsing a string, you're parsing an already parsed object.
the values in your object seem to be undefined.
change
var str = {'message': message,'text': text}; to
var str = {message: 'message',text: 'text'};

I mess up JSON object, arrays and strings

So i´m, trying send data from php to js.
PHP
$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);
JS
balkTypesData = {}; //Outside Ajaxcall
success: function(result){
balkTypesData = result;
Console.log(balkTypesData);
}
Console
[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]
Now, i´d like to search my Json object?!
I´d like to find "viktM" for "typ:Bas 200*600"
//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
if (balkTypesData[i][searchField] == searchVal) {
weigth = balkTypesData[i]['viktM'];
console.log(weigth);
}
}
First of all, it seams that i cannot use .lengton "balkTypsData". it gives me 410 hits. Must be all characters?
Second, i cannot find how to access part of my object.
If i use: console.log(balkTypesData[i][searchField]);
I get: "Undefined"
I have also tried to remove the "[i].
So what am i missing?
Be gentle i´m still learning.
Take a look at $.parseJSON() (jQuery) or JSON.parse() (vanilla):
With jQuery
success: function(result){
balkTypesData = $.parseJSON(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
Without jQuery
success: function(result){
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
When you receive the data from your AJAX request it's not JSON, just a string.
The length result that you're getting is the length of the string, not the amount of elements within the array.
Furthermore you're setting $balkTypes[] which means that you're trying to add 1 entry in the array of $balkTypes however $stmt->fetchAll(); also returns an array so you now have a nested array which is not needed.
In your PHP file change
$balkTypes[] = $stmt->fetchAll()
to
$balkTypes = $stmt->fetchAll()
this will make sure that when you fetch your data it will be an array containing all objects instead of an array containing the array of objects.
Then in your JS, instead of trying to directly read from the string, use JSON.parse() to convert the json string into a collection of JS objects/integers/arrays/strings/booleans
e.g.
success: function(result) {
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
}
EDIT
As pointed out by Armen you could also set the dataType: 'json' in the AJAX request, when the AJAX request returns it will automatically do the JSON.parse() so you can just directly console.log(result); to see the output.
Within the console.log you should now see the nested structure instead of just the string.
From here on your loop which checks the values seems correct and I would not change it unless it tells you that something is wrong.
Docs: JSON.parse();
Set in your jQuery $.ajax request additional attribute dataType: 'json'
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: { params },
success: function( response )
{
// Your data will be already json no need to parse it
console.log(response);
}
});
You are encoding a JSON on the PHP side. You are not decoding it on the JS side.
You should look at JSON.parse()

Array of objects for PHP (AJAX)

I've been struggling with converting an Array of objects to JSON, or any other PHP readable format so I can send it over AJAX.
I'm using localStorage and I save an object into it, I save it using
JSON.stringify(data)
Now when I loop through all the localStorage data, I add it to an array using the following code
var locations = new Array();
for(var i = 0; i < localStorage.length; i++){
locations[i] = JSON.parse(localStorage.getItem(localStorage.key(i)));
}
The end result looks like this.
This is my $.ajax request
$.ajax({
type: "POST",
url: "store.php",
dataType: "json",
data: locations,
success: function(data) {
console.log(data);
}
});
The only problem is that I can't seem to convert it to a readable format to send to PHP
Any clues? Thanks!
Make your post data an object.
$.ajax({
type: "POST",
url: "store.php",
dataType: "json",
data: {location: locations},
success: function(data) {
console.log(data);
}
});
Then on your PHP: print($_POST['location']);
You can also simplify like this.
$.post('store.php', {location: locations}, function(data) {
console.log(data);
});
You should also be able to pass the content directly from localStorage -- no need to build an array from it.
Data formed with JSON.stringify() can be sent through $.ajax and interpreted by PHP.
You can use PHP's input stream to read your data:
$json = file_get_contents('php://input');
$array = json_decode($json);
For more info on PHP's I/O streams, see http://php.net/manual/en/wrappers.php.php

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/

Using $.ajax to return HTML & turn it into JavaScript array

var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "html",
success: function (data) {
var dataObj = data.replace(/"/g, '"');
console.log(dataObj);
}
});
I'm grabbing the contents of an HTML page, and the contents on that page is super simple. It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. This is all that's on that HTML page:
[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
Without replace the "'s, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array?
You can use JSON.parse
JSON.parse(dataObj);
You can parse the returned HTML fragment as JSON:
JSON.parse(dataObj);
Change "dataType" to "json" and it will convert it for you:
var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "json",
success: function (data) {
console.log(data);
}
});
If it is returning the " instead of ", then I would change the AJAX return page to make sure it is doing a proper JSON response.

Categories

Resources