使用codeigniter和jquery插入后如何获取最后插入的id

使用codeigniter和jquery插入后如何获取最后插入的id

问题描述:

Please help me on how to get the last inserted id from database using codeigniter and jquery. What I want is to get the the last inserted id after inserting. I am using jquery to insert the data. I don't have any idea on how to it. Thanks a lot in advance.

SCRIPT

$('#add-tag').click(function () {
    var lang = $('#lang').val();
    var tag  = $('#tag').val();

    var data = {
        tag: tag,
        lang: lang
    }

    if (tag === '') {
        $('.error').html('<h4><i class="glyphicon glyphicon-info-sign">' +
            '</i> Field cannot be empty!</h4>').addClass('bounceIn').show();

        $('.error').delay(3000).fadeOut();
    } else {
        $.ajax({
            url: "<?= site_url('blog/add_tag'); ?>",
            type: 'POST',
            data: data,
            success: function (result) {
                //display message if successful
                $('.message').html('<h4><i class="glyphicon glyphicon-ok">' +
                    '</i> Tag has been added</h4>').addClass('bounceIn').show();
                $('.message').delay(3000).fadeOut();
                $('#tag').val('');

                $('#tags').append('<a class="tags animated fadeInDown">' +
                    '<span class="remove-tag" id="remove-tag' + lid + '">' +
                    '</span></span> ' + tag + '</a>');

                window.setTimeout(function () {
                    location.reload();
                }, 2000);
            }
        });
    }
});

VIEW

<div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12">
        <div id="add-tag-form" class="display-none relative">
            <div class="well well-sm">
                <div class="row">
                    <div class="col-md-12 col-sm-12 col-xs-12">
                        <h5>Add Tag</h5>
                        <input type="text" id="tagLastID" class="form-control" placeholder="Tag Last ID" readonly>
                        <input type="hidden" id="lang" class="form-control" placeholder="Lang" required value="<?= $lang; ?>">
                        <input type="text" id="tag" class="form-control" placeholder="Tag" required>
                        <br />
                        <button id="add-tag" class="btn col-md-12 col-sm-12 col-xs-12">Add Tag</button>
                        <div class="text-center"><a id="close-tag">cancel</a></div>
                    </div>
                </div>
            </div>
        </div>
        <button id="add-tag-btn" class="btn col-md-12 col-sm-12 col-xs-12">Add Tag</button>

    </div>
</div>

CONTROLLER

public function add_tag() {
    $this->Mblog->addTag();
}

MODEL

public function addTag() {
    $lang = $this->input->post('lang');
    $tag  = $this->input->post('tag');

    $data = array(
        'tags' => $tag,
        'lang' => $lang
    );

    $this->blog->insert('tags', $data);

    return $this->blog->insert_id();
}

Add return to your controller function or echo the result like as follows:

public function add_tag() {
    return $this->Mblog->addTag();
}

OR

public function add_tag() {
    echo json_encode(['data' => $this->Mblog->addTag()]);

    exit;
}

And then try to modify dump and see the ajax success response:

$.ajax({
    url: "<?= site_url('blog/add_tag'); ?>",
    type: 'POST',
    data: data,
    dataType: 'json', // this will convert your results to json by default
    success: function (result) {
        // You should get the json result
        console.log(result.data);

        // Your regular logic to handle result
    }, 
    fail: function(res) {
        console.log(res); // will log fail results
    }
});

Try these and let us know if this works for you or not.

If you are asking that how to return data from controller to jQuery then yes, this is the answer.

Replace your controller code with this

public function add_tag() {
     $insert_id = $this->Mblog->addTag();
     echo(json_encode(array("insert_id"=>$insert_id)));
}

The echo'ed result will be appear in your success of jQuery.ajax.

You're already returning the id from the Model, so in your controller the only thing you have to do is echo-ing the result.

public function add_tag() {
          echo $this->Mblog->addTag();
        }

Then in you jquery the result will be what you have echoed from the controller.