web service call and JSON array manipulation in javascript - javascript

I need to call a web service from javascript that returns a JSON array in the following format:
["hello","there","I","am","an","array"]
Unfortunately, the javascript library I'm using (Sencha Touch) to load this data into a widget doesn't accept that format as data input. It will work with something like this however:
[["hello"],["there"],["I"],["am"],["an"],["array"]]
So there are two questions here-- how can I call that web service in javascript and then manipulate the returned array into the format I need? I've been looking at jQuery's getJson() method, not sure if that's the way to go or if there are better ways.
The URL that delivers the JSON array is this right here. Thanks for your help.

Here's a jsFiddle showing both parts of what you asked about. I'm using jQuery for my AJAX call (faked in the jsFiddle) and I'm using Underscore.js for the manipulation:
http://jsfiddle.net/JohnMunsch/E7YTQ/
// Part 1: Get the raw data. Unfortunately, within a jsFiddle I can't go get it from a different domain. So I'm
// simulating the call instead.
var rawDataPromise = $.ajax({
url : "/echo/json/",
data : fakeData,
type : "POST"
});
// var rawDataPromise = $.ajax("http://fastmotorcycleservice.cloudapp.net/FastMotorCycleListService.svc/list/Bruno");
rawDataPromise.done(
function (results) {
// Part 2: Manipulate the data into the form we need.
var manipulatedResults = _.map(results, function (item) { return [ item ]; });
console.log(manipulatedResults);
}
);
// You could also pull that together into a single call $.ajax(...).done(function (results) { ... });

once you have the data in one of your local variables you can manipulate it as you want:
var data = the_function_you_use_to_get_data();
var formatted_array = new Array();
for(i in data){
var d = new Array();
d[0] = i;
formatted_array.push(d);
}
i hope it answered your question

Related

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

Using javascript/html to grab one piece of data from JSON result

Before I start, I'm complete beginner and I hope I'm not misusing terms when I ask my question.
I'm starting off writing an HTML5/Javascript application using Intel XDK to query barcodes of videos games from an online api, and I only need one piece of the JSON result (the title of the game) to then go on and use within my app.
The JSON result looks like this:
{"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
All I want to use in my app is that very first 'productname' entry.
The JSON is from an api provider I have an account with so it's on a remote URL for examples sake we'll call the URL: http://JsonIs.here
I want to be able to query the JSON URL and return "The Elder Scrolls V: Skyrim" as a string which I can then go on to use elsewhere in the application.
I've got my barcode scanning working, I can create the GET request URL already, I just don't know where to start calling that URL and then returning the small piece of information I need.
You can use jQuery's $.getJSON for this. The method returns a promise which has a nice easy-to-understand API.
var productName;
$.getJSON('http://JsonIs.here').then(function (data) {
productName = data[0].productname;
});
A couple of things to note here. 1) getJSON is an asynchronous process, so productName won't be immediately available, so you might have to restructure your code a little to account for this. You can't, for example do this:
var productName;
$.getJSON('http://JsonIs.here').then(function (data) {
productName = data[0].productname;
});
console.log(productName); // undefined
You may find this article useful as it covers how to return a value from an async process in depth.
2) getJSON automatically parses the JSON so you don't have to which is why, in the example, I've called the argument data and not json to save confusion.
To simulate you getting your JSON
var getJSON = function(){
return '{"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}';
};
a function that gets the JSON and creates an array that holds all your productnames
var getProductName = function(){
// get the JSON_string ;)
var JSON_string = getJSON();
// convert it to an obj.
var JSON_obj = JSON.parse(JSON_string);
//create something to store your data in, you don't need to do this ofcourse
var r_productNames = [];
for(var key in JSON_obj){
if(JSON_obj.hasOwnProperty(key)){
r_productNames.push(JSON_obj[key].productname);
}
}
// et voila, you have an array of all the productnames, returned by your request.
console.log(r_productNames);
};
It works for me ;)
Json comes with a key value pair and the indexing starts with 0. Hence json[0] that means json in first index. json[0].productname here productname is the key which will give the value in return
var json = {"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
alert(json[0].productname);
Try using ajax
$.ajax({
type: 'GET',
url: 'http://JsonIs.here',
dataType: "json",
success: function(data) {
console.log(data[0].productname)
},
error: function(data) {
}
});
Using ajax you can try to get the data from the url and you can get the data in the success of the request
Here you go. However I find "0" as key in your JSON response somewhat not seen till today. It is better practice to start of with a character.
Your JSON response have one object. You can access the element in the object by index. Here on 0th index you have your data. The reason we are accessing it as a[0].key where key represent name of key you want to access from the object.
This is how you can get the data from JSON and use it in your application to achieve rest of your functionality as per your question.
var a = {"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
a[0].productname;

LungoJS Json, fill content returned into a list

i am a Java Developer and i need to create a SIMPLE app, as i need this to run into ios & Android i decided to try it using lungoJS, my main problem is that i dont know much JavaScript.. :(
well i have created the prototipe of the app using lungo, but now i need to fill a list with the response (on Json) from my server. I saw in lungos api the function that is used to get a Json request. looks like this:
var url = "http://localhos:8080/myService";
var data = {id: 25, length: 50};
var parseResponse = function(result){
//Do something
};
Lungo.Service.json(url, data, parseResponse, "json");
//Another example
var result = Lungo.Service.json(url, "id=25&len=50", null, "json");
my http request is indexed from 1 to 4 so for each element would be "www.myapp.com/api/1" "www.myapp.com/api/2"
....
my question is, hoy could i get the answer (json) of my request and how do i select items for example if i only want the "name" or "surname"...
thanks, hope some1 could help me :)
I solved my problem long time ago, i will share it:
function some_function(callback) {
var my_number = $$.get('http://app.com/applications/3.json',{ }, function(api) {
obj=api;
template="{{#name}}\
\
{{/name}}";
html=Mustache.render(template,obj);
$$('section#main article#main-article').html(html); //Painting Json obtained on my HTML
}
);
;
callback(my_number);
}
// call the function
some_function(function(num) {
// this anonymous function will run when the
// callback is called
console.log("callback called! " + num);
});
This code uses the obtained Json to Prototype HTML, useful to load images or data from server and not stored on local.
BR, Kike

$.get with dynamic data names?

I am having an issue trying to set the data name or the objects being passed in. I am writing a system that uses AJAX to send requests to the server which then returns the necessary data. However, I am trying to make things generic to where if the developer adds more "slates" then it will automatically send the request on its behalf. The code looks as following:
$(document).ready(function() {
$(".slate").each(function(){
$.get("requests.php", { $(this).attr('name') : "true" }, function(data){
});
});
});
in other words it takes the name of the element and applies it to the query string. JavaScript doesn't seem to like the
$(this).attr('name')
in the syntax which is understandable since it expects just text (not a var or a string). Is there a way to make this work? Any help is greatly appreciated!
$(document).ready(function() {
$(".slate").each(function(){
var data = {};
data[$(this).attr('name')] = "true";
$.get("requests.php", data, function(data){
});
});
});

How to get JSON from PHP to JS?

I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).
{
"1": [
{"id":"2","type":"1","description":"Foo","options:[
{"opt_id":"1","opt_desc":"Bar"},
{"opt_id":"2","opt_desc":"Lorem"}],
{"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
{"id":"14","type":"1","description":"Test","options:[
...
etc
Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:
Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
enter code here
}
Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...
EDIT:
I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
$.each(pushedData, function(i, serverData)
{
alert(i);
})
})
})
});
The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.
Not sure but I think, you can use
$.getJSON('url', data, function(jsonData) {
// operate on return data (jsonData)
});
now you can access and operate on the PHP json data,
if you're going to use it outside the getJson call you can assign it to a variable
var neededData;
$.getJSON('url', data, function(jsonData) {
neededData = jsonData;
});
Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/
This example should get you started:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example is based on the JSON structure being;
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Do not use echo in PHP. It will print string not JSON.
Use json_encode to pass JSON to javascript.
Use can use each to get the values in JSON at javascript end.
Example
http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.
Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.
HTH

Categories