I'm trying to use PHP and jQuery to create a dynamic search results page.
On the PHP
side, a SELECT
statement is called, where I check if all variables are set, add my HTML that I want to be used clientside, then put the variables in an array named $result
.
Of the results of the database call, I also add the longitude
and latitude
in their own array, named $pins
.
I then create a multidimensional array called $results
, and put the array together like so:
$result = array('listing'=>$listing);
$pins = array('lat'=>$lat1,'lng'=>$lon2);
$results = array('listing'=>$result,'pins'=>$pins);
echo json_encode($results);
Now, clientside I use jquery. The issue I'm facing, is there should be 2 results in total. However I see the same result repeated twice (I can confirm they should be unique). Here is my jQuery:
$.ajax({
url: '/updatedsearch.php',
type: 'POST',
data: {
q: search,
lng: coordinates[0],
lat: coordinates[1],
},
dataType: "json",
success: function(data) {
if(data == "undefined" || data == null) {
console.log("There was no search results or something similar");
} else {
var pins = [data.pins.lat, data.pins.lng];
$.each(data, function(key, val) {
$('#listings').append(data.listing.listing);
console.log(pins);
console.log(data);
});
}
},
Everything here works as it should, apart from when $.each()
runs, it appears to be appending the same data twice.
I assume it's because of .append(data.listing.listing);
, if I understand correctly I'm not looping through the array here, I'm effectively referencing data.listing.listing[0]
- have I understood this correctly?
Edit: I now have an issue with my results appearing twice. There should be only two results, however there are four in total, it appears as though these have been duplicated.
{"listing":["<div>This contains my HTML</div>"], "pins":"lat":"50.000000","lng":"-1.000000"}}
I have run this though jsonlint
and it appears invalid. Using PHP I have created this data as follows:
while($listrow = mysqli_fetch_assoc($list)) {
$listing[] = '<div>This contains my HTML</div>';
}
$pins = array("lat"=>$lat1, "lng"=>$lon2);
$results = array('listing'=>$listing, 'pins'=>$pins);
echo json_encode($results);
Have I misunderstood using multidimensional arrays, which is causing the error?