I am using this tutorial to help me with rendering a tiled map. I want to try this example but CORS seems to be stopping me on the local side. It is not my main issue though, because i need to use dynamic JSON data, instead of directly including the json file. The relevant code is like this :
....
renderLayers: function(layers) {
layers = $.isArray(layers) ? layers : this.data.layers;
layers.forEach(this.renderLayer);
},
loadTileset: function(json) {
this.data = json;
this.tileset = $("<img />", { src: json.tilesets[0].image })[0]
this.tileset.onload = $.proxy(this.renderLayers, this);
},
load: function(name) {
return $.ajax({
url: "mountain.json",
type: "JSON"
}).done($.proxy(this.loadTileset, this));
}
};
scene.load("mountain");
Ideally, i would want to have a var that holds the whole json object and change the above method to support that. I tried a few things, but i lack jquery knowledge, so i think i kinda messed this.
Please notice that the sample gist is here :
https://gist.github.com/shaneriley/4078905
Could anyone help me with how i would go about directly using the json object instead of including the json file ? Thanks !
Related
I'm trying to use Mozilla Readability stand-alone library for a personal project I am currently developing. The idea is to pass Mozilla Readability a document element and that after some parsing magic it returns the document's title, author, text, etc.
So, the first thing is dealing with how to get the HTML source of an external URL. I have dealt with that using an internal PHP file, which retrieves this external URL's source code.
After that, I call an AJAX GET to process the data returned by my PHP file. However, I am having lots of problems to convert this HTML source into an actual Javascript document element to pass to Mozilla Readability.
This is the code that I am currently using:
$('#btn_fetch').on('click', function() {
var url = 'https://www.rtl.be/info/monde/france/pierre-bellemare-s-est-eteint-a-88-ans-1025563.aspx';
$.ajax({
type: "GET",
url: 'fetchurl.php',
data: {
url: url
},
dataType: "html"
})
.done(function(data) {
var doc = document.implementation.createHTMLDocument("New Document");
// i don't know how to add "data" into "doc" element !
var article = new Readability(doc).parse();
alert(article.title);
})
.fail(function(xhr, ajaxOptions, thrownError) {
alert('Error:' . thrownError);
});
});
I just discovered it was actually very easy. The line I was missing was...
doc.body.parentElement.innerHTML = data;
it should be added here in the .done function
.done(function(data) {
var doc = document.implementation.createHTMLDocument("New Document");
// you need to add it here
doc.body.parentElement.innerHTML = data;
var article = new Readability(doc).parse();
alert(article.title);
})
I am struggling with getting data from WFS in my GeoServer. I want to get specific properties from the JSON returned by WFS and use it in my html page filling a table. I have read lots of posts and documentation but I can't seem to make it work. I have:
(a) changed the web.inf file in my geoserver folder to enable jsonp
(b) tried combinations of outputFormat (json or text/javascript)
(c) tried different ways to parse the JSON (use . or [], JSON.parse or parseJSON etc),
(d) used JSON.stringify to test whether the ajax call works correctly (it does!!)
but, in the end, it always returns undefined!!
function wfs(longitude, latitude){
function getJson(data) {
var myVar1=data['avgtemp1'];
document.getElementById("v1").innerHTML = myVar;
}
var JsonUrl = "http://88.99.13.199:8080/geoserver/agristats/wfs?service=wfs&version=2.0.0&request=GetFeature&typeNames=agristats:beekeeping&cql_filter=INTERSECTS(geom,POINT(" + longitude + " " + latitude + "))&outputFormat=text/javascript&format_options=callback:getJson";
$.ajax({
type: 'GET',
url: JsonUrl,
dataType: 'jsonp',
jsonpCallback:'getJson',
success: getJson
});
}
wfs(38, 23);
Could you please help me?
You are close to it. First, you have a typo in the variable name you are writing (myVar1 vs myVar). Secondly, your function is receiving a Json object, so you must dive into its structure. First you get the features, then the 1st one, then the property array, then the property of your choice.
I suggest you read a tutorial on Json Objects, as you will surely want to loop through properties/items, validate they are not null etc.
function getJson(data) {
var myVar1=data.features[0].properties['avgtemp1'];
document.getElementById("v1").innerHTML = myVar1;
}
At last, don't forget to use the debugger in your favorite browser. put a breakpoint in your function and check the structure and content of data.
TL;DR: Any good examples of using AJAX, d3 and PHP to get data from a database and produce graphs from it would be greatly appreciated.
So I'm using d3 to create a force chart based on data pulled from a database using AJAX and PHP, I think there's a few ways to do this, either binding the data to a DOM element, or using D3.queue seem to be the most logical ways to do it, but I'm struggling to find simple examples of using all these bits together.
So my working AJAX request looks like this:
$(document).ready(function() {
$('select[name="locations"]').change(function(){
var location = $(this).val();
$.ajax({
type: 'POST',
url: 'dataselect.php',
data: { l_id: location },
success: function (response) {
console.log(response);
},
});
});
});
I've tried passing the JSON to a DOM element, but no luck extracting it and some people seem to dislike this approach.
The d3 that works looks like this:
d3.json("test.php", function(error, graph) {
if (error) throw error;... Lots more d3 that I don't think is relevant.
test.php and dataselect.php are identical except dataselect has a variable for the AJAX request and the d3 doesn't like it as it is.
So, my question is what is the smoothest way for d3 to "wait" for the data from the AJAX request before running?
I'm guessing I need to wrap some stuff in functions and queue it into some kind of order, but I'm really struggling to tie it together.
Finally, sorry I feel like this should be fairly trivial, but I have read a lot of questions and haven't managed to implement any solutions so far.
EDIT: So following the d3.request route, I've figured out how to send the data without AJAX:
d3.selectAll("#onploc")
.on('change', function() {
var location = eval(d3.select(this).property('value'));
console.log(location);//gets value property of selected menu item.
d3.json("dataselect.php?l_id="+location,function(error, data) {
console.log(data);//sends location variable to php to get data back.
})
});
This could go either way - you could either call the d3 drawing code from your success callback, e.g.
...
success: function(response) {
var data = JSON.parse(response) // maybe, if you need to convert to JSON
d3RenderFunction(data);
}
or you could pass the parameters using d3.request:
d3.request('dataselect.php')
.mimeType("application/json")
.response(function(xhr) { return JSON.parse(xhr.responseText); })
.post({ l_id: location }, function(error, graph) { ... })
I am using backbone for the first time and I am really struggling to get it to function correctly with a JSON data file.
I have a model Like so:
window.Test = Backbone.Model.extend({
defaults: {
id: null,
name: null,
},
url: function() {
return 'json/test.json/this.id';
},
initialize: function(){
}
});
When a test item is clicked I then try to bring up the details of the pacific model that was clicked by doing
testDetails: function (id) {
var test = new Test();
test.id = id;
test.fetch({ success: function(data) { alert(JSON.stringify(data))}});
},
However this does not work, I am unable to correctly say "get the JSON element with the passed ID"
Can anyone please show me how to correctly structure the models URL to pull the element with the ID.
Thanks
The problem here is that you're treating your JSON data file like a call to a server. That won't work and it's the reason you're getting a 404. If you're accessing a file locally, you have to load the file first. You can do this with jQuery using the .getJSON() method, or if the file's static, just load it into memory with a script block (though you'll probably need to assign a var in the file). Most likely, you'll use jQuery. An example of this can be found here:
Using Jquery to get JSON objects from local file.
If this is an array of JSON, you can load the array into a collection, and use the "at" method to access the particular element by id. If it's entirely JSON, you'll have to create a custom parser.
your url is incorrect for one. you are returning the literal string 'this.id'. you probably want to do something more along the lines of
url: function () {
return 'json/test.json/' + this.id;
}
I would start by fixing your url function:
url: function() {
return 'json/test.json/' + this.get('id');
}
The way you have it now, every fetch request, regardless of the model's id, is going to /json/test.json/test.id
I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.