Procedure to request a JSON file or an XML file in the local host Using with JQuery

With Google Chrome: Need a local Server to request a file using AJAX with JQuery on the local host With Firefox: No need to set a local server to request a file using AJAX with JQuery on the local host

In order to host these pages locally I used MAMP’s local server. Using the local server was necessary because when introducing JQuery’s getJson function we encounter cross origin domain requests which are not allowed when not on a server.

/*use the JQuery function $.getJSON() to simply grab a JSON data file*/ function getJSON(){

$.getJSON("YelpOneBusinessJasonData.json", function(result){

jsondata = result;

processJson(jsondata);

});

}

/*set our corresponding html via our json objects*/ function processJson(data){

//Set name first

var name_html = document.getElementById('name');

name_html.innerText = data.name;

//Create our services and features table

replacement_html = "

";

for(i in data.attributes){ replacement_html += "

"

if(typeof data.attributes[i] == 'object'){

var vals = Object.values(data.attributes[i]);

var keys = Object.keys(data.attributes[i]);

for(j in vals){

if(vals[j] == true){

replacement_html += "

";

replacement_html += "

";

}

}

}else{

if(data.attributes[i] == true){

replacement_html += "

";

replacement_html += "

";

}

}

}

replacement_html += "

" + keys[j] + "
" + i + "
";

var services_html = document.getElementById('services');

services_html.innerHTML = replacement_html;

}

For XML, Consider using jQuery.parseXML

If you need to parse large XML documents that you may not be able to completely hold in memory, consider using a SAX style parser like this one: https://github.com/isaacs/sax-js/

function getXML(){ 116. var xhttp = new XMLHttpRequest(); 117. xhttp.onreadystatechange = function (){ 118. if (this .readyState == 4 && this .status == 200){ 119. processXML( this ); 120. } 121. } 122. xhttp.open("GET", "restaurant_menu.xml", true ); 123. xhttp.send(); 124. } 125.

126. function processXML(data){ 127. var parser = new DOMParser(); 128. var xml = parser.parseFromString(data.responseText, "text/xml"); 129. 130. //Process breakfast 131. var html = document.getElementById("breakfast"); 132. var tempHtml = tableCreator(xml, "BREAKFAST"); 133. html.innerHTML += tempHtml; 134. 135. //Process brunch 136. html = document.getElementById("brunch"); 137. tempHtml = tableCreator(xml, "BRUNCH"); 138. html.innerHTML += tempHtml; 139. 140. //Process lunch 141. html = document.getElementById("lunch"); 142. tempHtml = tableCreator(xml, "LUNCH"); 143. html.innerHTML += tempHtml; 144. 145. //Process dinner 146. html = document.getElementById("dinner"); 147. tempHtml

jQuery.parseXML( data ) Returns: XMLDocument Description: Parses a string into an XML document.

• version added: 1.5 jQuery.parseXML( data ) o data Type: String a well-formed XML string to be parsed jQuery.parseXML uses the native parsing function of the browser to create a valid XML Document. This document can then be passed to jQuery to create a typical jQuery object that can be traversed and manipulated. Example:

Create a jQuery object using an XML string and obtain the value of the title node.

1 2 3 4 jQuery.parseXML demo

5

6

7

8

9

10

11 24

25 26 27

28

29

30

jQuery.ajax( url [, settings ] ) Returns: jqXHR Description: Perform an asynchronous HTTP (Ajax) request.

• version added: 1.5 jQuery.ajax( url [, settings ] ) o url Type: String A string containing the URL to which the request is sent. o settings Type: PlainObject A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup() . See jQuery.ajax( settings ) below for a complete list of all settings. • version added: 1.0 jQuery.ajax( [settings ] ) o settings Type: PlainObject A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup() .  accepts (default: depends on DataType ) Type: PlainObject A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header. This header tells the server what kind of response it will accept in return. For example, the following defines a custom type mycustomtype to be sent with the request:

1 $.ajax({

2 accepts: {

3 mycustomtype: 'application/x-some-custom-type'

4 },

5 // Instructions for how to deserialize a `mycustomtype` 6 converters: { 7 'text mycustomtype' : function(result) { 8 // Do Stuff 9 return newresult; 10 }

11 },

12

13 // Expect a `mycustomtype` back from server

dataType: 'mycustomtype' 14 }); 15 16

Note: You will need to specify a complementary entry for this type in converters for this to work properly.  async (default: true ) Type: Boolean By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false . Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8 , the use of async: false with jqXHR ($.Deferred ) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() .  beforeSend Type: Function ( jqXHR jqXHR, PlainObject settings ) A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event . Returning false in the beforeSend function will cancel the request. As of jQuery 1.5 , the beforeSend option will be called regardless of the type of request.  cache (default: true, false for dataType 'script' and 'jsonp' ) Type: Boolean If set to false , it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.  complete Type: Function ( jqXHR jqXHR, String textStatus ) A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success" , "notmodified" , "nocontent" , "error" , "timeout" , "abort" , or "parsererror" ). As of jQuery 1.5 , the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event .  contents Type: PlainObject An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5 )  contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8' ) Type: Boolean or String When sending data to the server, use this content type. Default is "application/x-www- form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() , then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded , multipart/form-data , or text/plain will trigger the browser to send a preflight OPTIONS request to the server.  context Type: PlainObject This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ( $.ajaxSettings merged with the settings passed to $.ajax ). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

1 $.ajax({

2 url: "test.html" ,

3 context: document.body

4 }).done(function() {

$( this ).addClass( "done" ); 5 }); 6

 converters (default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} ) Type: PlainObject An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5 )  crossDomain (default: false for same-domain requests, true for cross-domain requests ) Type: Boolean If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true . This allows, for example, server-side redirection to another domain. (version added: 1.5 )  data

 dataType (default: Intelligent Guess (xml, json, script, or html) ) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:  "xml" : Returns a XML document that can be processed via jQuery.  "html" : Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.  "script" : Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, _=[TIMESTAMP] , to the URL unless the cache option is set to true . Note: This will turn POSTs into GETs for remote- domain requests.  "json" : Evaluates the response as JSON and returns a JavaScript object. Cross- domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)  "jsonp" : Loads in a JSON block using JSONP . Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]" , to the URL unless the cache option is set to true .  "text" : A plain text string. • multiple, space-separated values: As of jQuery 1.5 , jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml" . Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

• Sending Data to the Server

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

The data option can contain either a query string of the form key1=value1&key2=value2 , or an object of the form {key1: 'value1', key2: 'value2'} . If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false . The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

Examples:

Save some data to the server and notify the user once it's complete.

1

2

$.ajax({ 3 method: "POST" , url: "some.php" , 4 data: { name: "John" , location: "Boston" } }) 5 .done(function( msg ) { alert( "Data Saved: " + msg ); 6 });

7

8

Retrieve the latest version of an HTML page.

1

2 $.ajax({ 3 url: "test.html" , cache: false 4 }) .done(function( html ) { 5 $( "#results" ).append( html ); }); 6

7

Send an xml document as data to the server. By setting the processData option to false , the automatic conversion of data to strings is prevented. 1

2

var xmlDocument = [create xml document]; 3 var xmlRequest = $.ajax({ url: "page.php" , 4 processData: false, data: xmlDocument 5 });

6 xmlRequest.done( handleResponse );

7

8

Send an id as data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert the user.

1

2 var menuId = $( "ul.nav" ).first().attr( "id" ); var request = $.ajax({ 3 url: "script.php" , method: "POST" , 4 data: { id : menuId }, dataType: "html" 5 });

6 request.done(function( msg ) { $( "#log" ).html( msg ); 7 });

request.fail(function( jqXHR, textStatus ) { 8 alert( "Request failed: " + textStatus ); }); 9

Load and execute a JavaScript file.

1 $.ajax({

2 method: "GET" ,

3 url: "test.js" ,

4 dataType: "script"

}); 5

Problem:

I'm working on a offline version of a website using jQuery and some xml files. I'm running in to a problem in jQuery when I do a $.ajax call on an xml file jQuery throws a error.

When I look at the error I can tell its loading the XML file because its in the error's responceText property. It seems to work just fine in Firefox.

This is how my call looks

$.ajax({ type: "GET", url: "Modules/" + ModuleID + "/ModuleContent.xml", dataType: "xml", success: function(x) { xml = x; ProcessXML(); }, error: function(x) { alert(x.responceText); } }); When I run this on a web server it works just fine. Its only when I run it from the file itself when I have this problem. How I can make this work in IE? Need to Covert http://api.jquery.com/jQuery.ajax/

When loading XML files locally, e.g. a CD-ROM etc., the data received by Internet Explorer is plain-text, not text/xml. In this case, use the dataType parameter to load the xml file as text, and parse the returned data within the success function

$.ajax({ url: "data.xml", dataType: ($.browser.msie) ? "text" : "xml", success: function(data){ var xml; if (typeof data == "string") { xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = false; xml.loadXML(data); } else { xml = data; } // Returned data available in object "xml" } });

If you are planning to use NodeJS ,

See The best node module for XML parsing . I've used xml-stream and it works pretty well. For a cross-browser solution: Cross-Browser Javascript XML Parsing .

Regarding the 'talking to the browser', if in NodeJS, use fs module. Otherwise (browser), use the FileAPI (see https://scotch.io/tutorials/use-the-html5-file-api-to-work-with-files-locally-in-the- browser ) and then the crossbrowser solution above.

See the compatibility table for the FileAPI: http://caniuse.com/#feat=fileapi (all modern browsers)

The best node module for XML parsing you can try with xml2js . Its a simple XML to JavaScript object converter. It gets your xml converted to js object so that you can access them with ease.

Here are some other options

1. libxmljs 2. xml-stream 3. xmldoc 4. cheerio – implements a subset of core jQuery for XML (and HTML)

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat . Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc . They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp. Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Creating Hyperlinks to Files on the Local Hard Drive

Problem: I am creating a report in LabVIEW and I would like to have a hyperlink that opens a file on the local hard drive. I can create a link to a webpage, but what is the URL syntax for a file on the local machine?

Solution: The URL of a file on the local system is specified in the following format: file:///filepath/filename

Where filepath is the full path to the location of your file (e.g. C:/temp/myfolder/ ) and filename is the name of the file (e.g. mydoc.txt ).

For example, the URL for a file called mydoc.txt located in the temp folder on the C: drive would be: file:///C:/temp/mydoc.txt

If you are using the Report Generation Toolkit with LabVIEW, this URL is wired to the input of the Append Hypertext Link Anchor to Report.vi.

Using HTML5 File API

I recently came across a problem in a project that I was working on. I needed the user to be able to load an image into the browser, make a few edits to it, and then upload after they were pleased with the edits.

A more old fashioned way of doing this would be to:

• Upload your image via AJAX • Render the uploaded image in the browser • Make edits using JavaScript • Make another request with data on how to process the image and • Apply the changes on the server

Two trips to the server? That seemed inefficient to me so I researched a little bit more and discovered the HTML5 File API . # What is the HTML5 File API? The HTML5 File API allows you to create applications that let the user interact with files locally. Basically, you can load files and render them in the browser without actually having to upload the files. # 3 Main HTML5 File Objects There are three main objects that you need to know about to work with files locally:

File – A single file object with some metadata

FileList – Simply a list of file objects.

FileReader – An object to read files with a number of methods and event handlers to interact with them. # Accessing A File Using JavaScript A file list can be accessed when you select a file using an HTML file input. Here is some sample code to handle file inputs. We will console.log() so that we can see what the input is providing us.

Select a Single File

// detect a change in a file input with an id of “the-file-input” $("#the-file-input").change(function() { // will log a FileList object, view gifs below console .log(this. files ); });

Selecting Multiple Files

# Rendering the File in Browser

Now that we know how to access the FileList object, all that is left to do is to render the file in the browser. We do this by feeding one of the File objects into a FileReader to generate a local url that can be used as the src in an image element.

// render the image in our view function renderImage( file ) {

// generate a new FileReader object var reader = new FileReader();

// inject an image with the src url reader .onload = function( event ) { the_url = event .target .result $('#some_container_div').html("") }

// when the file is read it triggers the onload event above. reader .readAsDataURL( file ); }

// handle input changes $("#the-file-input").change(function() { console .log(this. files )

// grab the first image in the FileList object and pass it to the function renderImage(this. files [0]) });

With this simple code, we are able to grab and display an image without a trip to the server ! This is great since it lessens the load on our server when we have a giant amount of users uploading to our incredibly popular application.

Cross-Browser Javascript XML Parsing

Are there any cross-browser / cross-platform ways to parse XML files in Javascript?

The following will work in all major browsers, including IE 6: var parseXml; if (typeof window.DOMParser != "undefined") { parseXml = function(xmlStr) { return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml"); }; } else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) { parseXml = function(xmlStr) { var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xmlStr); return xmlDoc; }; } else { throw new Error("No XML parser found"); }

Example usage:

var xml = parseXml("Stuff"); alert(xml.documentElement.nodeName);

Live demo:

http://jsfiddle.net/3s7Ly/1/

Consider using jQuery.parseXML

If you need to parse large XML documents that you may not be able to completely hold in memory, consider using a SAX style parser like this one: https://github.com/isaacs/sax-js/

jQuery.parseXML( data ) Returns: XMLDocument Description: Parses a string into an XML document.

• version added: 1.5 jQuery.parseXML( data ) o data Type: String a well-formed XML string to be parsed jQuery.parseXML uses the native parsing function of the browser to create a valid XML Document. This document can then be passed to jQuery to create a typical jQuery object that can be traversed and manipulated. Example:

Create a jQuery object using an XML string and obtain the value of the title node. 1 2 3

4 jQuery.parseXML demo

5

6

7

8

9

10

11 24

25 26 27

28

29

30