I’m working on a Codeigniter application and in a page I’m using jQuery to make an Ajax call to a function inside a controller. I pass to this function some values taken from the page; the function make some calculations and then I have to display the result. All of this withouth refreshing the page.
The ajax code is this:
$.getJSON("photos/change_product", {product_id: product_type, ajax: 'true'}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++)
{
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#options").html(options.join(''));
})
};
When I trigger it from a click event on some html element it works just fine. The problem is that I also need it to run when I load the page the first time. So I thought I could move that code into a function and then call it wherever I needed it. So, I created a changeProduct function with the code above and then called it like this:
$(document).ready(function() {
function changeProduct(product_type) {
$.getJSON("photos/change_product", {product_id: product_type, ajax: 'true'}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++)
{
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#options").html(options.join(''));
})
};
var selected_product = $("ul#products li:first-child a");
changeProduct(selected_product);
And this is causing an infinite loop of page refreshing. How can I avoid this? Shall I create counters and conditionals or is there some better way?
SOLVED: the problem is in the selected_product variable. It should be something like this:
var selected_product = $("ul#products li:first-child a").val();
Is it because ‘selected_product’ is a jquery object? Do you want to do something like $(“ul#products li:first-child a”).text() instead to get it’s value?