jeudi 30 juin 2016

Multidimensional PHP array to jQuery - Only seeing one result

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?

Aucun commentaire:

Enregistrer un commentaire