Get JSON data from WFS/Geoserver - javascript

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.

Related

Ajax doesn't get to success function. Always error function. It fails to post data to another file

Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.

How can I iterate this json?

"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there

JSON returned from ASP.NET not usable in JS

I'm returning a DataSet converted to JSON via a jQuery AJAX call, all is well! The request I receive back is:
{"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]}
Looks valid to me, also ran it through JSLint validator, again, all is well! Now, whenever I try to access any of this data, I simply receive undefined from the following:
var dataObject = data.d //data.d is the response from the server and what is logged above
console.log(dataObject.Table) //undefined
console.log(dataObject["Table"]) //undefined
Now, if I run JSON.parse(dataObject), I can then access it alright. This is a problem right now however, since the site this will reside on sticks IE into IE7 mode, and JSON is always undefined according to IE (I know, IE7, it's out of my hands tho).
So my question is why can I not use the returned JSON as is? why must I run it through JSON.parse before using it? More info is available on request (AJAX call, DataSet converter, etc)
AJAX Call, per request:
$.ajax({
type: "POST",
url: "DBManager.asmx/GetAdminList",
contentType: 'application/json',
data: '{"strEmail": "' + strFilter + '" }',
dataType: "json",
success: function (data) {
console.log(data.d); //valid JSON response.
}
});
If you returning back a string you have to somehow parse it into an object. E.g.
var data = '{"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]}';
var dataJ
eval('dataJ = ' + data )
alert(dataJ.Table)
http://jsfiddle.net/uvvAm/
If you're using jQuery you can use
var dataJ = $.parseJSON(data);
This is preferable, since eval is open to all kinds of attacks.
var dataObject = eval('(' + data + ')');
alert(dataObject.Table);
Try this thing may help you.

Rendering mongodb database results from POST request in .ajax jquery wrapper in node js

I am creating a basic piece of functionality to allow users to send their location to a server which then queries a database and returns locations near to them. I am using the below jQuery .ajax wrapper to POST data to the server. This takes the form of a latlon point which is then used as the basis for a geosearch in MongoDB using nodejs and express on the backend. The results of the search are then intended to be returned to the client and rendered by the createMapListings function.
The /find page is initially rendered through a GET request to the database via mongodb separate from the below code. However subsequent to initial rendering, I then want to return results dependent on the location provided.
The POST method works fine and the location is posted to the server, with the search results being returned as I can print contents out through the console log.
However, I then want to render the results on the client-side. As mentioned, the results of the search render in the console, but when I attempt to pass through to the client, I can render the data itself (in the form of an array of objects) in the #output div, but the createMapListings function does not seem to catch the data.
In fact, the below function appears to be called but prints out over a thousand rows with the data that should be caught described as 'undefined'. I have tried to use res.render and res.redirect, but in the first case, the view renders in the div (which I suppose is expected) and the redirect fails.
The createMapListings function works fine when a simple GET request is made to the server, for example, for all objects in a collection, using ejs template. However, I think the issue here may be a combination of a POST request and then wanting to pass the results back to the AJAX request using the complete callback.
I apologise if the below code is somewhat obtuse. I’m definitely what you would call a beginner. I appreciate the above functionality may not possible so if there is a better way, I would of course be open to it (res.direct perhaps).
Here is the relevant client side script:
$(document).ready(function(){
$("#geolocate").click(function(){
navigator.geolocation.getCurrentPosition(geolocate, function(){
});
});
});
function geolocate(pos){
var latlonpt = [];
var x = pos.coords.latitude;
var y = pos.coords.longitude;
latlonpt.push(x);
latlonpt.push(y);
var obj = {
userlocation: latitudelongitudept
};
$.ajax({
url: "/find",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(obj),
complete: function (data) {
$('#output').html(data.responseText);
$('#infooutput').children().remove();
createMapListings(data.responseText);
}
});
};
function createMapListings(maps) {
for (var i = 0; i < maps.length; i++) {
var url = maps[i]._id;
var fullurl = "<a href='/show?id=" + url + "'>Route</a></div>";
var title = "<div>" + maps[i].title + " - " + fullurl +"";
$('#infooutput').append(title);
};
};
</script>
Here is the relevant route used in a basic express app to handle the post request made by the above .ajax wrapper.
exports.findbylocation = function(req, res) {
console.log(req.body.userlocation);
var userlocation = req.body.userlocation;
Map.ensureIndexes;
Map.find({loc :{ $near : userlocation }}, function(err, maps) {
if (err) {
console.log(err)
}
else {
var jmaps = JSON.stringify(maps);
console.log(jmaps);
res.send(jmaps);
}
});
};
By convention, the data variable name in an $.ajax callback signature refers to the parsed HTTP response body. Since your callback is on complete, we're actually passed the XMLHttpRequest used, by convention called xhr. You rightly grab the responseText property, but this needs parsing to be useful. So long as we take care over our Content-Type's and don't explicitly disable processData, jQuery will do the encoding/unencoding for us - we just deal with objects. This is a good thing, since the transport format isn't usually of any particular importance to the application logic. If we use res.json(maps) in place of res.send(jmaps), we can write our call more simply:
$.ajax({
url: '/find',
type: 'POST',
data: obj,
success: function(data) {},
error: function(xhr, text, err) {}
});
Here data is a Javascript object already parsed and ready to use. We also use a default application/x-www-form-urlencoded request rather than explicitly setting a contentType. This is the same as far as express is concerned: it will just be parsed by urlencoded instead of json.
Assuming you solved your client-sie problem.
As you are using express there is no need for JSON.stringfy,
you can use res.json(maps).

pass array and individual string to php file using ajax call

I try to implement the following code
var flag = new Array();
var name = $("#myselectedset").val();
$.ajax({
type: 'post',
cache: false,
url: 'moveto.php',
data: {'myselectset' : name,
'my_flag' : flag
},
success: function(msg){
$("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
}
});
You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks
It is impossible to pass arrays in a POST request. Only strings.
You will either need to stringify your array, or consider posting as JSON instead.
You should be able to do something quite simple, like replace your "data" property with:
data : JSON.stringify( { myselectset : name, my_flag : flag } )
That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);
Very important note:
For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.
Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.

Categories

Resources