0

I have this jquery ajax form submitting script which i wrote for creating and editing items in the DB.

The issue is that whenever i create an item 2 items are created.

<script type="text/javascript">
    $(document).ready(function() {
        $('#new_item').on('hidden', function () {
            $(".alert").hide();  // remove errors…when the modal form closes
        });
        $(".showedit").click(function(){
            var edit = $(this).attr('id').split("_");// get the edit id
            var id = edit[1];

            var values = $('#data_'+id+' td').map(function(_, td) {
                return $(td).text();
            }).get();
            // populate the form with the database field
            var name    = $("input[name=name]").val(values[1]);
            var model   = $("select[name=model]").val(values[2]);
            var brand   = $("select[name=brand]").val(values[3]); 
            $('#new_item').modal();
        });

        $("#submit_button").click(function( e ) {
            e.preventDefault();

            var name    = $("input[name=name]").val();
            var amount  = $("input[name=amount]").val();
            var model   = $("select[name=model]").val();
            var brand   = $("select[name=brand]").val(); 

            $.ajax({            
                    type: "POST",                   
                    url: "<?=base_url()?>items/create",                 
                    cache: false,
                    dataType: "json",
                    data: 'name='+name+'&amount='+amount+'&model='+model+'&brand='+brand,
                    success: function(result){
                        if(result.error) {
                            $(".alert").addClass('alert-error');
                            $(".alert").fadeIn('slow').html(result.message);
                          } 
                          else 
                          {                 
                            $(".alert").addClass('alert-success');
                            $(".alert").fadeIn('slow').html(result.message);
                          }

                    }
            }); 

        });
    });
</script>

Please help me solve this. I will be greatful!!

4

1 回答 1

0
$("#submit_button").click(function( e ) {
            e.preventDefault();

这意味着它将阻止按钮默认操作

你必须把它改成

$("form").submit(function( e ) {
            e.preventDefault();

或者您可以将 ID 添加到表单中

于 2012-10-31T05:56:12.697 回答