I have a JS function that uses ajax to filter options in a sub navigation/filter menu.
It makes the calls correctly and receives the JSON response from the server, however it won't loop through the results.
It is only displaying the last result in the JSON response.
The ajax script:
function updateVenues(opts){
$.ajax({
type: "POST",
url: "/venue-search/ajax/",
dataType : 'json',
cache: false,
data: {filterOpts: opts, get_param: 'id'},
success: function(records){
$.each(records, function(idx, record){
$("#searchResults").html('<a href="/venue-preview/' + record.id + '" class="various fancybox.ajax">' + record.title + "</a>");
});
}
});
}
A typical response from the server
[
{"id":"1","title":"Wedding Venue 1","main_image":"wedding-venue-1.jpg"},
{"id":"2","title":"Wedding Venue 2","main_image":"wedding-venue-2.jpg"},
{"id":"3","title":"Wedding Venue 3","main_image":"wedding-venue-3.jpg"}
]
Could anyone shed some light on why it isn't looping?
Try this
function updateVenues(opts){
$.ajax({
type: "POST",
url: "/venue-search/ajax/",
dataType : 'json',
cache: false,
data: {filterOpts: opts, get_param: 'id'},
success: function(records){
$.each(records, function(idx, record){
$("#searchResults").append('<a href="/venue-preview/' + record.id + '" class="various fancybox.ajax">' + record.title + "</a>");
});
}
});
}
Each time you call .html
it's overwriting the entire contents with the new value, which is why you only get the last one displayed. You need to use append:
function updateVenues(opts){
$.ajax({
type: "POST",
url: "/venue-search/ajax/",
dataType : 'json',
cache: false,
data: {filterOpts: opts, get_param: 'id'},
success: function(records){
//clear out any previous results first
$("#searchResults").empty();
$.each(records, function(idx, record){
//now append each one
$("#searchResults").append('<a href="/venue-preview/' + record.id + '" class="various fancybox.ajax">' + record.title + "</a>");
});
}
});
}
You should use:
$("#searchResults").append('<a href="/venue-preview/' + record.id + '" class="various fancybox.ajax">' + record.title + "</a>");
Otherwise you overwrite your "#searchResults") in each loop.