If I have many forms generated by PHP and want a “Reply” button on each of them, where it sends the content of the form via ajax to another php page, then can I use the same javascript snippet for all of these elements?
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Reply" />
</form>
So if I do something like the following, then can I still handle all the responses individually and display the response ONLY on the element that “Reply” was clicked on?
$("#foo").submit(function(event){
$.ajax({
url: "/form.php",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked only in the element it was clicked in!");
});
// prevent default posting of form
event.preventDefault();
});
If you want to handle all forms on the page, your code could work with minor changes.