skip to Main Content

I have been trying to insert data into the database through CodeIgniter Controller. I have made a validation process and receiving validation error through response in ajax. But It seems that when in the form all the fields are filled and after that if I click on any input field the data is inserted without even clicking the save or submit button in the form.

enter image description here

So, if I press Name field, Color field, or Price field the data is inserted without pressing the "Save Car" button.

**My Controller: CarModel.php **

<?php
class CarModel extends CI_Controller
{

    public function index()
    {
        $this->load->view('car_model/list.php');
    }
    public function showCreateForm()
    {
        $html = $this->load->view('car_model/create', '', true);
        $response['html'] = $html;
        echo json_encode($response);
    }
    public function saveModel()
    {
        $this->load->model('Car_model');

        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('color', 'Color', 'required');
        $this->form_validation->set_rules('price', 'Price', 'required');
        if ($this->form_validation->run() == true) {
            //save enteries to DB
            $formArray = array();
            $formArray['name'] = $this->input->post('name');
            $formArray['color'] = $this->input->post('color');
            $formArray['transmission'] = $this->input->post('transmission');
            $formArray['price'] = $this->input->post('price');
            $formArray['created_at'] = date('Y-m-d H:i:s');
            $this->Car_model->create($formArray);
            $response['status'] = 1;
        } else {
            $response['status'] = 0;
            $response['name'] = strip_tags(form_error('name'));
            $response['color'] = strip_tags(form_error('color'));
            $response['price'] = strip_tags(form_error('price'));
        }
        echo json_encode($response);
    }
}

My Model: Car_model.php

<?php

class Car_model extends CI_Model {
    public function create($formArray){
        $this->db->insert('car_models',$formArray);
    }
}

The ajax code in the list.php file. The code is given below:

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <!-- Optional JavaScript -->


    <title>Ajax Crud</title>
</head>

<body>
    <div class="header">
        <div class="container">
            <h3>
                Ajax CodeIgniter CRUD
            </h3>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <h3>Car Models</h3>
            </div>
            <div class="col-md-6 text-right"><a href="javascript:void();" class="btn btn-primary text-right" onclick="showModel()">Create</a></div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <table class="table table striped">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Color</th>
                        <th>Transmission</th>
                        <th>Price</th>
                        <th>Created Date</th>
                        <th>Edit</th>
                        <th>Delete</th>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <div class="modal fade" id="createCar" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Create Model</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div id="response"></div>
            </div>
        </div>
    </div>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

    <script>
        function showModel() {
            $("#createCar").modal("show");
            $.ajax({
                url: '<?php echo base_url('CarModel/showCreateForm'); ?>',
                type: 'POST',
                data: {},
                dataType: 'json',
                success: function(response) {
                    console.log(response);
                    $("#response").html(response["html"]);
                }
            })
        }
        $("body").on("click", "#createCarModel", function(e) {
            e.preventDefault();

            $.ajax({
                url: '<?php echo base_url('CarModel/saveModel'); ?>',
                type: 'POST',
                data: $(this).serializeArray(),
                dataType: 'json',
                success: function(response) {

                    if (response['status'] == 0) {
                        if (response["name"] != "") {
                            $(".nameError").html(response["name"]).addClass('invalid-feedback d-block');
                            $("#name").addClass('is-invalid');
                        } else {
                            $(".nameError").html("").removeClass('invalid-feedback d-block');
                            $("#name").removeClass('is-invalid');
                        }

                        if (response["color"] != "") {
                            $(".colorError").html(response["color"]).addClass('invalid-feedback  d-block');
                            $("#color").addClass('is-invalid');
                        } else {
                            $(".colorError").html("").removeClass('invalid-feedback d-block');
                            $("#color").removeClass('is-invalid');
                        }

                        if (response["price"] != "") {
                            $(".priceError").html(response["price"]).addClass('invalid-feedback  d-block');
                            $("#price").addClass('is-invalid');
                        } else {
                            $(".priceError").html("").removeClass('invalid-feedback d-block');
                            $("#price").removeClass('is-invalid');
                        }
                    } else {
                        $(".nameError").html("").removeClass('invalid-feedback d-block');
                        $("#name").removeClass('is-invalid');

                        $(".colorError").html("").removeClass('invalid-feedback d-block');
                        $("#color").removeClass('is-invalid');

                        $(".priceError").html("").removeClass('invalid-feedback d-block');
                        $("#price").removeClass('is-invalid');
                    }
                }
            })
        });
    </script>
</body>

</html>

Please help me fix it. Thank you.

2

Answers


  1. Chosen as BEST ANSWER

    I have found the issue. The problem was occurring because I set the whole form as an event listener for the insert operation. I needed to use submit instead of click in the line $("body").on("click", "#createCarModel", function(e) {. So, I have changed it to $("body").on("submit", "#createCarModel", function(e) {. Then the problem stopped happening.

    Thanks to all who tried to help me.


  2. Try Changing your onclick selector to your submit button id.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search