How to include JSON data in javascript synchronously without parsing? - javascript

I want to load a JSON file from my own server containing an array into a javascript Object variable.
I would like to do it at the beginning of page load in a synchronous way because data is needed during page load.
I managed to use jQuery.getJSON but this is asynch ajax and it seems a little overkill.
Is there a way to load JSON in a synch way without doing your own parsing? (more or less like using a <script language="JavaScript" src="MyArray.json"></script>)
Thanks in advance for any help, hope it makes sense since I am a javascript newbie.
Paolo

getJSON() is simply shorthand for the ajax() function with the dataType:'json' set. The ajax() function will let you customize a lot about the request.
$.ajax({
url: 'MyArray.json',
async: false,
dataType: 'json',
success: function (response) {
// do stuff with response.
}
});
You still use a callback with async:false but it fires before it execution continues on from the ajax call.

Here you go:
// Load JSON text from server hosted file and return JSON parsed object
function loadJSON(filePath) {
// Load json file;
var json = loadTextFileAjaxSync(filePath, "application/json");
// Parse json
return JSON.parse(json);
}
// Load text with Ajax synchronously: takes path to file and optional MIME type
function loadTextFileAjaxSync(filePath, mimeType)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
if (mimeType != null) {
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType(mimeType);
}
}
xmlhttp.send();
if (xmlhttp.status==200 && xmlhttp.readyState == 4 )
{
return xmlhttp.responseText;
}
else {
// TODO Throw exception
return null;
}
}
NOTE: This code works in modern browsers only - IE8, FF, Chrome, Opera, Safari. For obosolete IE versions you must use ActiveX, let me know if you want that I will tell you how ;)

if you're using a server script of some sort, you could print the data to a script tag on the page:
<script type="text/javascript">
var settings = <?php echo $json; ?>;
</script>
This will allow you to use your data synchronously rather than trying to use AJAX asynchronously.
Otherwise you'll have to wait for the AJAX callback before continuing on with whatever it is you're doing.

I only needed to read a small input file provided in json format and extract a small amount of data. This worked just fine in the circumstances:
json file is in the same directory as the script and is called data.json, it looks something like this:
{"outlets":[
{
"name":"John Smith",
"address":"some street, some town",
"type":"restaurant"
},
..etc...
read the data into js like this:
var data = <?php echo require_once('data.json'); ?>;
Access the data items like this:
for (var i in data.outlets) {
var name = data.outlets[i].name;
... do some other stuff...
}

If RequireJS is an option, you can make it a dependency using requirejs. I use it to mock data in my Angular application. It's essential that some of the mocked data is there before the bootstrap of the app.
//Inside file my/shirt.js:
define({
color: "black",
size: "unisize"
});
Just wrap the json data in a define and declare it as a dependency. More info here: http://requirejs.org/docs/api.html#defsimple

AFAIK jQuery has deprecated synchronous XHR requests because of the potential for performance issues. You could try wrapping your app code up in the XHR response handler as in the following:
$(document).ready(function() {
$.get('/path/to/json/resource', function(response) {
//'response' now contains your data
//your app code goes here
//...
});
});

The modern HTML5 way without jQuery would be:
var url="https://api.myjson.com/bins/1hk8lu" || "my.json"
var ok=await fetch(url)
var json=await ok.json()
alert(a.test)

Related

call PHP function inside JS [duplicate]

Is there a way I can run a php function through a JS function?
something like this:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
test
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
jQuery - http://jquery.com/download/
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX.
You can send data to server (for eg, GET /ajax.php?do=someFunction)
then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:
<?PHP
echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";
function myPhp(){
echo"The page says: Hello world!<br>";
echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>
<div id="mainx"></div>
<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>
<input type="button" value="CallPHP" onclick="callPhp()">
Note: The texto.txt file has the content 'Hello world! (Old content).
The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.
But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.
So, If you don't want the user to know what commands are running on the server:
You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).
Otherwise:
If the output of commands on the server-side is not delayed:
You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).
Otherwise:
You 'must' use Ajax.

Ajax call via POST not working

I have a lil problem with an AJAX request.
We have a lil PHP, JavaScript application (Website). The application is running fine on all desktop browsers + on our old MDE's (some Windows CE6 MDE). Now on our new Motorola MC9200 (Windows Embedded Compact 7 formerly CE7) it's not working anymore.
The problem is some small JavaScript function. It disables the buttons/input fields, starts a Ajax.Request (prototype 1.72 but I tested jQuery 1.11.1 too), does something on the database and when everything went right it is refreshing the site via window.location. This function isn't working always on the new devices. Sometimes it does, sometimes not.
simplified code:
function loadSite(siteName) {
disableForm();
var parameters = {
/* SOME PARAMETERS */
};
new Ajax.Request('ajax/ajax_db_execute.php', {
method: 'post',
parameters: parameters,
onSuccess: callbackFunc
});
}
function callbackFunc(transport) {
response = transport.responseText.evalJSON(true);
if(response.retcode === 0) {
window.location = "start.php?id=<?php echo $id; ?>";
} else {
show_error_box(response.errortext);
enableForm();
}
}
I tried to output the response in the callbackFunc but that function wasn't even called. Next thing I tried was to put some alert at the end of the loadSite function, it was fired everytime. I already checked the parameters and they look fine too.
After that I put some simple fwrite in the php file. It looks like that file isn't even called sometimes. So the question is why?
By changing the method to 'get' I couldn't reproduce the problem and everything is working fine. Problem about that is that I don't want to use get + some parameters might be too long for get to handle.
The parameters in that example were just some simple integers and strings. Does anyone have an idea what might cause the problem and some workaround?
It seems that your post request response is not synchronized. So please use setTimeout function in your post callback like that
setTimeout(function(transport) {
response = transport.responseText.evalJSON(true);
if(response.retcode === 0) {
window.location = "start.php?id=<?php echo $id; ?>";
}
else
{
show_error_box(response.errortext);
enableForm();
}
}, 3000);

reading server file with javascript

I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:
<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
and (with file_inhoud, lines defined elsewhere)
function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
Debug function shows:
readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
So statement that stops the program is:
var file_inhoud=doc.document.body;
What is wrong? What is correct (or best) way to read this file?
Note: I see that the file is read and displayed in the frame.
Thanks!
Your best bet, since the file is on your server is to retrieve it via "ajax". This stands for Asynchronous JavaScript And XML, but the XML part is completely optional, it can be used with all sorts of content types (including plain text). (For that matter, the asynchronous part is optional as well, but it's best to stick with that.)
Here's a basic example of requesting text file data using ajax:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
You'd call that like this:
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
However, the above is somewhat simplified. It would work with modern browsers, but not some older ones, where you have to work around some issues.
Update: You said in a comment below that you're using jQuery. If so, you can use its ajax function and get the benefit of jQuery's workarounds for some browser inconsistencies:
$.ajax({
type: "GET",
url: "path/to/file",
success: function(text) {
// `text` is the file text
},
error: function() {
// An error occurred
}
});
Side note:
I found that javascript is client based...
No. This is a myth. JavaScript is just a programming language. It can be used in browsers, on servers, on your workstation, etc. In fact, JavaScript was originally developed for server-side use.
These days, the most common use (and your use-case) is indeed in web browsers, client-side, but JavaScript is not limited to the client in the general case. And it's having a major resurgence on the server and elsewhere, in fact.
The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.

HTML/Javascript - Get text from online file

I have info that Shoutcast outputs as an html file.
The html file looks like this: http://216.118.106.247:443/7.html.
Is there any way to get the last item in that list/array into Javascript as a string?
I want to output the song info in a html file, I assume that once I get it into JS as a string that I can use the document.write() function to output the code...
Thanks!
If you look at http://code.google.com/chrome/extensions/xhr.html, you'll need to set up cross-origin requests and then you should be able to use the XMLHttpRequest to fetch the data.
EDITED:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = process;
xhr.open("GET", "http://216.118.106.247:443/7.html", true);
xhr.send();
function process()
{
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
// resp now has the text and you can process it.
alert(resp);
}
}
Take a look at XMLHttpRequest aka Ajax requests.
There are a ton of libraries that make "Ajax" easy. Try this one:
http://www.prototypejs.org/api/ajax/request
There are limitations with what you can retrieve using ajax. Due to security issues your browser will not let javascript running on yourwebsite.com perform ajax requests to mywebsite.com.
Look up cross site scripting.
There are several methods out there for you to use. But make sure files are in the same server or folder.
Using XMLHttpRequest: http://www.javascripter.net/faq/xmlhttpr.htm
Using FileSystemObject: http://msdn.microsoft.com/en-us/library/czxefwt8(v=VS.85).aspx
Using a "helper" Java applet that reads a file or URL for your script
var fileContent='';
var theLocation='';
function readFileViaApplet(n) {
document.f1.t1.value='Reading in progress...';
document.ReadURL.readFile(theLocation);
setTimeout("showFileContent()",100);
}
function showFileContent() {
if (document.ReadURL.finished==0) {
setTimeout("showFileContent()",100);
return;
}
fileContent=document.ReadURL.fileContent;
document.form1.textarea1.value=fileContent;
}
Some other source to reference: http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm (many examples).
Just write a javascript file (js file) and include with the script tags.
This file will have your data like that.
<script type="text/javascript" src="data.js" >
where data.js can be..
var data[];
data[0]="something";
e.t.c
In your page (the one that calls data.js) the array data will be accessible.

How to read a text file from server using JavaScript?

On the server, there is a text file. Using JavaScript on the client, I want to be able to read this file and process it. The format of the file on the server cannot be changed.
How can I get the contents of the file into JavaScript variables, so I can do this processing? The size of the file can be up to 3.5 MB, but it could easily be processed in chunks of, say, 100 lines (1 line is 50-100 chars).
None of the contents of the file should be visible to the user; he will see the results of the processing of the data in the file.
You can use hidden frame, load the file in there and parse its contents.
HTML:
<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>
JavaScript:
<script type="text/javascript">
function LoadFile() {
var oFrame = document.getElementById("frmFile");
var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
while (strRawContents.indexOf("\r") >= 0)
strRawContents = strRawContents.replace("\r", "");
var arrLines = strRawContents.split("\n");
alert("File " + oFrame.src + " has " + arrLines.length + " lines");
for (var i = 0; i < arrLines.length; i++) {
var curLine = arrLines[i];
alert("Line #" + (i + 1) + " is: '" + curLine + "'");
}
}
</script>
Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.
Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax() function.
<html><head>
<script src="jquery.js"></script>
<script>
getTxt = function (){
$.ajax({
url:'text.txt',
success: function (data){
//parse your data here
//you can split into lines using data.split('\n')
//an use regex functions to effectively parse it
}
});
}
</script>
</head><body>
<button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button>
</body></html>
You need to use Ajax, which is basically sending a request to the server, then getting a JSON object, which you convert to a JavaScript object.
Check this:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
If you are using jQuery library, it can be even easier:
http://api.jquery.com/jQuery.ajax/
Having said this, I highly recommend you don't download a file of 3.5MB into JS! It is not a good idea. Do the processing on your server, then return the data after processing. Then if you want to get a new data, send a new Ajax request, process the request on server, then return the new data.
Hope that helps.
I used Rafid's suggestion of using AJAX.
This worked for me:
var url = "http://www.example.com/file.json";
var jsonFile = new XMLHttpRequest();
jsonFile.open("GET",url,true);
jsonFile.send();
jsonFile.onreadystatechange = function() {
if (jsonFile.readyState== 4 && jsonFile.status == 200) {
document.getElementById("id-of-element").innerHTML = jsonFile.responseText;
}
}
I basically(almost literally) copied this code from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2 so credit to them for everything.
I dont have much knowledge of how this works but you don't have to know how your brakes work to use them ;)
Hope this helps!
It looks like XMLHttpRequest has been replaced by the Fetch API. Google published a good introduction that includes this example doing what you want:
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
However, you probably want to call response.text() instead of response.json().
Just a small point, I see some of the answers using innerhtml. I have toyed with a similar idea but decided not too, In the latest version react version the same process is now called dangerouslyinnerhtml, as you are giving your client a way into your OS by presenting html in the app. This could lead to various attacks as well as SQL injection attempts
You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status and if it is from web server it returns the status)
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
For device file readuing use this:
readTextFile("file:///C:/your/path/to/file.txt");
For file reading from server use:
readTextFile("http://test/file.txt");
I really think your going about this in the wrong manner. Trying to download and parse a +3Mb text file is complete insanity. Why not parse the file on the server side, storing the results viva an ORM to a database(your choice, SQL is good but it also depends on the content key-value data works better on something like CouchDB) then use ajax to parse data on the client end.
Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.

Categories