PublicDisplayName
PublicDisplayName

Reputation: 317

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?

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?

Upvotes: 0

Views: 55

Answers (2)

John S
John S

Reputation: 21482

You are correct that you are not looping through the array. You are also not referencing the individual array items when you append.

Try:

$.each(data.listing.listing, function(i, item) {
    $('#listings').append(item);
});

When you do the following:

$.each(data, function(key, val) {

You are looping through the properties of the data object. It has two properties: listings and pins, so the loop executes twice.

And for each iteration of the loop, you are appending the same value (data.listing.listing), which I assume is an array.

Instead, I think you want to iterate over the array, and append each item in the array.


EDIT: The PHP you show at the top of your question looks like it would generate JSON like this:

{
    "listing": { "listing": ["<div>This contains my HTML</div>"] },
    "pins": { "lat":"50.000000","lng":"-1.000000" }
}

But with your edit, you show JSON that looks like this:

{
    "listing": ["<div>This contains my HTML</div>"],
    "pins": { "lat":"50.000000","lng":"-1.000000" }
}

If that is what your JSON looks like, you should use:

$.each(data.listing, function(i, item) {

jsfiddle

Upvotes: 1

BeetleJuice
BeetleJuice

Reputation: 40886

It appears that you intend your $.each to loop through the listings placed in $results['listing'] in your PHP, but it's actually looping over the whole $results.

To better see what's going on, use a different name for the current item in your $.each. Because you use data, the same name you use as the argument of your success callback, you're making the code harder to debug. If you want to cycle through your listings, do the following inside the success callback:

$.each(data.listing, function(i, result)){
   $('#listings').append(result);
}

The JSON you posted:

{
    "listing":["<div>This contains my HTML</div>"], 
    "pins":    "lat":"50.000000","lng":"-1.000000"}
}

Is invalid because you're missing an opening bracket between "pins": and "lat". It should be

{
    "listing":["<div>This contains my HTML</div>"], 
    "pins":   {"lat":"50.000000","lng":"-1.000000"}
}

Upvotes: 1

Related Questions