I have an ajax request which fetches well (server side script does well) data from my database but my client side script does not show the returned data as I need. I am doing an application which should tell a user weather he is on a flooded area or not after he indicates his position on the map. I want the app say something like “Hi user, you are on a flooded area with the following characteristics….” and from the client side. See my codes below. Thanks
Server side script :
$prenom = $_GET['nPrenom']; $quartier = $_GET['nQuartier']; $long = $_GET['nLong']; $lat = $_GET['nLat']; $req = "SELECT type_zari FROM zari WHERE ST_Intersects(geom, ST_SetSRID(ST_Point($long, $lat), 4326));"; $resultat = $dbconn->prepare($req); $resultat->execute(); while($data = $resultat->fetch()){ if(in_array('ZARIE', $data)) echo"Vous etes sur une zone a risque d'inondation tres eleve"; elseif(in_array('ZARIM', $data)) echo"Vous etes sur une zone a risque d'inondation moyenne"; elseif(in_array('ZARIF', $data)) echo"Vous etes sur une zone a risque d'inondation faible"; else echo"Vous n'etes pas sur une zone a risque d'inondation"; }
Client side script which is a function called using a modal, but modal doesn’t close neither when clicked on the save button:
function saveDataToDB(){ var nomPrenom = document.getElementById('userName').value; var quartier = document.getElementById('areaSelect').value; var long = clickedCoord[0]; var lat = clickedCoord[1]; if(nomPrenom != '' && quartier != '' && long != '' && lat != ''){ $.ajax({ url: 'getPosition.php', type:'GET', dataType: 'html', data:{ nPrenom: nomPrenom, nQuartier: quartier, nLong: long, nLat: lat }, succcess: function(dataResult){ var dataResult = JSON.parse(dataResult); if(dataResult.statusCode == 200){ $('#pointadding').modal('hide'); $(dataResult).appendTo('#map'); } else{ alert('Something went wrong'); } } }); } else{ alert('Fill complete information'); } }
Advertisement
Answer
It looks like the problem here is how you’re processing the data on the client-side. The data is HTML, but you’re processing it as JSON!
Looking at your PHP, it looks like the server is just returning a plain text response:
Vous etes sur une zone a risque d'inondation tres eleve
A JSON response would look more like this:
{ 'content': "Vous etes sur une zone a risque d'inondation tres eleve" }
Both are equally valid ways of sending data from the server to the client in response to an AJAX request! But if you’re going with the first, you don’t need to JSON.parse()
the response on the client-side. And if you’re going with the second, you’ll need to consider using a function like json_encode()
on the server-side.
I suggest simply removing var dataResult = JSON.parse(dataResult);
from your JavaScript and seeing if that solves the issue!