javascriptjquery-3

jquery serialize yields an empty array


i am trying to use jquery serialize to pass some values from a form in an ajax post request to my server but the serialize function returns an array full of nulls, the values aren't serialized. i do not understand why the values are not serialized, i added the relevant code, here it is hope someone has an idea:

<div class="modal fade" id="modal_form" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h3 class="modal-title">Contact Form</h3>
                </div>
                <div class="modal-body form">
                    <form action="#" id="form" class="form-horizontal">
                        <input type="hidden" value="" name="id"/>
                        <div class="form-body">
                            <div class="form-group">
                                <label class="control-label col-md-3">first name</label>
                                <div class="col-md-9">
                                    <input name="first_name" placeholder="first name" class="form-control" type="text">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-md-3">last name</label>
                                <div class="col-md-9">
                                  <input name="last_name" placeholder="last name" class="form-control" type="text">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-md-3">phone</label>
                                <div class="col-md-9">
                                    <input name="phone" placeholder="phone" class="form-control" type="text"> 
                                </div>
                            </div>
                            <div class="form-group">
                                    <label class="control-label col-md-3">email</label>
                                    <div class="col-md-9">
                                            <input name="email" placeholder="email" class="form-control" type="text">
                                    </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
<script type="text/javascript">
        $(document).ready( function () {
            $('#table_id').DataTable();
        } );
        var save_method; //for save method string
        var table;


        function add_contact()
        {
            save_method = 'add';
            $('#form')[0].reset(); // reset form on modals
            $('#modal_form').modal('show'); // show bootstrap modal
            //$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
        }

        function edit_contact(id)
        {
            save_method = 'update';
            $('#form')[0].reset(); // reset form on modals

            //Ajax Load data from ajax
            $.ajax({
                url : "<?php echo site_url('index.php/contacts/ajax_edit/')?>/" + id,
                type: "GET",
                dataType: "JSON",
                success: function(data)
                {
                    console.log(data);
                    $('[name="id"]').val(data.id);
                    $('[name="first_name"]').val(data.first_name);
                    $('[name="last_name"]').val(data.last_name);
                    $('[name="phone"]').val(data.phone);
                    $('[name="email"]').val(data.email);


                    $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                    $('.modal-title').text('Edit Contact'); // Set title to Bootstrap modal title

                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert('Error get data from ajax');
                }
            });
        }

        function save()
        {
            var url;
            if(save_method == 'add')
            {
                url = "<?php echo site_url('contacts/contact_add')?>";
            }
            else
            {
              url = "<?php echo site_url('contacts/contact_update')?>";
            }

            // ajax adding data to database
            $.ajax({
                url : url,
                type: "POST",
                data: $("#form").serialize(),
                dataType: "JSON",
                contentType: 'application/json; charset=utf-8',
                success: function(data)
                {
                    console.log(data);
                    e.preventDefault();
                    //if success close modal and reload ajax table
                    $('#modal_form').modal('hide');
                    location.reload();// for reload a page
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    console.log(errorThrown);
                    alert('Error adding / update data');
                }
            });
        }

        function delete_contact(id)
        {
            if(confirm('Are you sure delete this data?'))
            {
            // ajax delete data from database
                $.ajax({
                    url : "<?php echo site_url('index.php/contacts/contact_delete')?>/"+id,
                    type: "POST",
                    dataType: "JSON",
                    success: function(data)
                    {

                       location.reload();
                    },
                    error: function (jqXHR, textStatus, errorThrown)
                    {
                        alert('Error deleting data');
                    }
                });
            }
        }

    </script>

Solution

  • .serialize() does not produce JSON it produces application/x-www-form-urlencoded. Setting the content type as JSON is wrong just dont set the content type and jQuery will set it as application/x-www-form-urlencoded for you.

            $.ajax({
                url : url,
                type: "POST",
                data: $("#form").serialize(),
                dataType: "JSON",
                // remove contentType: 'application/json; charset=utf-8',
                success: function(data)
                {
                    console.log(data);
                    //e.preventDefault();
                    //if success close modal and reload ajax table
                    $('#modal_form').modal('hide');
                    location.reload();// for reload a page
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    console.log(errorThrown);
                    alert('Error adding / update data');
                }
            });
    

    Also, I don't know what you expect e.preventDefault(); in the success handler to do but its definitely not doing it.