Reading JSON encoded Array form cakePHP view controller - json

Hello I have a JQuery/Ajax function as following:
$.ajax({
type : "POST",
url : "/posts/getids",
success: function(response){
console.log(response);
},
error: function() {
alert('An unexpected error has occurred! Please try later.');
}
});
In my cakePHP script I'm sending an array using the json_encode($array) function.
In firebug I get this result :
[{"Post":{"id":1}},{"Post":{"id":2}},{"Post":{"id":4}},{"Post":{"id":3}}]
So my question is How can I simply print only the ids like this : 1, 2, 3, 4
Thank you.

// Convert JSON to JavaScript array.
var dataFromServer = JSON.parse(response);
// Creating an array of id's.
var idArray = [];
// Moving data to "idArray".
for(i = 0; i < dataFromServer.length; i++){
idArray[i] = dataFromServer[i].Post.id;
}
// Checking the result.
console.log(idArray);
// [1, 2, 3, 4].

Related

Using data in html from an API response

As a starter in html world, i would like to know and start using simple APIs to insert into my blog posts.
I tried to include as html values some simple API like: https://bitcoinfees.earn.com/api/v1/fees/recommended and I used examples given here: Display Json data in HTML table using javascript and some others more like: http://jsfiddle.net/sEwM6/258/
$.ajax({
url: '/echo/json/', //Change this path to your JSON file.
type: "post",
dataType: "json",
//Remove the "data" attribute, relevant to this example, but isn't necessary in deployment.
data: {
json: JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]),
delay: 3
},
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
function drawTable(data) {
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(drawRow(data[i]));
}
$("#personDataTable").append(rows);
}
function drawRow(rowData) {
var row = $("<tr />")
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
return row;
}
but the result is always blank.
Please, can you give me some hint to can use that API and insert that numbers values for "fastestFee","halfHourFee","hourFee" as html values?
Thank you all!
Welcome to the html world. You are certainly right in assuming that data from APIs is a great way to make your websites more dynamic.
There is an example on W3 Schools on how to handle a http request. I think this is a good place to start https://www.w3schools.com/xml/xml_http.asp. You create a http object that does some sort of data fetching. In this example it is done with the xhttp.send(). At the same time you have a listener that monitors if the onreadystatechange property of the xhttp has changed. And if that change is status 200 (success) then perform some actions.
Here is my JSfiddle with example from your API
http://jsfiddle.net/zvqr6cxp/
Typically these actions would be to structure the returned data and then do something with the data, like show them in a table.
The example shows the native html xhttp object in use with an event listener. Typically as you learn more about this you would probably start using a framework such as jquery or Angular that can handle http requests smoother, keyword here is callback functions.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//In this example, I used your API link..first I would do is turn the JSON into a JS object
myObject = JSON.parse(xhttp.responseText)
document.getElementById("fast").innerHTML = myObject.fastestFee
document.getElementById("half").innerHTML = myObject.halfHourFee
document.getElementById("hour").innerHTML = myObject.hourFee
}
};
xhttp.open("GET", "https://bitcoinfees.earn.com/api/v1/fees/recommended", true);
xhttp.send();

Reading an External json data

My script is looking at json files created on the server and retrieved using
//this is the code that gets the JSON file
jQuery.get(link,data)
Alerting out 'data' shows the json text as valid:
{"menu":[{"link":"../chapter-1/index.html","title":"Chapter 1", "dl": "chapter-1"}
I try and parse the returned 'data' variable
obj = JSON.parse(data);
So that I can loop through it and do my additional tasks.
When I try and JSON.parse(data) it fails
//The loop
for (i = 0; i < obj.menu.length; i++) {
console.log(obj.menu[i].dl);
download_packet(obj.menu[i].dl, i);
}
When I add the json manually
obj = JSON.parse('{"menu":[{"link":"../chapter-1/index.html","title":"Chapter 1", "dl": "chapter-1"}]}');
It works.
I have tried to convert to string etc.
Anyone know what I am stuffing up? - There are no error messages in the console.
This is the whole snippet:
function download_items(link) {
jQuery.get(link, function(data) {
var obj = data;
var i;
for (i = 0; i < obj.menu.length; i++) {
console.log(obj.menu[i].dl);
}
});
}
#Malcolm Mclean - put me on the right track.I converted my object to string then parsed it and it worked. A bit inefficient but its working.
Thanks Mal!
The JSON had to be parsed correctly:
jQuery.get(link, function(data) {
var obj = String(json_object);
obj = JSON.parse(json_object);
}

How to create an object of specific type from JSON in Parse

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible

Return json object from dojo.xhrget

I am trying to get the json object from a dojo xhrGet call.
What I want is jsonobject = stuff;
I can see the json object in the console, but cannot access it!
var xhrargs = {
url: "/rest/url",
handleAs: "json",
preventCache : false,
load: function(json_results){
console.log(json_results);
store = json_results;
return dojo.toJson.json_results;
},
error: function(response, ioArgs) {
console.error(response);
console.error(response.stack);
}
};
var deferred = dojo.xhrGet(xhrargs);
console.log("Json is "+JSON.stringify(deferred));
The console.log part that shows the json_results is fine, exactly what I want.
The dojo.xhrXXX methods are asynchronous. This means that the lines following
var deferred = dojo.xhrGet(xhrargs);
Will continue to execute while the call to an external endpoint is processing. This means you need to use the promise API to tell a certain block of code to execute once the XHR request is complete:
var deferred = dojo.xhrGet(xhrargs);
deferred.then(function(result){
//this function executes when the deferred is resolved (complete)
console.log('result of xhr is ',result);
});
Due to the asynchronous nature of the request, for most intents and purposes that value doesn't exist outside the scope of the callback function. One way to structure your code around this is in multiple blocks. for example:
var xhrLoaded = function(results){
console.log('results = ',results);
store = results;
}
var performXhr = function(){
var xhrargs = {
url: "/rest/url",
handleAs: "json",
preventCache : false,
error: function(response, ioArgs) {
console.error(response);
console.error(response.stack);
}
};
var deferred = dojo.xhrGet(xhrargs);
deferred.then(xhrLoaded);
}
performXhr();
You can still access variables outside of the scope of the function (for example if store were defined globally).
try this
var xhrArgs = {
url:"MethodName.action?Id="+id,
handleAs: "json",
load: function(Data){
var values = Data;
var count = Object.keys(values).length // gives u all keys count in a json object. In mine it is 0,1,2,3
for (var i =0; i<count; i++){
var temp = values[i]; // values['name']
// do somthing ..
}
}
},
error: function(error){
alert(error);
}
}
dojo.xhrPost(xhrArgs);

JSON.stringify gives me wrong json array

I have this code:
var sidebars = {};
var counter = 0;
// Loop through all already crated sidebars
$('.custom_dynamic_sidebars li').each(function(event) {
sidebars[counter] = $(this).text();
counter++;
});
var sidebars_string = JSON.stringify(sidebars);
but it gives me this string:
{\"0\":\"aa\",\"1\":\"bb\"}
Here is javascript which sends array to the server:
$.ajax({
url:"/welit_2/wp-admin/admin-ajax.php",
type:'POST',
data:'action=dynamic_sidebars&sidebars='+sidebars_string+'',
success:function(results) {
console.log(results);
}
});
does anyone know what am I doing wrong?
thx for your time
So I found a solution If you run stripslashes() on the JSON string before you output it, it works fine