Reputation: 1688
I recently started using jQuery/AJAX for submitting data to my PHP API.
Currently what I'm using is an input type="button" in the html and then a .click() jQuery function to submit it.
I'm not quite sure it's the best way to do it though, should I use a input type="submit" with preventDefault() instead ?
Upvotes: 0
Views: 85
Reputation: 2184
Submitting is not limited to any specific events via jquery. You can use any event which exists like click or customized methods/functions written by you or other to send the ajax request depending on user behavior like hover or any other. Simply how you use jquery ajax is limited by your imagination and practice.
Upvotes: 1
Reputation: 9847
You can use .submit()
, you just have to insert return false;
in your callback to prevent actual form submission and do your own operations.
$('#target').submit(function() {
alert('Handler for .submit() called.');
return false;
});
Upvotes: 2
Reputation: 1038890
It's better to use .submit()
on the form instead of .click()
on the submit button. In both cases preventDefault
is necessary though. The reason for that is that the user could submit the form by pressing Enter while editing some field and if you subscribed to the .click event of a button, this event won't fire.
Upvotes: 5