I'm answering a certain request to my Django server with a JSON object:
return HttpResponse(json.dumps(geojson), mimetype="application/json")
But I don't know how to get it at the HTML/javascript. I have gone through lots of similar questions and tutorials, but they all start defining an string variable with an example of JSON to use it. But I haven't been able to find how to get the JSON the server is answering me.
Any help or tutorial link?
EDIT: I tried using jQuery.ajax as suggested, but the function is never being executed:
Content of map-config.js:
var jsondata;
var lon = 5;
var lat = 40;
var zoom = 5;
var map, layer;
function init(){
map = new OpenLayers.Map( 'map' );
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0",
{layers: 'basic'} );
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
var geojson_format = new OpenLayers.Format.GeoJSON();
var vector_layer = new OpenLayers.Layer.Vector();
map.addLayer(vector_layer);
vector_layer.addFeatures(geojson_format.read(jsondata)); // Feeding with the json directly
}
$.ajax({
url: "localhost:8000/form/",
type: "POST",
dataType: "json"
}).done(function (data) {
$("#dialog").dialog('Hello POST!');
console.log(data);
jsondata = data; // Saving JSON at a variable so it can be used with the map
});
I also have another js file for a form, which works properly. And the HTML file is this one:
<html>
<head>
<script src="{{STATIC_URL}}js/jquery-1.9.1.js"></script>
<script src="{{STATIC_URL}}js/jquery-ui-1.10.3.custom.js"></script>
<script src="{{STATIC_URL}}js/OpenLayers.js"></script>
<script src="{{STATIC_URL}}js/form.js"></script>
<script src="{{STATIC_URL}}js/map-config.js"></script>
<link rel="stylesheet" href="{{STATIC_URL}}css/jquery-ui-1.10.3.custom.css">
<link rel="stylesheet" href="{{STATIC_URL}}css/style.css" type="text/css">
</head>
<body onload="init()">
<div id="form" class="form-style">
<p>Start Date: <input type="text" id="id_startDate"></p>
<p>
<label for="amount">Interval:</label>
<input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>
<p> <div id="id_interval"></div> </p>
<p>
<button id="id_okButton">OK</button>
</p>
</p>
</div>
<div id="map" class="smallmap">
</body>
So, when the POST request is received with the json coming from server, the jQuery.ajax method should execute, and the map should show some data (draw polygons over it to be exact). That POST is arraiving OK as stated at FireBug (the snapshot is not showing the whole json object, which is big):
Did you serialize your object to json format ?
$.ajax({
url: //your_url,
type: "POST",
success: function (data) {
// write your parsing code..
}
},
error: function (err) {
}
});
exp json from w3schools.com
{
"people": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
parsing exp (in jquery ajax success function ):
$.each(data.people, function (i, person) {
console.log(person.firstName + " " + person.lastName)
});
You could use jQuery for the request on the browser side.
$.ajax({
url: "example.com/data",
dataType: "json"
}).done(function (data) {
// data is the javascript object from the json response
});
Edit: Linked to the wrong jQuery call.
See details
Related
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 );
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
So im trying to make a jquery request to kimono to get information from the api. I'm getting "unexpected token o" when i inspect element in the console in chrome.
Basically im way out of my depth here, I'm trying to get the text field pulled into a table The closest i got was pulling the whole json into the webpage.
Sam
<?php header('Access-Control-Allow-Origin: true'); ?>
<html>
<head>
<title></title>
</head>
<body>
<table border="1">
<tr>
<td>Title</td>
<td>Link</td>
</tr>
</table>
</body>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
url: 'https://www.kimonolabs.com/api/ca266cam?apikey=zdRSeNfI0Nnr8GJ9KgSbc6awtvvSyOYh',
success: function (data) {
var json = $.parseJSON(data);
for(var i =0;i < json.results.collection1.length;i++) {
var title = json.results.collection1[i].EventsUK.text;
var href = json.results.collection1[i].EventsUK.href;
$("table").append("<tr><td>"+title+"</td><td>"+href+"</td></tr>");
}
}
});
</script>
</html>
Thats my main php file! The Url link if clicked will show the json. Any ideas would be great. Pleas say its something simple.
Just change your ajax call like below,it worked for me.The problem seems to be related to $.parseJSON(data) line.The response you are receiving from server is already a javaScript Object,So no need to parse that.
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
url: 'https://www.kimonolabs.com/api/ca266cam?apikey=zdRSeNfI0Nnr8GJ9KgSbc6awtvvSyOYh',
success: function (json) {
//var json = $.parseJSON(data);
for(var i =0;i < json.results.collection1.length;i++) {
var title = json.results.collection1[i].EventsUK.text;
var href = json.results.collection1[i].EventsUK.href;
$("table").append("<tr><td>"+title+"</td><td>"+href+"</td></tr>");
}
},
error: function(error){
console.log(error);
}
});
I've been trying some code from here to achieve my goal but I haven't found the solution yet.
Goal: I have to get a JSON objects array from a web (through the URL) using GET method. I have to do that in Javascript or HTML. I have been trying in javascript with jquery and with ajax. The idea is when the webpage I'm making loads I have to get the JSON objects array. I would want to save the JSON objets array fetched in a string to manipulate it.
Example of JSON array that I have to get from http://www.example.com/example
[
{
"type": "1",
"id": "50a92047a88d8",
"title": "Real Madrid"
},
{
"type": "1",
"id": "500cbb1a5ef23",
"title": "Fernando Alonso"
}
]
When I run my code in the browser I always get no response.
These are some pieces of code I've tried:
HTML Code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link type = "text/css" rel = "stylesheet" href = "stylesheet.css"/>
</head>
<body onload = "httpGet('http://www.example.com/example')">
</body>
</html>
Javascript code
function httpGet(theUrl)
{
$.getJSON(theUrl, function(data)
{
$.each(data, function()
{
console.log(this['title']);
})
});
}
Other Javascript code
$.ajax(
{
url: theUrl,
type: 'GET',
dataType: 'json',
accept: 'application/json',
success: function(data)
{
console.log(data);
var objets= $.parseJSON(data);
$.each(objets, function(i, obj)
{
console.log(obj.title);
});
}
});
And I have prove a lot of code from here (stak overflow)...
Thank you very much and excuse me for my English.
Edit:
Some time ago I tried with stringify, but I don't really known how can it works.
I proved the following:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, true ); // I tried with true and with false
xmlHttp.send();
var answer= xmlHttp.responseText;
var str = JSON.stringify(answer);
console.log(str);
var jsonResponse = JSON.parse(str);
console.log(jsonResponse);
}
You can't fetch data cross domain with javascript, you have to put the data under your domain or using jsonp to get it, or just print it on the page.
I have found the solution to my problem with one line php code
<?php
echo file_get_contents("http://www.example.com/example");
?>
After that, I needed to reference the php file in the javascript file.
Finally I could access to the key-value pairs of the JSON objects array.
function httpGet()
{
$.getJSON('phpfile.php', function(data)
{
$.each(data, function(i, obj)
{
console.log("object: " + i + ", title: " + obj.title);
});
});
}
In the HTML file I modified the next line:
<body onload = "httpGet()">
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());