简体   繁体   中英

CodeIgniter and AJAX form submit

I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.

Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.

My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.

Here is my AJAX call:

$(document).ready(function() {

    $('form#feedInput').submit(function(e) {

        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
            data: $('.feed-input').val(),
            dataType: "html",
            success: function(data){
                debugger;
                $('#feed-container').prepend(data);
            },
            error: function() { alert("Error posting feed."); }
       });

    });
});

I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.

How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?

The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val() . Also there is an unnecessary debugger variable in the success method.

A working code could be:

$('form#feedInput').submit(function(e) {

    var form = $(this);

    e.preventDefault();

    $.ajax({
        type: "POST",
        url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
        data: form.serialize(), // <--- THIS IS THE CHANGE
        dataType: "html",
        success: function(data){
            $('#feed-container').prepend(data);
        },
        error: function() { alert("Error posting feed."); }
   });

});

Html part in view

<form id="comment" method="post">
    <h2>Enter Your Details</h2>
    <center><div id="result"></div></center>

    <div class="form_fld">
        <label>Name</label>
        <input type="text" placeholder="Enter Your Full Name" name="name" required=""> 
    </div>
    <div class="form_fld">
        <label>Email ID</label>
        <input type="text" placeholder="Enter Email ID" name="email" required="">
    </div>
    <div class="form_fld">
        <label>Contact Number</label>
        <input type="text" placeholder="Enter Contact Number" name="contact" required="">
    </div>
    <div class="form_fld">
        <label>Developer</label>
        <select name="developer">
            <option>Lotus</option>
            <option>Ekta</option>
            <option>Proviso</option>
            <option>Dosti</option>
            <option>All</option>
        </select>
    </div>
    <div class="form_fld">
        <button type="submit" id="send">Submit</button>
    </div>
</form>

After Html Part Just put ajax request

<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
    $("#comment").submit(function(){
        dataString = $("#comment").serialize();

        $.ajax({
            type: "POST",
            url: "home/contact",
            data: dataString,
            success: function(data){
                // alert('Successful!');
                $("#result").html('Successfully updated record!'); 
                $("#result").addClass("alert alert-success");
            }

        });

        return false;  //stop the actual form post !important!

    });
});
</script>

Within Controller

public function contact()
{
    $ip = $_SERVER['REMOTE_ADDR'];
    $data = array('name' => $this->input->post('name'),
                  'email' => $this->input->post('email'),
                  'number' => $this->input->post('contact'),
                  'developer' => $this->input->post('developer'),
                  'ip' => $ip,
                  'date' =>  date("d/m/Y"));
    $result = $this->User_model->contact($data);
    print_r($result);
}

You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.

You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.

You should also check if you have errors in your console.

To determine if default action is prevented you can use e.isDefaultPrevented() . By default action in this case I mean submit action of the form with id feedInput.

You didn't name your param in data. Check jquery ajax examples .

You are probably getting an error e.preventDefault(); is not stopping the ajax.

$.ajax({
    type: "POST",
    url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
    data: $("#form").serializeArray(),
    success: function(resp){
        $('#container').html(resp);
    },
    error: function(resp) { alert(JSON.stringify(resp)); }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM