0

I am currently getting the below syntax error whilst trying to send data to a PostGIS server and retrieve the data back to a Leaflet map:

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Object. (Geoserv2.js:185) at u (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at k (jquery.min.js:2) at XMLHttpRequest. (jquery.min.js:2) (anonymous) @ Geoserv2.js:185 u @ jquery.min.js:2 fireWith @ jquery.min.js:2 k @ jquery.min.js:2 (anonymous) @ jquery.min.js:2 load (async) send @ jquery.min.js:2 ajax @ jquery.min.js:2 (anonymous) @ Geoserv2.js:180 l @ jquery.min.js:2 c @ jquery.min.js:2 setTimeout (async) (anonymous) @ jquery.min.js:2 u @ jquery.min.js:2 fireWith @ jquery.min.js:2 fire @ jquery.min.js:2 u @ jquery.min.js:2 fireWith @ jquery.min.js:2 ready @ jquery.min.js:2 _ @ jquery.min.js:2

The code it is referencing is:

//knn feature
var kTable = 'geoupload.pubs';
var kColumn =["id", "p_name", "address1", "postcode", "local_authority"];
var kGeom = "geom";
var kLOC = "189349 307998";

//var klocy = "User location is " + test;

console.log(kLOC);
$(document).ready(function(){
    $.ajax({
        url: "knn.php",
        data:{ktable: kTable, kinclu: kColumn, kgeomy: kGeom, Loc: kLOC}
    })
    .done(function(data){
        knnPubsLay = L.geoJSON(JSON.parse(data),{
            pointToLayer: function (feature, latlng){
                return L.circleMarker(latlng,nearStyle);
        }});
        console.log("after " + kLOC);
        pub_map.addLayer(knnPubsLay);

    })
});

I believe it is some kind of issue whilst parsing the data back to the function, however, I know this to work for a previous statement in the same document WORKING EXAMPLE:

$(document).ready(function(){
    $.ajax({
        url: "pub.php",
        data:{table: pTable, inclu: pColumn, geomy: pGeom}
    })
    .done(function(data){
        pubsLay = L.geoJSON(JSON.parse(data),{
            pointToLayer: function (feature, latlng){
                return L.circleMarker(latlng,markerOptions);
        }});
        pub_map.addLayer(pubsLay);
    })
});

The KNN.php file is as follows

<?php

//console error reporting:  0=off  1=on
ini_set('display_errors', 1); 
//to use Chrome Logger
include 'src/ChromePhp.php';
    
//** database login details **
$host = 'ces-gis';
$port = '5432';
$dbname = 's20';
$user = 's20';
$password = 'WnJh';

//attempt connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
    ChromePhp::error("...database knn connection FAILED" );
    exit;
}
ChromePhp::warn("knn connection worked");


//call tables for knn query although same as the previous I have changed the variable names to keep them seperate
    $ktable = $_GET['ktable'];
    $kinclu = $_GET['kinclu'];
    $kgeomy = $_GET['kgeomy'];
    $Loc = $GET['kloc'];
    
//substitutes
$fields = "";
    foreach ($kinclu as $i => $col) {
        $fields = $fields . $col . ", ";
    }
    $fields = $fields . $kgeomy;
    $geom = " - " . $kgeomy;


//knn query
$knn1 =
    "SELECT jsonb_build_object(
            'type',     'FeatureCollection',
            'features', jsonb_agg(feature))
    FROM (
        SELECT jsonb_build_object(
            'type',       'Feature',
            'geometry',   ST_AsGeoJSON(st_transform(geom,4326),4)::jsonb,
            'properties', to_jsonb(row) #omits#
        ) AS feature
        FROM (SELECT #fields# FROM #table# as K, st_geomfromtext('point(#location#)',4326) ORDER BY st_distance(K.geom, st_geomfromtext('point(#location#)',4326)) LIMIT 5) row) features;";

    //replace placeholders
    $knn2 = str_replace("#table#", $ktable, $knn1);
    $knn3 = str_replace("#fields#", $fields, $knn2);
    $knn4 = str_replace("#location#", $Loc, $knn3);
    $knn5 = str_replace("#omits#", $geom, $knn4);
    ChromePhp::log($knn5);

//execute query
if (!$response = pg_query($conn, $knn5)) {
    ChromePhp::error("*KNN script failed*");
    exit;
}
    
//return data
while ($row = pg_fetch_row($response)) {
    foreach ($row as $i => $attr){
        echo $attr;
    }
}
?>

Using Chrome logger I can see that the connection to the database is fine and stable but because the data does not come back the script comes back as a failed response as shown below.

Chrome logger error

Because of this error it is not passing the location through to the script and this is why the script fails. I have tried to even manually insert the location within the script within the PHP file and remove the kLOC part of the script as I belived passing 4 items may have been the issue but still nothing.

As said before I do know this works as the same script works above.

Full js file:

//Creating the map in map space
var pub_map;
var pubsLay;
var knnPubsLay;

//Marker styles
//Either get these using SLD or from geo server if possible 
        var markerOptions = {
            radius: 4,
            fillColor: '#FF6600',
            color: '#000',
            weight: 1,
            opacity: 1,
            fillOpacity: 0.4 }
            
        var ire_style = { 
            radius: 8,
            fillColor:'#00FF00',
            color: '#ffa500',
            weight: 1,
            opacity: 1,
            fillOpacity: 0.4 }
            
        var nearStyle = {
            radius: 4,
            fillColor:'#00FFFF',
            color: '#FF0000',
            weight: 1,
            opacity: 1,
        fillOpacity:0.4 }
        
        /*mark: symbol(cross);
        mark-size: 8px;
        :mark {
            fill:#00FF00;
            fill-opacity:0.4;
            stroke:#ffa500;
        }
        */
        var ire_invert = { 
            radius: 8,
            fillColor:'#ffa500',
            color: '#00FF00',
            weight: 1,
            opacity: 1,
            fillOpacity: 0.4 }
            
/* <style>{
  mark: symbol(triangle);
  mark-size: 8px;
  :mark {
    fill:#FF0608;
    fill-opacity:0.4;
    stroke:#080;
  }
}</style>
*/

//Base Map layer
var basetiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Tom Slater 18018815 &#169; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'});

//UK constituency layer WMS

//php mainland uk Pub Layer
//db sql feature calls
var pTable = 'geoupload.pubs';
var pIRETable = 'geoupload.Pubs_and_Clubs_in_Causeway_Coast_and_Glens NI';
var pColumn =["id", "p_name", "address1", "postcode", "local_authority"];
var pGeom = "geom";

$(document).ready(function(){
    $.ajax({
        url: "pub.php",
        data:{table: pTable, inclu: pColumn, geomy: pGeom}
    })
    .done(function(data){
        pubsLay = L.geoJSON(JSON.parse(data),{
            pointToLayer: function (feature, latlng){
                return L.circleMarker(latlng,markerOptions);
        }});
        pub_map.addLayer(pubsLay);
    })
});

//N IRE pub layer
var wfs_root = 'https://ces-gis.southwales.ac.uk:2345/geoserver/ows';
//wfs parameters
var WFSparam = {
    service:'WFS',
    version:'1.0.0',
    request:'GetFeature',
    typeName:'s20:Pubs_clubs_NI',
    outputFormat: 'text/javascript',
    format_options:'callback: getJson',
    srsName: 'EPSG:4326'
};

var GeoURL = wfs_root + L.Util.getParamString(WFSparam);

//Ajax script to get the WFS data
$(document).ready(function() {
    $.ajax({
        url: GeoURL,
        dataType: 'jsonp',
        jsonpCallback: 'getJson',
    })
    .done(function(data) {
        ire_pubs = L.geoJson(data, {
            pointToLayer: function(feature, latlng) {
            return L.circleMarker(latlng,ire_style) 
            },
            //ire_pubs popups
            onEachFeature: function(feature, layer) {
                popupOptions = {maxWidth: 300};
                var pophtml="Pubs/Clubs <br/>"
                + "Name: " + feature.properties["Name"] + "<br/>"
                + "Address: " + feature.properties["Address"] + "<br/>"
                + "Town: " + feature.properties["Town"] + "<br/>"
                + "Postcode: " + feature.properties["Postcode"] + "<br/>"
                + "Pub or Club?: " + feature.properties["Type_"] + "<br/>";
            layer.bindPopup(pophtml, popupOptions);
            }
        });
        pub_map.addLayer(ire_pubs);
    })
});


//Map instantiation and layer calls
pub_map = L.map('mapspce');
pub_map.setView([54.00, -2.54],5.5);
pub_map.addLayer(basetiles);

//User location
var Position, Accuracy,test;
function onLocationFound(e) {
    if(Position){
        pub_map.removeLayer(Position);
        pub_map.removeLayer(Accuracy);
    }
test = e;
var radius = e.accuracy / 2;
//pop up stating the users position
Position = L.marker(e.latlng).addTo(pub_map).bindPopup("<h4>You are here</h4><p>You are  within " + radius + " metres from here</p>").openPopup();
Accuracy = L.circle(e.latlng, radius).addTo(pub_map);

/* var lat, lon;
lat = parseFloat(Position.coords.latitude);
lon = parseFloat(Position.coords.longitude);

console.log("user lat is: " +lat);
console.log("user lat is: "+lon); */

}

//error message if user location cannot be found
 function onLocationError(e) {
    alert(e.message);
}
//display the layers to the map
pub_map.on('locationfound', onLocationFound);
pub_map.on('locationerror', onLocationError);

//locate function
pub_map.locate({setView: true, maxZoom:16});


//knn feature
var kTable = 'geoupload.pubs';
var kColumn =["id", "p_name", "address1", "postcode", "local_authority"];
var kGeom = "geom";
var kLOC = "189349 307998";

//var klocy = "User location is " + test;

console.log(kLOC);

$(document).ready(function(){
    $.ajax({
        url: "knn.php",
        data:{ktable: kTable, kinclu: kColumn, kgeomy: kGeom, Loc: kLOC}
    })
    .done(function(data){
        knnPubsLay = L.geoJSON(JSON.parse(data),{
            pointToLayer: function (feature, latlng){
                return L.circleMarker(latlng,nearStyle);
        }});
        console.log("after " + kLOC);
        pub_map.addLayer(knnPubsLay);

    })
});


//pub_map.addLayer(uk_cl);
//pub_map.addLayer(uk_pubs);
//pub_map.addLayer(ire_pubs);
1
  • 2
    Chances are that some PHP file is not executing properly, and asking a webserver for the URL of such PHP script is returning < as the first character. Do use your browser's debugging tools and inspect the contents of the network requests. – IvanSanchez Apr 3 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.