Using a javascript array to request data from a JSON file - javascript

I was wondering if it's possible to request data from a JSON file (For example: customers.name). But instead of that using an array containing the JSON object names and looping it. My code is below.
function load(url ,callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', url, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == 200) {
callback(xobj.responseText);
}
};
xobj.send(null);
}
load("klanten.json", function(response) {
var klanten = JSON.parse(response);
//Array containing JSON file object names.
var infArray = ['name', "address", "email", "phone", "place", "zip"];
//Calling said info using a for loop.
for(var i = 0; i < infArray.length; i++) {
console.log(klanten[i].infArray[i]);
//It not working for some reason.
}
});
I`d love some help with this. And in case what im asking is completely stupid, also let me know! Any help is welcome, thanks!

Change console.log(klanten[i].infArray[i]); to:
console.log(klanten[i][infArray[i]]);

Related

My jQuery Ajax Call to pure Javascript

I asked about 5 month ago about rewriting my ajax call in pure Javascript. Here the original post: https://stackoverflow.com/questions/35415812/need-help-to-rewrite-my-jquery-ajax-call-to-plain-javascript
I never thought about to rewrite the script completely because it works but now i need to rewrite the whole script to plain js. I already startet.
Here is the jQUery/JS mix:
var cc = document.getElementsByClassName("cart-count");
var wc = document.getElementsByClassName("wishlist-count");
var url = wp_ajax.ajax_url;
var data = {
action: 'get_counts'
};
// JQUERY JS mixed VERSION
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (data) {
var counts = JSON.parse(data);
console.log(data);
for(var i = 0; i < cc.length; i++){
cc[i].innerText=counts["cartCount"];
}
for(var i = 0; i < wc.length; i++){
wc[i].innerText=counts["wlCount"];
}
}
});
console says:
{"cartCount":"(1)","wlCount":"(3)"}
That's right!
But now i tried to rewrite the rest. Here the latest:
var cc = document.getElementsByClassName("cart-count");
var wc = document.getElementsByClassName("wishlist-count");
var url = wp_ajax.ajax_url;
var data = {
action: 'get_counts'
};
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
//document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
var counts = data
console.log(data);
for(var i = 0; i < cc.length; i++){
cc[i].innerText=counts["cartCount"];
}
for(var i = 0; i < wc.length; i++){
wc[i].innerText=counts["wlCount"];
}
console.log('done');
} else if (xmlhttp.status == 400) {
console.log('There was an error 400');
} else {
console.log('something else other than 200 was returned');
}
}
};
xmlhttp.open('POST', url, true);
xmlhttp.send(data);
It does't work. The console gives me not the value, just the var:
Object {action: "get_counts"}
My question/problem: How can i get the data action values without the jQuery ajax? Please no questions like "why not jQuery?".
Thanks for all help!!! Sorry for my english.
UPDATE:
I got it!
jQuery:
var data = {
action: 'get_counts'
};
JS:
url + '?action=get_counts'
add this
var data = JSON.parse(xmlhttp.responseText);//you have to parse result
before this
var counts = data
console.log(data);
You are not evaluating the AJAX response data, but the local variable data which is set above the AJAX call:
var data = {
action: 'get_counts'
};
You need to parse the AJAX response instead:
if (xmlhttp.status == 200) {
console.log( JSON.parse(xmlhttp.response) )
}
See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response
Its happening because Ajax is async request which the browser handers in a different thread than the one which is processing your code. Normally jquery and other similar frameworks have callback methods defined for that but in pure JS implementation you can use
xmlhttp.responseText
to fetch the output once the request is done

Return array back through nested functions with Javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Good evening everyone. I know this will seem like an extremely easy subject for many here, but I've been struggling for a while to reconstruct a function I have in order to make it dynamic and reusable site-wide.
The main struggle I'm having is returning an Array using the following:
var arr = getData("admin/fullDatabaseAccess.php");
This doesn't return the array as expected. Now, without writing every possible variation of what I did to the getData function in an attempt to return the array which it creates, I'll first show you the original function which works:
function getData() {
var xmlhttp = new XMLHttpRequest();
var url = "admin/fullDatabaseAccess.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
processResponse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
var arr = JSON.parse(response);
// do stuff with the array - I originally modified the DOM using jQuery here, however I now want to use this entire getData function as a more generically useful function
}
}
I would then trigger the getData function on the single page which I was using this code with to generate an array, followed by modifying the page elements with the array data.
THIS BRINGS ME TO MY PROBLEM - I tried to make this function re-usable across the site by creating this version below, and calling the array data using the code line I posted at first (var arr = ..):
function getData(file) {
var xmlhttp = new XMLHttpRequest();
var url = file;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
processResponse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
var arr = JSON.parse(response);
return arr;
}
}
I cannot seem to feed the data back to the variable. I've tried restructuring the function quite a lot to return values within the nests etc but I've got to the point where I'm confusing myself and can't really show the examples I tried as I deleted them and decided to start again.
Any help would be greatly appreciated!!
You need to provide a callback to getData, like this
function getData(file, cb) {
var xmlhttp = new XMLHttpRequest();
var url = file;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Calls the callback function with the response data
cb(processResponse(xmlhttp.responseText));
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
var arr = JSON.parse(response);
return arr;
}
}
getData(file, function(data) {
// data is now what's being returned from processResponse()
});

cannot pass a javascript object to php via ajax

I've created a new array in javascript and I'm adding values to it indexes from a function an then passing the array to the ajaxCall function were I try to convert it to json and send it to a php file via ajax, but the variable json is allways empty. I've been reading a lot about how to send javascript objects json_encoded via ajax and looks like this is the way to do it, but obviously I haven't readed enought or there is something I've been missing. Anycase I'm newbie in javascript and any help would be apreciated.
function createArray()
{
var advancedFormVars = new Array();
advancedFormVars['checkbox1'] = document.getElementById('OfferID').value;
advancedFormVars['checkbox2'] =document.getElementById('offerName').value;
AjaxCall(advancedFormVars);
}
function AjaxCall(advancedFormVars){
var json = new Array();
json = JSON.stringify(advancedFormVars); //in debuger it shows me this as content of json variable--> [] but advancedFormVars is not empty
$.ajax({
url : 'AL_loadForm.php',
type : 'POST',
data : {
json : json
},
dataType:'json',
success : function(data) {
alert(data);
}
...
You are trying to use your array as a hash, so the values are not being set..
Instead of setting
var advancedFormVars = new Array();
Try setting
var advancedFormVars = {};
Example
JS:
var advancedFormVars = {};
advancedFormVars['checkbox1'] = 'valueA';
advancedFormVars['checkbox2'] = 'valueB';
var json = JSON.stringify(advancedFormVars);
console.log(json); //{"checkbox1":"valueA","checkbox2":"valueB"}
PHP
<?php
$json = '{"checkbox1":"valueA","checkbox2":"valueB"}';
$obj = json_decode($json);
var_dump($obj);
/*
object(stdClass)#1 (2) {
["checkbox1"]=>
string(6) "valueA"
["checkbox2"]=>
string(6) "valueB"
}
*/
?>
If all you have are two smaller arguments, I'd keep it simple and make an http get request. Encode your arguments if neccessary.
var url = "http://wherever.com/something.php?arg1=";
url += document.getElementById('OfferID').value;
url += "&arg2=" + document.getElementById('offerName').value;
httpGetAsync(url, returnMethod);
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}

Json created to fit a structure

I have created a JSON like this one :
{"data":[{"content":"Event1","start":"new Date(2014,07,10)"},{"content":"Event2","start":"new Date(2014,07,17)"}],"success":true}
In order to fit the following code in Javascript :
data = [
{
'start': new Date(2010,7,23),
'content': 'Event'
},
{
'start': new Date(2010,7,23),
'content': 'Event'
},
];
Witth th JSON i have, i can easily access field, for example :
json.data[0].content
Return : "Event1"
My question is : how can i make the Javascript code "dynamic" to load every components in my JSON, assuming the fact that i don't know how many elements it will contains ?
Currently, i've done the followig code :
var xhr = new XMLHttpRequest();
xhr.open("GET", "/Test", true); // Call to a java servlet
xhr.send();
var json;
var jsonLength;
var data;
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
json = JSON.parse(xhr.responseText);
jsonLength = json.data.length;
}
}
data = [];
for(var i = 0 ; i < jsonLength ; i++){
data.push({
'start':json.data[i]['start'],
'content':json.data[i]['content']
})
}
timeline.draw(data);
EDIT : I don't even enter to the for loop ... Why ?
That's quite simple as these are just arrays and hash objects in JavaScript.
So you can just iterate over them:
for(var i = 0; i < json.data.length; i++) {
var item = data[i];
// Insert this into your data table
// Here you can use item which is set to the current item you are iterating over
}
JavaScript even let's you inspect your so you can look at the individual data item and find out what properties it has like this (see this question for details):
var keys = [];
for(var k in obj) keys.push(k);
UPDATE:
It seems you have fallen into the asynchrosity trap that JavaScript lays out.
The function xhr.onreadystatechange is only called once the event happens, the code below that function is executed instantly. So you where iterating over an empty dataset since the data you where looking at was not yet loaded.
JavaScript is very much callback based and especially with AJAX. Always keep in mind when the code will run, in this case xhr.onreadystatechange = function returns instantly and the code after continues to run. Only inside the function can you expect your variables to be set correctly.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/Test", true); // Call to a java servlet
xhr.send();
var json;
var jsonLength;
var data;
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
json = JSON.parse(xhr.responseText);
jsonLength = json.data.length;
data = [];
for(var i = 0 ; i < jsonLength ; i++){
data.push({
'start':json.data[i]['start'],
'content':json.data[i]['content']
})
}
timeline.draw(data);
}
}
If your json is a string, just do
obj = JSON.parse(jsonString);
Then you'll have an object containing your json data, where you can access using obj[0].content (as an example)
Else, just iterate throught the json object, like Tigraine said.
(You question is a little bit unclear though)
try this:
var x={"data":[{"content":"Event1","start":"new Date(2014,07,10)"},{"content":"Event2","start":"new Date(2014,07,17)"}],"success":true};
for(i=0;i<x.data.length;i++)
{
console.log("content: "+x.data[i].content+" start: "+ x.data[i].start);
}
<script type="text/javascript">
var json = {
'data': [
{
'start': new Date(2010, 7, 23),
'content': 'Event'
},
{
'start': new Date(2010, 7, 23),
'content': 'Event'
},
]
};
alert(json['data'].length);
$(function() {
});
</script>

How can I retrieve multiple JSON files using JavaScript?

I have a web application that receives json from a server. I was using this code:
var http_request = new XMLHttpRequest();
var url = "url where I have the json"
http_request.onreadystatechange = handle_json;
http_request.open("GET", url, true);
http_request.send(null);
var obj;
function handle_json() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var json_data = http_request.responseText;
obj = eval("(" + json_data + ")");
processData(obj);
} else {
alert("A problem ocurred");
}
http_request = null;
}
}
But now I want to receive json from two url's and show the information. How can I do this using JavaScript? I know eval is not the appropiate thing to do but this is just a prototype.
Thank you so much! :)
As others have mentioned, you simply need to make 2 requests. In order to re-use the code you have already written, you could define a function to get json that takes a url argument. Something like this:
function getJson(url, callback){
function handle_json() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var json_data = http_request.responseText;
var parser = (JSON && typeof JSON.parse == 'function') ? JSON.parse : eval;
var obj = parser("(" + json_data + ")");
callback(obj);
} else {
alert("A problem ocurred");
}
http_request = null;
}
}
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = handle_json;
http_request.open("GET", url, true);
http_request.send(null);
}
I replaced the call to eval with some logic that will call JSON.parse if it is present, otherwise it will use eval. Using this function would allow you to make multiple requests by calling it multiple times, like so:
getJson("some url", processData);
getJson("some other url", processData");
If you wanted to process data from different urls in different ways, just define another function similar to processData and pass it along instead, like getJson("some crazy url", processCrazyData);
Using a framework like jQuery would reduce the amount of code that you have to write, but this solution should get it done using basic javascript.
The easiest way would be to put it into a function.
function getJson(url) {
//Remove the var url="string" line
//Rest of code
}
function handleJson() {
//Other code
}
Alternatively, you could use jQuery, in which case your code would be:
$.getJSON('url goes in here',function(data){
processData(data);
});
And just use that whenever you want to grab a page.

Categories