It seems like you are looking to attach an event handler to your form. For instance, you may want to assign a handler that manages the submission event of your form.
$("#myform").submit(function() {
$.post("sendFromDataHere.php", $(this).serialize());
});
There are two possible scenarios to consider:
- If you place this script in your main JavaScript file.
- If you include this script along with the returned HTML content.
In scenario 1, it will not work as expected because #myForm does not exist in the DOM when the script is running. However, in scenario 2, it works since #myForm is added to the DOM allowing the event handler to be assigned.
So, what can be done? Scenario 2 is generally considered bad practice. To handle elements added to the DOM in the future, you can utilize jQuery's .live() and .delegate functions. For newer versions of jQuery (>= v1.7), consider using .on() instead of .bind(), .live(), and .delegate().
Below is an example of the script using .do():
$("body").on("submit", "#myForm", function() {
$.post("sendFromDataHere.php", $(this).serialize());
});
It's advisable to replace "body" with the specific container selector where the HTML is inserted.
The following information is quoted from the documentation of .on():
"Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design..."
By implementing this method of assigning event handlers to your form, you should be able to organize your scripts within your main JavaScript file effectively.