Fetching image from php web service using JSON in javascript - javascript

I want to fetch images from the php web service in my javascript code using json. The alert in the for loop returns "undefined". Please help with your suggestions.
<script>
var menu_category;
var menu_id = [];
var menu_title = [];
var menu_img = [];
"use strict";
function jsonp(url) {
alert("JSONP URL");
var head = document.head;
var script = document.createElement("script");
script.setAttribute("src", url);
head.appendChild(script);
head.removeChild(script);
}
function jsondata(data) {
alert("JSONdata");
var parsedata = JSON.parse(JSON.stringify(data));
var parsed_data = parsedata["main Category"];
for (var i = 1; i <= parsed_data.length; i++) {
alert("FOR");
menu_id[i] = parsed_data.mcatid;
alert(menu_id[i]);
}
}
jsonp("http://remoteaddress/maincategory.php?callback=jsondata");
</script>

Related

Binance Rest API JSON to HTML

I have made 2 .js files with the scripts inside them which are then called by app.html
I'm trying to call both the spot price and 24hr rolling percentage change from Binance rest API. My problem is that it prints the percentage change in the spot pricing HTML element. I think it has something to do with the percentage symbol ID being the same as the spot price symbol ID but I'm not sure.
What did I do wrong?
Here are the finance rest API docs.
HTML
<div class="div-block-3">
<div class="text-block-2"><span class="currency-title">USD</span> <span class="currency-symbol">$</span><strong id="BTCUSDT" class="rates">11,794.00</strong></div>
<div id="BTCUSDT" class="text-block-6"><strong class="negative">-1.84%</strong></div>
</div>
24hr rolling percentage .js
function load() {
var url_base = "https://api.binance.com/api/v3/ticker/24hr?symbol="
var elements = document.getElementsByClassName('text-block-6');
for (var i = 0; i < elements.length; i++) {
var id = elements[i].id;
var url = url_base + id;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url, true);
ourRequest.onload = function () {
console.log(this.responseText);
var obj = JSON.parse(this.responseText);
document.getElementById( obj.symbol ).innerHTML = obj.priceChangePercent;
};
ourRequest.send();
}
}
window.onload = load;
spot pricing .js
function load() {
var url_base = "https://api.binance.com/api/v3/ticker/price?symbol="
var elements = document.getElementsByClassName('rates');
for (var i = 0; i < elements.length; i++) {
var id = elements[i].id;
var url = url_base + id;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url, true);
ourRequest.onload = function () {
console.log(this.responseText);
var obj = JSON.parse(this.responseText);
document.getElementById( obj.symbol ).innerHTML = obj.price;
};
ourRequest.send();
}
}
window.onload = load;

How to get data from a local JSON file in Javascript

I'm trying to retrieve a specific ID from the JSON file depending on user input and then display a picture based on the ID retrieved from the JSON file
function showCard() {
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var obj = JSON.parse("https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper)
var imgId = obj["data"][0]["id"]
document.getElementById("chosenCard").src = "https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jgp";
event.preventDefault();
}
I think what you need is below but I am not sure I understood your json structure:
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var oReq = new XMLHttpRequest();
oReq.open("GET", "https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper", true);
oReq.responseType = "json";
oReq.onload = function(e) {
JSONObject json = new JSONObject(res);
JSONArray ja = json.getJSONArray("data");
JSONObject obj = ja.getJSONObject(0);
var imgId = obj.id;
document.getElementById("chosenCard").src = "https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jgp";
}
oReq.send();
I tried to answer your problem after identifying your problem.
function showCard()
{
event.preventDefault();
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var obj = JSON.parse("https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper)
var imgId = obj[0].id
document.getElementById("chosenCard").src =
"https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jpg";
}

Calling data from JSON file using AJAX

I am trying to load some data from my JSON file using AJAX. The file is called external-file.json. Here is the code, it includes other parts that haven't got to do with the data loading.The part I'm not sure of begins in the getViaAjax funtion. I can't seem to find my error.
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
As #light said, this:
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
Should be:
function getViaAjax(url, callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", url, true);
I built up a quick sample that I can share that might help you isolate your issue. Stand this up in a local http-server of your choice and you should see JSON.parse(xhr.response) return a javascript array containing two objects.
There are two files
data.json
index.html
data.json
[{
"id":1,
"value":"foo"
},
{
"id":2,
"value":"bar"
}]
index.html
<html>
<head>
</head>
<body onload="so.getJsonStuffs()">
<h1>so.json-with-ajax</h1>
<script type="application/javascript">
var so = (function(){
function loadData(data){
var list = document.createElement("ul");
list.id = "data-list";
data.forEach(function(element){
var item = document.createElement("li");
var content = document.createTextNode(JSON.stringify(element));
item.appendChild(content);
list.appendChild(item);
});
document.body.appendChild(list);
}
var load = function()
{
console.log("Initializing xhr");
var xhr = new XMLHttpRequest();
xhr.onload = function(e){
console.log("response has returned");
if(xhr.status > 200
&& xhr.status < 400) {
var payload = JSON.parse(xhr.response);
console.log(payload);
loadData(payload);
}
}
var uri = "data.json";
console.log("opening resource request");
xhr.open("GET", uri, true);
xhr.send();
}
return {
getJsonStuffs : load
}
})();
</script>
</body>
</html>
Running will log two Javascript objects to the Dev Tools console as well as add a ul to the DOM containing a list item for every object inside the data.json array

Capture the call that analytics.js makes after it is loaded using phantomjs

I have been trying to Capture the call that analytics.js makes after it is loaded in phantomjs headless browser.
The problem with this is that, analytics.js load after the page completely loads. So, its getting difficult to track analytics.js calls.
The code which I have tried till now is:
var url = "http://www.alexandani.com/necklaces/sand-dollar-expandable-necklace.html";
var auditlinks = {"www.google-analytics.com/analytics.js": 6, "metrics.alexandani.com": 9, "www.google-analytics.com/collect": 7};
var block_request = 1;
var execution_timeout = 40000;
var resource_timeout = 50000;
var inactivity_timeout = 50000;
var user_agent = "Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.0 Safari/534.34";
var page_http_status_target_url = url;
var page_http_status = null;
var inactivity_timeout_check_period = 100;
var requests = new Array();
var auditlink_urls = Object.keys(auditlinks);
function print(obj){
console.log(JSON.stringify(obj));
}
function create_url_cleaner(){
var rx_match_protocol = /^(http|https):\/\//i;
var rx_match_query_params = /\/*\?.*/i;
function clean_url(url){
return (
(url.replace(rx_match_protocol, ''))
.replace(rx_match_query_params, '')
);
}
return clean_url;
}
function exit(exit_reason){
console.log(requests);
print({
'requests': requests,
'exit_reason': exit_reason,
// Returning http status as an integer makes little sense to me.
'http_status': (page_http_status === null)
? null : page_http_status.toString(),
});
phantom.exit(0);
}
function start_exec_time_limiter(execution_timeout){
setTimeout(
function (){
console.log('hi');
exit("EXEC_TIMEOUT");
},
execution_timeout
);
}
function start_inactivity_tracker(
inactivity_timeout,
inactivity_timeout_check_period
){
var last_activity_time = Date.now();
function register_activity(){
last_activity_time = Date.now();
}
function check_inactivity(){
var now = Date.now();
if (now - last_activity_time > inactivity_timeout){
exit("INACTIVITY_TIMEOUT")
}
}
setInterval(check_inactivity, inactivity_timeout_check_period);
return register_activity;
}
start_exec_time_limiter(execution_timeout);
var clean_url = create_url_cleaner();
var register_activity = start_inactivity_tracker(
inactivity_timeout, inactivity_timeout_check_period);
var page = require('webpage').create();
page.settings.userAgent = user_agent;
page.settings.resourceTimeout = resource_timeout;
//page.injectJs('wait.js');
page.onError = function (msg, stack){
// Ignore errors in the webpage context.
}
page.onResourceReceived = function (response){
register_activity();
if (response.url == page_http_status_target_url){
if (response.redirectURL){
page_http_status_target_url = response.redirectURL;
}
else {
page_http_status = response.status;
page_http_status_target_url = null;
}
}
}
page.onResourceRequested = function (requestData, request){
register_activity();
var timestamp = Date.now();
var url = requestData["url"];
var bare_url = clean_url(url);
for (var k in auditlink_urls){
var alurl = auditlink_urls[k];
if (bare_url.indexOf(alurl) === 0){
requests[requests.length] = [url, auditlinks[alurl], timestamp];
if (block_request === true){
request.abort();
}
break;
}
}
}
page.open(url);
//---------------------------------------------------------------------------//
Why do you need to load analytics.js at all in PhantomJS? If all you want to do is test that the calls to ga() are what you'd expect, just stub out the ga() function and assert that the calls it receives are what you'd expect.
In fact, the analytics.js snippet itself is essentially just a stub that stores the calls it receives on its q property while it waits for the full library to download.
If you don't download the analytics.js script, that ga.q will always be inspectable.

Difficulty in loading multiple images in a list view served by multiple xml files

I am developing a html application for Android and I am trying to load images in a list view. Data specific to list items is being served by multiple xml files. I am using ajax to load xml files and populate the list items. Problem I am facing here is that there are 164 list items. Hence, 164 images and 10 xml files to load. my loader function exhausts after two iterations. It does read the xml files but it's unable to dynamically create list items and populate them with images after two iterations. I believe it's due to stack limitations. I can't think of alternate solution. If somebody could suggest an alternate solution that will be highly appreciated. Below is my loader function. It's a recursive function:
function loadChannels() {
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){ console.log('Error Loading Channel XML'); },
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
loadChannels();
}
}
});
}
try to remove the recursion with an outer loop - something like that:
function loadChannels(){
var stopFlag = false;
// request the pages one after another till done
while(!stopFlag)
{
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){
console.log('Error Loading Channel XML');
errorFlaf = true;
},
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
// lets disable the recursion
// loadChannels();
}
else {
stopFlag = true;
}
}
});
}
}

Categories