views:

292

answers:

2

Hi, I use AJAX to load an external HTML file, containing a form, into another HTML file. The form HTML looks something like this:

<form id="..." name="..." onsubmit="postUsingAJAX(x,y,x); return false;">

Loading works fine. However, the onSubmit code is not executed when the form is submitted, same thing with onClick handlers on the submit button; no event listeners seems to be triggered. Is this the way things work when HTML is loaded through AJAX or am I doing something wrong?

A possible work-around would be to do

theFormObject.addEventListener('submit', function...)

but I can't figure out how to make the form NOT submit after the callback is fired. How can I make it wait for a return value (or rather, feed it "return false" no matter what happens in the callback function)?

Any ideas?

A: 

If you're using AJAX, my guess is that you don't want the form to take the user to a new page - you want it to call the processing page and update the current page accordingly. What you should do instead is create the entire form without any <form> tags. Then, using the <button> tag (example: <button id="whatever">Whatever</button>) attach a click event listener to that button to do the AJAX stuff. That's the way that I always do AJAX calls with a form that the user is filling in.

John Nicely
It looks like he is taking care of this using "return false" in the javascript for his onsubmit handler - so the form should be prevented from posting through the normal process, unless there is a javascript error.
RMorrisey
Yeah, but I've actually tried doing the onsubmit with a return false and that neveerrrr worked for me - it would always go through. Best to just avoid it straightaway.
John Nicely
+3  A: 

It looks like an error in function postUsingAJAX. Code "return false" will not executes. To continue properly work after error you should use try..catch statement. Example:

function postUsingAJAX() {
    try {
        // dangerous code
    } catch (e) {
        // report about error
    }
}

<form onsubmit="postUsingAJAX(); return false;">
Anatoliy
You might consider further documenting this for novices coming through Google.
Nerdling
Done. Sorry for my english, maybe someone correct me.
Anatoliy