load json data into js - javascript

I am learning how to load json data into .js file. I have created a employee.json file. I saved my js and json file and on the desktop. What I trying to do is to put all the id in json files into an array in the js. I do not know what could be wrong. Hope someone could help me out. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON with jQuery</title>
</head>
<body>
<p id="demo"></p>
<h1><h2>
<script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
}
});
document.getElementById("demo").innerHTML = res.toString();
</script>
</body>
</html>
{
"person": [
{
"id" : 1,
"firstName" : "Lokesh"
},
{
"id" : 2,
"firstName" : "bryant"
}
{
"id" : 3,
"firstName" : "kobe"
}
]
}

Error 1: Typing error. <script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>. You mistyped the src of the script, accidentally adding another another <script> start tag.
Error 2: Misplaced statement. document.getElementById("demo").innerHTML = res.toString(); should be placed in the success callback function, so it will be executed only after the server responds. If it executes prematurely, res will still be [].
Error 3: type: 'GET' should be method: 'GET', according to the docs (though 'GET' is default so you don't need to explicitly write this).
Use this:
<p id="demo"></p>
<h1><h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>

You can't use the local json to read. it gives cross origin request failure. so deploy both the files (html and json) into a we server and execute. or place the json data onto some web url(http://somesite/myjson) and then request that url and see.

First of all, the JSON shouldn't be existed as in physical "file". It has to be generated by a backend language / web service etc. The JSON tags inside a manually created "file" have high chance of data invalidity upon parsing.
Solution
Use a Web Service to generate valid JSON output. And from Javascript end, use:
JSON.stringify( data );

Related

Requesting JSON from server and parsing in Javascript

I am trying to pull json down from my server and parse it into a Javascript object. here is what my json looks like:
{
"tour1": [
{
"title": "building1",
"description": "Tour of building1",
"image": "Icon.png",
"video": "tour.mp4",
"length": "0.00",
"version": "1.0",
"timestamp": "1111111111"
}
]
}
Here is the requst to the server:
<!DOCTYPE html>
<html>
<body>
<h2>Parse JSON from Server</h2>
<p id="demo"></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
$.ajax({
url: "mysite.com/videos/tour.json";
var j = [];
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
});
window.alert(j.tour1[0].title);
</script>
</body>
</html>
I cant understand why its not working. I am new to javascript. I appreciate any help with this issue.
I think better if you use getJson when you want to load JSON-encoded data from the server using a GET HTTP request, check example bellow :
$.getJSON( "mysite.com/videos/tour.json", function( j ) {
alert( j.tour1[0].title );
});
Hope this helps.
Ajax call is an asynchronous call, j is not populated as soon as your ajax statement ends.
Use success handler of Ajax to alert the j (didn't tested the code)
$.ajax({
url: "mysite.com/videos/tour.json",
method: "GET",
dataType: "JSON",
success: function( data ){
window.alert(data.tour1[0].title);
}
});
gurvinder give the best solution, because if you are firing the ajax-request then you must catch the response, but if you make the alert in your code your request is still working and j must be undefined because it is not a global variable.
there a lot of mistakes:
check your ajax-synthax , because the declaration of "var j.." is wrong,
never use ";" in a object declaration, always use ","
in your alert you try to find a variable "j", but j don't exist, it is undefined.

how to print data sent by ajax post method in javascript

I need to post data and display it also. I am using ajax post method. I am able to get the event Id where data is saved, but not able to display the data. I searched a lot and got some answer also. I tried it in my code, but didn't got the result. My code is:
<!DOCTYPE html>
<html>
<head>
<title>POST API</title>
<script type="text/javascript" src="http://ajax.googleapis.com /ajax/libs /jquery/1.2.6/jquery.js"></script>
</head>
<body>
<button id="btn1">Check HTTP POST</button>
<p>Display sample output from POST API:</p>
<p id="one" />wEventId :
<p id="two" />
<script>
$(document).ready(function() {
$("#btn1").click(function() {
$.ajax({
url: 'url',
dataType: 'json',
type: 'POST',
crossDomain: true,
contentType: 'application/json',
data: {},
success: function(data) {
console.log(data);
document.getElementById("two").innerHTML = data.result.wEventId;
},
failure: function(errMsg) {
console.log(errMsg);
}
var myData = data;
myData = new Array;
});
});
});
</script>
</body>
</html>
Anyone please help me how to modify the code to print the data saved. I have not given the url as it is an internal server and supposed not to disclose it. Thanks in advance.
First I need to know, what is the structure of your json data.
Assuming that it is in a format like given below:
{"field_A":"value_a","field_b":"value_b"}
your code where you are trying to print as innerHTML should be like this:
success: function(data)
{
console.log(data);
document.getElementById("two").innerHTML = data.field_A;
},
Try to adjust accordingly.
I am still surprised from where are you getting the result of data.result.wEventId

How to get plain xml from file

I search for a method to get plain xml(with tags ect.) from a file and save it so the localStorage.
I found a few opportunities, but every one of them returns the xml without tags. I prefer jQuery to do this...
I tried $.get, $("").load() and AJAX but I don't get it. I just want to save the whole xml as string into the localStorage and read it out later (and work with it).
Does anyone have a idea?
Regards
You can use:
$.ajax({
url: 'http://example.com',
dataType: 'text',
success: function (data) {
localStorage.setItem('xml-content', data);
}
});
This will provide you the XML document as plain text and save it to the localStorage.
Here is a full solution:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<pre id="output">
</pre>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function setXML() {
$.ajax({
url: 'test.xml',
dataType: 'text',
success: function (data) {
localStorage.setItem('xml-content', data);
getXML();
}
});
}
function getXML() {
var xml = localStorage.getItem('xml-content');
$('#output').text(xml);
}
setXML();
</script>
</body>
</html>

Parsing xml data from a remote website

I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = xml.city;
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website.
Note: I have also 'City' instead of 'city' but its not working...
Thanks in advance...
I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=json",
dataType: "jsonp",
success: function (data) {
document.myform.result1.value = data.city;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.
[HttpGet]
public ContentResult XmlExample()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
string xml = null;
using (WebResponse response = request.GetResponse())
{
using (var xmlStream = new StreamReader(response.GetResponseStream()))
{
xml = xmlStream.ReadToEnd();
}
}
return Content(xml, "text/xml");
}
Your xmlParser function will look like this:
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "XmlExample",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.
Make sure to replace the XmlExample with the url that it maps to based on your controller.
The solution is quite simple (mentioned in Pekka's comment)
1.On your server add a file IAD_proxy.php
2.Put the following code inside it
header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');
3.Change the url in your Ajax request to IAD_proxy.php.
In case you're using any other server-side language, try to implement the same idea.
Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.
Javscript:
$.ajax({
type: "GET",
url: "IAD_proxy.php",
dataType: "xml",
success: function (xml) {
alert($(xml).find('City').text());
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
Here I tried it with document.write($(xml).find('City').text());

How to keep consistency between two js files?

I have two html files (for add and edit) which contains js codes. These two files are identical except few js lines in its functions. Actually I don't like to have common code for both files. Is there a good way to handle this kind of situations ?
Example:
(file one)
<html>
<title>title goes here</title>
<javascript>
$('#button1').click(function () {
$.ajax({
type: "POST",
url: '/admin/test/checkcode',
data: {code:code, id:id}, // in here there is an id
async: false,
success: function(data){
}
});
}
</script>
<body>
</body>
</html>
(file two)
<html>
<title>title goes here</title>
<javascript>
$('#button1').click(function () {
$.ajax({
type: "POST",
url: '/admin/test/checkcode',
data: {code:code}, // in here there is no id
async: false,
success: function(data){
}
});
}
</script>
<body>
</body>
</html>
You may want to try putting that JavaScript code into a separate file. That way, you can just include the single JavaScript file into each of those pages... and only have to make changes to that one JavaScript file.
For reference, here is a way to include a JavaScript file:
<script type="text/javascript" src="javascript_file_here.js"></script>
Inside of that JavaScript file, there could be some type of basic function that takes parameters for that data value that is used in the $.ajax() call. For example, something like:
function example(data1, data2) {
// your code here
// then just check for data1 and data2 (etc.)
// to see what to include in the `data:`
}

Categories