I have a object district_boundaries which is leaflet geojson object
var district_boundary = new L.geoJson();
and the data is added through ajax call to a geojson file of district
$.ajax({
dataType: "json",
url: "data/district.geojson",
success: function(data) {
$(data.features).each(function(key, data) {
district_boundary.addData(data);
district_boundary.setStyle(district_boundary_styles["default"]);
});
}
});
So in the _layers there are 75 values, one example of such values is the one in the picture with key 149.
I need to loop through all these 75 values and get the values from features key. i.e the name of districts and use them to label the districts.
I tried with this
_test = district_boundary._layers;
for (var aht in _test) {
console.log('inside the loop');
var b = _test[aht];
console.log(b.feature.properties.NAME_3);
}
This works fine when tried in the console and shows the result
But when i tried with by running in the script of my page this doesnot work the though _test is populated with the values in district_boundary._layers, loop is not executed. What could be the reason can anyone please help me with this?
the output of msg and msg.d is
I am guessing your JSON data is getting wrapped in a d variable. Try the following -
$.ajax({
dataType: "json",
url: "data/district.geojson",
success: function(msg) {
//console.log(msg); //try this to see whether the data is really getting wrapped in d
var data = msg.d; //msg.d contains the actual data
$(data.features).each(function(key, data) {
district_boundary.addData(data);
district_boundary.setStyle(district_boundary_styles["default"]);
});
}
});
Solved. Everything in the code is fine except the flow of execution. I was trying to use the data which would be defined later according to the flow, so in the part of script where i tried to loop through _test it is not populated yet, but when i tried in console it was after all the data was loaded and hence it worked.
Related
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.
I'm trying to access some JSON data that I got through an ajax call. I'm not sure how to access this data now though. I want to extract the "test" portion out of the json. Could someone please help me out with this
Image of current output
code sample:
$(".test").on("click", function() {
var dialogID = $(this).attr("id");
console.log(dialogID);
$.ajax({
type: "GET",
url: "test.php?id=" + dialogID,
dataType: "json",
success: function(data) {
console.log(data);
},
error: function() {
console.log("error");
}
});
Assuming the ajax data is stored in a variable called 'data'
data['DATA'][0][0];
If you look at the developer console, you'll notice that 'test' in an item in array at index 0. That array is at index 0 of another array called DATA. DATA is an array in the object returned by the AJAX call.
You can see all the data types next to the variable names in the developer console, i.e 'COLUMNS: Array[1]' on the second line tells you that COLUMNS is an array of length 1.
I've made some code with jQuery that whenever I press a button I shall retrieve some information. This works fine with 3 of my tables, but of some reason that last table wont work.
My jQuery code looks like this
$.ajax({
url: "ajax.php",
type: "get",
datatype: "json",
success: function(data){
var parsed = jQuery.parseJSON(data);
$.each(parsed, function(i){
var oldhtml = $('p').html();
$("p").html(oldhtml + "<br>Name: " + parsed[i]['name']);
});
}
)};
So I have this connected to a button and an onclick function. So my PHP code echoes an associative array, and it works fine with my tables moment1, moment2, moment4. But whenever I try to use it on my table called konsult, I get syntax error.
"Unexpected end of JSON input at Function.parse [as parseJSON] (anonymous)".
It it something with my table or what is the problem? I use the same code to get info from the first tables. I only switch the tablename and instead of "parsed[i]['name']" I have "parsed[i]['titel']"
EDIT: It seems to be fixed. One of my cells had a "ö" which for some reason gave me syntax error.
I have a php file with a lot of checkboxes on the left hand side. I extract the values via javscript and pass them into an array. Which works just fine. I would like to pass then this array via Ajax to PHP in order to mess around with the values and create SQL-statements out of them.
$(document).ready(function(e) {
$('#getSelectedValues').click(function() {
var chkBoxArray = [];
$('.graphselectors:checked').each(function() {
chkBoxArray.push($(this).val());
});
for (var i = 0; i < chkBoxArray.length; i++) {
console.log(i + " = " + chkBoxArray[i]);
}
$.ajax({
url: 'index.php', // (1)
type: 'POST',
dataType:'json',
data: chkBoxArray, //(2)
success: function(data){
console.log(data.length);
console.log(data);
}
});
});
});
Several questions:
(1) what file name do I need to add here? The origion or the target?
(2) I have numerous ways of this: serialization, with these brackets {}, and so on. How to get it done right?
An error that I get is the following:
Notice: Undefined index: data in graph.php
That makes me wondering a bit, because it clearly shows no data is being send.
var_dumps on $_POST and $_SERVER offer these results:
array(0) { }
array(0) { }
which is somewhat unsatisfying.
Where am I doing things wrong? The only puzzling aspect is the ajax, all other stuff is not much of an issue.
The site is supposed to work in the following way:
Page -> Checkbox(clicked) -> Button -> result (ajax) -> PHP fetches result -> SQL DB -> PHP gets DB result -> fetch result (ajax) -> jslibrary uses result for something.
1- You need to point your ajax to the script that will use the data you are sending. I would not recommend to point to index.php, since you'll need to add a if statement checking if there is data on $_POST that is exactly what your're expecting, otherwise it will return the same page that you're in (considering that you are in index.php and is making a request to index.php). A point to consider. Since it is a whole request and it's not a method call to actually return something to your page you need to echo things. That said, consider also to set header('Content-Type: application/json') then, since you're expecting dataType: 'json', echo json_encode($objectorarray);
2- Since you're sending a Javascript array to PHP, it can't interpret correctly the structure, that is why you should use JSON.stringify(chkBoxArray) before sending it. But just setting it on data attribute would send the number of checkboxes you selected as values to POST, so consider to data: {myCheckboxValues: JSON.stringify(chkBoxArray)}
In your PHP script, considering all the security measures to take, you can $foo = json_decode($_POST['myCheckboxValues']);
Well, of course you need to pass the target page as url in your ajax call. It can't guess which file should process the data.
As for the data property. You need to give your data a name.
data: {
something: "something"
}
Becomes: $_POST['something']. (value: something)
$.ajax({
url: 'target.php', // (1)
type: 'POST',
dataType:'json',
data: { data: chkBoxArray }, //(2) Now $_POST['data'] will work
success: function(data){
console.log(data.length);
console.log(data);
}
});
I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.