I have a problem with this jQuery code. It doesn't work as expected:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit( function(event){
$.post("list.php", { name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
});
});
});
However, this works:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit();
});
I wonder why the internal function on submit doesn't work. When a user selects a value from a dropdown, the form must be submitted. The second set of codes work but if I add an inner function to submit, it doesn't.
Basically, I want to do some ajax call after the user select on the dropdown.
So the problem here is that in the first case, you are binding an event handler to the element, and in the second you are triggering it. Let's look at the first case:
You're essentially doing something like
The second case is you instructing the form to submit, which is why it works. If you wanted the handler to work with your custom code you would need both of them. First bind your event handler, then, onchange instruct the form to submit.
Keep in mind though, that as other people have already said, if your action is set to go to another location, you may not see the results of the binded event handler so instead of explicitly stating a url for your action, you will have to use something to prevent the form from going anywhere like
action="javascript:void(0)"
or the like.To make your code a bit cleaner, you could pull the ajax out of an unnamed function and put it in a named one and call it on change so it looks like this.
I haven't run this code, please excuse any silly syntax mistakes I've made. But this should get you some of the way there. Good luck! :)
The
.submit
call in your first example is binding a function to the submit event on the form. From the fine manual:You need to bind your submit handler:
somewhere else and call
submit
as in your second example.When you call with a callback argument
submit( handler(eventObject) )
it will only attach an event handler. To trigger a form submit, callsubmit()
with no arguments:According to documentation ( http://api.jquery.com/submit/ ),
submit()
without parameters will submit your form, but if you include arguments it will bind thesubmit
event to the form, but it wont submit it.So, the code posted by @Chris Fulstow would be the right way of submitting the form, but as ajax is not synchronous, function will continue without waiting for the answer and then, the alert will not be shown.
You can make it synchronous, but you must use
$.ajax
instead of$.post
, because$.post
doesn't include anasync
option. Anyway, I'm providing a solution for your specific problem, but I'm guess there should be a better way for doing it.