Submitting a form with Javascript

2019-07-17 15:27发布

问题:

Some forms of mine are submitted with Javascript/JQuery, so no page refresh occurs.

But I've noticed a weird behavior with browsers between my 2 computers. On one computer (and all browsers I've tested) my form submission executes as expected. My other computer (Mac) it's hit and miss. I'll submit the form, and it will do a typical POST refresh. So the browser refreshes, and I see my button's text in the Url address bar.

-again, my PC's browsers do not do this.

Unless I'm going crazy, all I can deduct is that the browsers on my Mac are not executing the javascript properly. But I'm more prepared to expect an error on my coding side.

Am I properly ensuring the form is NOT getting submitted with my Javascript?

<form id="norefreshForm">
   <!--more form fields here -->
   <input type="submit" name="button" value="Submit Me" />
</form>

<script language="javascript" type="text/javascript">
$(document).ready(function(){

    $.ajaxSetup({
       global:false,
       cache:false,
       type:"POST",
       url:"<?=$_SERVER['REQUEST_URI'];?>",
       timeout:120000   
    });


    $("form#norefreshForm").submit(function(){

        $.ajax({ success:function(response){ alert("Submitted"); } });
        return false;
    });

});
</script>

回答1:

actually some browsers you should do e.preventDefault() instead of return false; and I really don't know why. but it happened to me a lot. So, you can do this:

 $("form#norefreshForm").submit(function(){
        e.preventDefault();//should be at the very top 
        $.ajax({ success:function(response){ alert("Submitted"); } });

    });

});


回答2:

Try this:

$("form#norefreshForm").submit(function(e){
        $.ajax({ success:function(response){ alert("Submitted"); } });
        e.preventDefault();
});


回答3:

In your form try not to use the submit button. Instead you can use a simple button and bind the ajax call on click of this button.

The reason for this seem like you are making two requests at the same time one by the submit button and the other your own ajax function.

Also the first submit fails because you haven't specified the action attribute for the form.



回答4:

When you are using jQuery only, return false should be enough. (Not 100% sure of mac)

But if you have pure javascript also written, in that case you may have to use preventDefault or stopPropagation also.

In case of IE its more different. Sometimes you will have to use window.event.returnValue = false;

So a combination of all these will do the trick normally.

So replace your return false statement with

if (eventObject.preventDefault) {
    eventObject.preventDefault();
} else if (window.event) /* for ie */ {
    window.event.returnValue = false;
}
return false;

This will work for both PC and MAC

Happy coding!!!