1

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();
}
6
  • You have mysql LAST_INSERT_ID() function Commented Sep 28, 2016 at 13:05
  • @Drew Could you please give the link for the same question? Thanks. Commented Sep 28, 2016 at 13:05
  • you can do something like this also mysql_query("INSERT INTO testtable(1, 2, 3, 'some')"); $last_inserted_id = mysql_insert_id(); Commented Sep 28, 2016 at 13:07
  • 1
    $this->db->insert('posts', $post_data); $insert_id = $this->db->insert_id(); return $insert_id; Commented Sep 28, 2016 at 13:08
  • @vamsi I know how to do it. But what I want is to return it with jquery. Commented Sep 28, 2016 at 13:09

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help :) Thanks for marking it as correct answer.
1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.