kate_hudson kate_hudson - 1 year ago 65
HTML Question

Make Ajax call fire only once

I have 4 selects. Using Javascript, I determine what options to display within these selects. When a select option is selected, I also trigger a change event to auto populate the additional select options. It is pretty hard to explain what exactly is happening so I have set up a JSFiddle. I have only done a little demonstration here using three selects.

Now within a change event, I also make an Ajax call. This is triggered via


I have included this function within the fiddle. My problem is this. I need to trigger the change event to prepopulate the additional selects. However, this event causes the ajax call to be fired multiple times. You can see this within the console. So if you select the year, the fiddle will make 2 ajax calls because the triggerImageChange is being called twice. When I have 4 selects, it makes 4 ajax calls.

Is there any way to stop this from happening?


Answer Source

In your change handler, you have this:

$('#year').change(function() {
    // other code


Then in the change handler for #product you have:

$('#product').change(function() {
    // other code


The triggerImageChange function makes an AJAX request. And you call the function twice. So it executes twice.

Why do you need $("#product").trigger("change");? It hasn't actually changed. If it has, and you need the second AJAX call to populate the third set of options, then it's kind of a non-issue in the first place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download