提交表单的jQuery Serialize()

时间:2014-03-05 21:21:46

标签: javascript jquery forms

当我点击按钮时,我有一个提交的表单,它会发送一封电子邮件,一切正常。

我想更改表单以使用type="submit",当我这样做并更改我的功能时,它永远不会发送电子邮件。

我该怎么做才能实现这一目标。

<!-- Changed to type="submit" for browser validation" -->
<button type="button" class="btn btn-primary" id="email-button" name="submit">
   Submit Emails
</button>

这一切对我有用

$('#email-button').on("click", function(){
    if(TestInput())
    {
        PostCustomerOrderData();
    }
});   

PostCustomerOrderData()

function PostCustomerOrderData() {

    $.ajax({
        type: "POST",
        url: "./send-email.php",        
        data: $("form").serialize()
    })
        .done(function(data) {
            var json = JSON.parse(data);
            //console.log(json);

            if(json.error == 1)
            {
                //Something wrong has happened
                alert(json.error_message);
            }
            else if(json.error == 0)
            { 
                 alert("Your order has been sent successfully");
                // Clear all fields
               ClearFormElements();

                if(PROCESS_SAVE_ORDERS)
                {
                    var orders = localStore.getValue(ORDERS_KEY);
                    orders.pop(); //Remove current order from the orders (in local storage)
                    localStore.setValue(ORDERS_KEY, orders);
                    /* Added in to make pending button alter 
                     the total number of orders pending for user feedback */
                    RenderPendingBtn();
                    // run function again 
                    FetchOrderFromLocalStorage();
                }   
            }
    })
        .fail(function (){
            var form = $('form').serializeArray();
            //console.log(form);

            if(!PROCESS_SAVE_ORDERS)
            {
                var orders = localStore.getValue(ORDERS_KEY);
                if(orders == null)
                {
                    orders = [];
                }
                orders.push(form);

                localStore.setValue(ORDERS_KEY, orders);

                ClearFormElements();                    
            }
        });              
}

我已经更改了要提交的按钮类型,以及jQuery函数的on("submit"),但我现在已经丢失了。

3 个答案:

答案 0 :(得分:1)

尝试使用

$('#email-button').on("click", function(e){
   e.preventDefault();
    if(TestInput())
    {
        PostCustomerOrderData();
    }
}); 

Fiddle

一个简单的例子

答案 1 :(得分:0)

我猜想默认的表单操作会覆盖你的jQuery事件。

在表单标记中添加onsubmit="return false"

答案 2 :(得分:0)

$("form").on("submit",function(e){
    //all your code goes here
    e.preventDefault();
    return false;
});