2014-01-01 02:46
浏览 290


I'm trying to get a simple form to submit via AJAX to the submit.php page where it is sent to a database. When I submit it, it redirects to submit.php. I want it to submit without redirecting. Thanks in advance!


var request;
    if (request) {
    var $form = $(this);
    var $inputs = $form.find("input, select, button, textarea");
    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);
    request = $.ajax({
        url: "/submit.php",
        type: "post",
        data: serializedData

        //Could something like this work? 
        //complete: function() {***Stop redirect?***}


    request.done(function (response, textStatus, jqXHR){
        console.log("Hooray, it worked!");
    }); (jqXHR, textStatus, errorThrown){
            "The following error occured: "+
            textStatus, errorThrown

    request.always(function () {
        $inputs.prop("disabled", false);


图片转代码服务由CSDN问答提供 功能建议

我正在尝试通过AJAX将一个简单的表单提交到submit.php页面,并将其发送到 一个数据库。 当我提交它时,它会重定向到submit.php。 我希望它在不重定向的情况下提交。 提前致谢!


  var request; 
 var $ form = $(this); 
 var $ inputs = $ form.find(“input,select,button,textarea”)  ; 
 var serializedData = $ form.serialize(); 
 $ inputs.prop(“disabled”,true); 
 request = $ .ajax({
 url:“/ submit.php”,
ntype  :“post”,
  } ;; 
 console.log(“Hooray,it working!”); 
});  jqXHR,textStatus,errorThrown){
 request.always(function(){\  n $ inputs.prop(“disabled”,false); 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dro44817 2014-01-01 03:33

    Is the document ready when your code runs? If not, $("#myForm") is returning an empty jQuery object, therefore any handlers attached to it won't ever be called. Test this by saving the jQuery object to a variable and logging it to the console.

    Two solutions:

    • Move your code into a document ready handler: $(function () { /* my code dependent on DOM elements */ });
    • Use an event listener instead of binding to elements: $(document).on('submit', '#myForm', function (event) { /* handler */ }

    There's nothing wrong with the event.preventDefault(); line - it can stay where it is, although I prefer to place it at the very top unless it's part of a conditional - and return false; isn't needed.

    Reason I can answer this: I just setup a local test for this and came across the same problem: my submit handler wasn't running at all. But then I realised my <script> tag was before the #myForm element but my code wasn't waiting until #myForm was in the document before trying to find it with $().

    Edit: Placing the <script> tag at the bottom of the <body> negates the need to wait for document ready in your case. It also speeds up page rendering, but that's a whole other discussion.

    打赏 评论
  • dsk61780 2014-01-01 03:09

    Put the event.preventDefault(); right after the first code line the one with the .submit listener

    打赏 评论

相关推荐 更多相似问题