Note that there are some explanatory texts on larger screens.

plurals
  1. POgetJSON inside a function causing an infinite loop
    primarykey
    data
    text
    <p>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.</p> <p>The ajax code is this:</p> <pre><code>$.getJSON("photos/change_product", {product_id: product_type, ajax: 'true'}, function(data) { var options = []; for (var i = 0; i &lt; data.length; i++) { options.push('&lt;option value="' + data[i].id + '"&gt;' + data[i].label + '&lt;/option&gt;'); } $("select#options").html(options.join('')); }) }; </code></pre> <p>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:</p> <pre><code>$(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 &lt; data.length; i++) { options.push('&lt;option value="' + data[i].id + '"&gt;' + data[i].label + '&lt;/option&gt;'); } $("select#options").html(options.join('')); }) }; var selected_product = $("ul#products li:first-child a"); changeProduct(selected_product); </code></pre> <p>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?</p> <p>SOLVED: the problem is in the selected_product variable. It should be something like this:</p> <pre><code>var selected_product = $("ul#products li:first-child a").val(); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload