store json data in a java script variable - javascript

First thing I am new to javascript.
What I am trying to do is to get data from a URL in json and save it in java script variable.
What I have already done:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
This shows me output : 1
and what I want is to get data from URL like:
var json ='url';
obj = JSON.parse(json);
alert(obj.count);
and for the clearance I am using this URL to get JSON data and i just need to print fare from the data.
any help in this matter would be highly appreciated !!
I have done this in php like this way, but I need it to do this in javascript.
$jsonData = file_get_contents("url");
$json = json_decode($jsonData,true);
echo $json['fare'];

$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
console.log(data)
});
Try this ways to read ur URL

Try this way, convert the url to an array then
var json = 'data url in array',
obj = JSON.stringify(json);
alert(obj.count);

Use Ajax call for fetching data from external sources.
On clicking it will fetch data from the url.
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://daewoocab-test.herokuapp.com/api/v1/rates?token=6ab676ddd7bf00101408ea3a27fdbb8ad22e9dcdf2faafdcd2ef0efc1509d463&pickup_area=Street%201%2CF-8%2CIslamabad%2CIslamabad%20Capital%20Territory%2CPakistan&drop_area=padhrarazadari.com%2C%20kallar%20kahar%20road%2C%20padhrar%2C%20punjab%2C%20pakistan&distance=169", function(result){
console.log(result);
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<button onclick="showHint()">abcd</button>
<script>
function showHint() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(JSON.parse(xhttp.response));
}
};
xhttp.open("GET", "http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback", true);
xhttp.send();
}
</script>
</body>
</html>

Temporary Solution:
Here is my working fiddle
If you get 'Access-Control-Allow-Origin' header is present on the requested resource. error, add CORS extension to your browser and enable it.
hope this helps :)

Related

How to return an array from PHP script when an HTTP request is sent from javascript?

Hi I'm new to PHP and I'm stuck on an issue,
I want to send a HTTP request to a PHP script and it should return a 2x2 array. But with my code I'm receiving nothing.
index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "get_info.php");
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
</script>
</body>
</html>
get_info.php:
<?php
$return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
return $return_array;
?>
json_encode() that array, and echo (not return!) the resulting json string:
<?php
$return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
echo json_encode($return_array);
// remove the trailing ?> just to make sure you don't send an unwanted newline, space or smth
Then in javascript
var myArray = JSON.parse(xhr.responseText);
console.log(myArray);
to make a js array out of it again.
Some docs and related reads:
php: json_encode()
JSON wiki
javascript: JSON.parse()
Use echo instead of return ... this isn't a function that was called; it is a code snippet that simply puts dynamic data in place of static text.

Customize DocxJS to render local docx file

I just found a working docx to html converter using only javascript on github. The main code which converts docx to html is below. The issue is the page just has a button which on click or drag and choosing a word document, opens it as html. I want to specify a file location in the code so I can load it on the server for loading some documents from computer locally.
Code which converts docx to html and renders :
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DocxJS Example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="https://www.docxjs.com/js/build/latest.docxjs.min.js"></script>
</head>
<body>
<input id="inputFiles" type="file" name="files[]" multiple="false">
<div id="loaded-layout" style="width:100%;height:800px;"></div>
<script>
$(document).ready(function(){
var $inputFiles = $('#inputFiles');
$inputFiles.on('change', function (e) {
var files = e.target.files;
var docxJS = new DocxJS();
docxJS.parse(
files[0],
function () {
docxJS.render($('#loaded-layout')[0], function (result) {
if (result.isError) {
console.log(result.msg);
} else {
console.log("Success Render");
}
});
}, function (e) {
console.log("Error!", e);
}
);
});
});
</script>
</body>
</html>
I tried changing var files = e.target.files; to var files = "C:/sda/path/to/docx"; but that didn't help.
I tried to change
var files = e.target.files;
to
var files = new Array(new File([""], "sample.docx"));
but it gives me OOXML parse error.
Update:
Lets say I have a file location variable in PHP and I wish to use that instead in the javascript code. How do I do it?
I also checked docx2html javascript code and here is the code for it:
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
<script>
function test(input){
require("docx2html")(input.files[0]).then(function(converted){
text.value=converted.toString()
})
}
</script>
</head>
<body>
<input type="file" style="position:absolute;top:0" onchange="test(this)">
<br/>
<br/>
<textarea id="text"></textarea>
</body>
</html>
Same issue need input.files[0] here as well
Update:
I am trying to use the method mentioned in the comments but encounter some errors:
var fil;
var getFileBlob = function (url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.addEventListener('load', function() {
cb(xhr.response);
});
xhr.send();
};
var blobToFile = function (blob, name) {
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};
var getFileObject = function(filePathOrUrl, cb) {
getFileBlob(filePathOrUrl, function (blob) {
cb(blobToFile(blob, 'test.docx'));
});
};
getFileObject('demo.docx', function (fileObject) {
console.log(fileObject);
fil = fileObject;
});
The error primarily was “Cross origin requests are only supported for HTTP.” before I used https://calibre-ebook.com/downloads/demos/demo.docx instead of just demo.docx in above file path. This however gives another error:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
which means chrome cannot load it. It needs to be working on a server. If someone can help providing a fix to make it work offline, let me know. The last method was asynchronous call.
In the browser, there is a sandbox policy.
It can not access files directly via Path.
Please access the file through drag & drop event or input file change event.

How to send response with javascript to draw html elements

I'm creating a script like twitter in which user just provide an id and all his/her tweets get loaded on site where the script inserted.
What I've done is
User should copy this code to load my widget
<a class="getStarted" data-getStartedID="123456789">Get Started App ID</a>
<script>
!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;
js.src=p+"://localhost/practices/js_practice/siteOpen.js";
fjs.parentNode.insertBefore(js,fjs);
}}(document,"script","getStarted-C");
My siteOpen.js is as below :
!function(d){
var a = d.getElementsByClassName('getStarted');
var x = document.getElementsByClassName("getStarted")[0].getAttribute("data-getStartedID");
var r = new XMLHttpRequest();
var appID = x;
r.open("POST", "openwebIndex.php", true);
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.setRequestHeader("Content-length", appID.length);
r.setRequestHeader("Connection", "close");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
if(r.responseText.trim()==1){
return '<p>output to be draw on where script is pasted</p>';
if(console)console.info('Valid appID');
}
};
r.send('appID='+appID);
}(document);
i don't know what to do to send the response and load/draw my widget on user's website.
My response will be in html elements.
Please suggest me what should i do. I just stuck at this point.
EDIT
I'm getting object HTMLScriptElement when I alert js variable.
Just trying adding the html code in the body tag.
users html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
<script src="widget.js"></script>
Your widget.js
// var appId = d.getElementsByClassName('getStarted');
// process the app id and make the output here
var output = "<div>This is the content of the widget</div>";
document.body.innerHTML += output;
This will show the content in the users html file. If you have cross domain issue, use JSONP for resolving that.

Handlebars not parsing?

I can't for the life of me figure out what I'm doing wrong.
This is my HTML/JS:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="handlebars-v1.1.2.js"></script>
<script>
$(document).ready(function(){
var jsonString = null;
$.getJSON("data.json", function(data) {
jsonString = data;
});
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
});
</script>
</head>
<body>
<script id="items" type="text/x-handlebars-template">
<span>{{Title}} : {{CSCI}}</span>
</script>
<ul>
</ul>
</body>
</html>
And this is my data.json file:
{
"Title":"I am a thing",
"CSCI":" "
}
The only output I get is the ":" so it's doing something properly. The console shows nothing (as in completely empty so I assume there's no syntactical errors anywhere?).
I don't like posting questions like this as it's usually because of a small mistake on my part somewhere, but I know you guys love this stuff ;)
As getJSON is an async function call you need to compile Handlebars in success callback function
$(document).ready(function(){
var jsonString = null;
$.getJSON("data.json", function(data) {
jsonString = data;
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
});
});
getJSON is async, and so
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
should all be inside of the callback as well

Javascript - Reading file in client directory

I'm a new programmer that learn javascript, Im new in js actually.
I have a task that require a web page able to read file in client directory. I've got some js code :
<html>
<script type="text/javascript">
function ReadWeight() {
var filePath = "file:///D:/Text.txt";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
alert(fileContent);
}
ReadWeight();
</script>
<body>
</body>
</html>
When I save this code in my directory and access it by this link, It works well.
file:///D:/test.html
But when I put it in my localhost and I access it, the JS doesn't works.
Does my code incorrect when in web server?
Please help me out.
Might I suggest using an error console to display the error so people know how to help you? =] And paste it in your query
Download something like firebug and see if a request is being made (for FireFox)
It looks like you would rather want to access the file via the http:// protocol, instead of file://
As far as I know you can only read client files using an <input type="file"> element. Once you get the file you can read it multiple times:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Refresh</title>
<script src="filerefresh.js"></script>
</head>
<body>
<input id="fileInput" type="file">
<pre id="fileDisplay"></pre>
</body>
</html>
JavaScript:
(function() {
var sleepInterval = 1000; // 1 second
var fileInput;
var fileDisplay;
var reader;
var id = undefined;
function initialize() {
fileInput = document.getElementById("fileInput");
fileDisplay = document.getElementById("fileDisplay");
reader = new FileReader();
reader.onloadend = function() {
fileDisplay.innerHTML = reader.result;
reschedule();
};
fileInput.addEventListener("change", readFile);
}
function reschedule() {
if (id !== undefined) {
clearTimeout(id);
}
id = setTimeout(readFile, sleepInterval);
}
function readFile() {
reader.readAsText(fileInput.files[0]);
}
window.onload = initialize;
})();

Categories

Resources