Calling a .php document in JavaScript using Django Framework - javascript

I'm wondering if this is Django URLs issue. I am following [a Google Tutorial][1] to pop down markers showing addresses on a Google Map pulled from a database using php and xml. I have wired up a .php to my PostgreSQL db okay and seem to be able to run the script and show all the addresses and details in the console (I believe this means the XML file is working too).
The Problem
The trouble I am having is on the JavaScript side: I am using downloadURL() function in my .js static file. And pointing the URL parameter to my .php file which is stored in my local directory:
var markerurl = 'testingland/www/xmlpgd.php'
downloadUrl(markerurl, function(data)
However when I test the script on my local development server (http://127.0.0.1:8000/cafe_list) it returns the following error:
http://127.0.0.1:8000/cafe_list/testingland/www/xmlpgd.php 404 (Not Found)
What I have tried
I have tried moving the xmlpgd.php file to different locations including templates, static and elsewhere. I have tried hosting it on Google Cloud (which returns a CORS error). I am at a loss and thinking maybe I need to wire it up to my urls.py file? I am just not sure whether this is the case or how to do this properly.
My Code
Here is my urls.py file:
urlpatterns = [
path('cafe_list/', views.cafes_home, name='cafes_home'),
url('electra/cafe_list/', views.cafe_list.as_view(), name='cafe_list'),
]
Here is my JS Code:
//loads map markers from database
function downloadUrl(url,callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
//get the markers from php file and adds them to map
var markerurl = 'testingland/www/xmlpgd.php';
downloadUrl(markerurl, function(data) {
var xml = parseXml(data);
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('location');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point
[1]: https://developers.google.com/maps/documentation/javascript/mysql-to-maps

Related

How to have access to a JSON file without declaring a variable reffering to it

I am working on a django project and want to have access in a JSON file in order to do a geolocation process with the data from the JSON to my template.
The JSON resides in project/static/test/data.js
And it has the below data:
var json= {"count":6,"next":null,"previous":null,"results":[{"title":"Name1","date":"2018-10-02","products":"","categories":"","client_id":{"id":500,"client_id":"3000-3333","title":"Name1","lat":"40.2323","lng":"34.232323","address":"address1","address_no":"","region":"region1","tk":"34343","municipality":"municipality1","department":"department1","description":null,"categories":null,"phone":"2323232332"},"pcategory":"","product_team":""},{"title":Name2....
My script in my template resides in project/templates/test/test_template_json.html
And it has the below script:
<script>
// Initialize and add the map
function initMap() {
var map = new google.maps.Map(
document.getElementById('map'), {
zoom:8,
center: new google.maps.LatLng(37.232323,23.72752323239)
});
//json is the whole document and results is the list with the json objects
for (var x in json.results){
var client=json.results[x].client_id;
var location =new google.maps.LatLng(client.lat,client.lng);
var marker=new google.maps.Marker({
position:location,
map:map});
}
}
</script>
If i use the variable: var json={"count":6,"next":null,.... };
in my data.js file for accessing my json i do not have any problem.
But I want not to declare the var json and still be able to access my json in the test_template_json.html file.
In other words how can i access my json if this has the format:
{"count":6,"next":null,"previous":null,"results":[{"title":...
How can I do it? Any ideas?
Finally after a research period I came up to a solution that worked.The below snippets are in Javascript.
Step 1) Define a XMLHttpRequest object and pass into the open() function the path referring to the json.
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
// xobj.open('GET', '/static/test/download2.json', true);
xobj.open('GET', 'path/path..../path', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
Step 2) Parse the response from loadJSON with JSON.parse(response) , so now you have access to the json data through a javascript variable(var actual_JSON).
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
for (var x in actual_JSON){
var client=actual_JSON[x].client_id;
var location =new google.maps.LatLng(client.lat,client.lng);
var marker=new google.maps.Marker({
position:location,
map:map});
}
});
Then you can easily access the data using a for loop.
A useful article on loading a json file can be found here:https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript

Failing to load CSV data through Omnivore

I am trying to load a CSV file, convert it to GeoJSON, add an empty geoJson layer and then adding data to that geoJson layer. Why is it not working?
var locations = 'locations.csv';
var x = omnivore.csv(locations);
var geojsonLayer = L.geoJson().addTo(map);
geojsonLayer.addData(x);
omnivore.csv returns a layer built with the loaded data, not the underlying GeoJSON object.
Try
var geojsonLayer = omnivore.csv(locations);
geojsonLayer.addTo(map);
Or build your layer and pass it to omnivore.csv:
var geojsonLayer = L.geoJson().addTo(map);
omnivore.csv('locations.csv', null, geojsonLayer);
Or ditch omnivore and use csv2geojson to load your data before populating your layer :
var geojsonLayer = L.geoJson().addTo(map);
xhr = new XMLHttpRequest();
xhr.onload = function() {
csv2geojson.csv2geojson(this.responseText, {}, function(err, data) {
geojsonLayer.addData(data);
});
};
xhr.open('GET', 'locations.csv', true);
xhr.send(null);

How to generate <a> list from published layers in Geoserver?

I am building a webmapping app. I parse the WMS request to have the title of each layer in layers:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8082/geoserver/wms?service=wms&request=GetCapabilities', true);
xhr.onload = function() {
var parser = new ol.format.WMSCapabilities();
var capabilities = parser.read(xhr.responseText);
var layers = capabilities.Capability.Layer.Layer.Title;
};
But then I fail to access to the titles contain in layers:
$.each(layers, function(i)
{
var list = $('</br><a/>')
.text(layers[i])
.appendTo($('div.myDiv'));
});
What did I miss? Thanx for the help.
I think the problem is, that you need the Name of the Layer, not the Title to be able to call it.
So you would parse the capabilities like this:
var layers = capabilities.Capability.Layer.Layer.Name;

Generate a blob with grunt which will be available to JS in var

I need to embed a Flash .swf on the page and am unable use the normal way of setting the src or data attribute to the swf url - don't ask :s. So, I'm doing an ajax request for the swf, converting to a blob and then generating a blob url which I set as the swf src. Then I realised that as I'm building with Grunt, there may be a way to just write the swf file into the code as a blob in a var, and avoid the ajax request completely. Here's the code with the ajax request:
function createFlashMovie(blobUrl){
var obj = document.createElement("object");
obj.setAttribute("width", "800");
obj.setAttribute("height", "600");
obj.setAttribute("type", "application/x-shockwave-flash");
obj.setAttribute("data", blobUrl);
document.body.appendChild(obj);
}
function onAjaxLoad(oResponse){
blobUrl = window.URL.createObjectURL(oResponse);
createFlashMovie(blobUrl);
};
//do the xhr request for a.swf
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
onAjaxLoad(this.response);
}
}
xhr.open('GET', '//theserver.com/a.swf');
xhr.responseType = 'blob';
xhr.send();
...but I'm sure it must be possible to have something like this which is replaced by grunt to have the blob already available when it runs, and go straight to creating the blob url without the xhr request:
var theBlob = new Blob(["GRUNT_WRITES_THIS_IN_FROM_FILE"], {type: "application/x-shockwave-flash"});
Well, grunt is at its core just a Node program, so you can use any node command in your Gruntfile or tasks definitions. And it seems that Node's http.request would be perfect for your needs.
So:
add a custom task in your Gruntfile (http://gruntjs.com/creating-tasks#custom-tasks)
that uses http.request to download your swf (https://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request)
update your code to use the local swf
I found a solution. Convert your swf file to be a base64-encoded string. At the moment I'm doing this separately and then pasting it into the source JS, but it can be automated at build time with grunt. Then in the page script create a var to store it as a dataURI:
var swfAsDataUri = "data:application/x-shockwave-flash;base64,BIG_LONG_CHUNK_OF_DATA_THAT_IS_YOUR_ENCODED_SWF_FILE__GRUNT_CAN_WRITE_THIS_IN_AT_BUILD_TIME";
Create a blob from the data url, and then create an object url from the blob:
//function taken from http://stackoverflow.com/questions/27159179/how-to-convert-blob-to-file-in-javascript
dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
};
var blobUrl = window.URL.createObjectURL( dataURLToBlob(swfAsDataUri) );
You can then use the object url as the src data for the flash movie's object tag when it's embedded:
function createFlashMovie(blobUrl){
var obj = document.createElement("object");
obj.setAttribute("width", "800");
obj.setAttribute("height", "600");
obj.setAttribute("type", "application/x-shockwave-flash");
obj.setAttribute("data", blobUrl); //use the object url here
document.body.appendChild(obj);
}
...and there you have it, no additional http request for the swf file.

reading a text file line by line using javascript

I am trying to read in lines from a text file that are in this form;
34.925,150.977
35.012,151.034
34.887,150.905
I am currently trying to use this methodology, which obviously isn't working. Any help would be appreciated.
var ltlng = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "C:\Gmap\LatLong\Coordinates.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) { // Makes sure it's found the file.
lines = txtFile.responseText.split("\n"); // separate each line into an array
ltlng.push(new google.maps.LatLng(lines.split(",")[0],lines.split(",")[1]); //create the marker icons latlong array
}
}
}
XMLHttpRequest works when resources are called by HTTP/S protocol (and not file protocol, as in your example)
So to make your code work, you should try this code along with a web server

Categories

Resources