views:

83

answers:

3

Hi,

I'm having trouble understanding why I have to place the button triggering the getJSON method outside of the form for the request to work.

If the button is placed within the form then the getJSON method returns no results.

The code bascially makes a XHR request on clicking the Submit button, based on the value selected. I have replicated the issue here: http://jsfiddle.net/z6caj/

Many Thanks,

+3  A: 

The clicking of the button will submit the form the normal way (when placed inside the form). return false at the end of your click handler, and it should work as expected. Alternatively, prevent submission by making the form's submit handler return false:

$("form").submit(function() {
    return false;
});
karim79
+2  A: 

Because it is a submit button and you do nothing to prevent the default action.

So the JS runs (setting the Ajax request going) and then the form submits (leaving the page and throwing the request away).

See http://docs.jquery.com/Tutorials:How_jQuery_Works (the section starting "For click and most other events")

David Dorward
+1  A: 

You could actually do the ajax request on the dropdown using the onchange event e.g.

$('#state').change(function(){

     //do stuff

}
matpol
thats what i ended up doing :)!
nav