rzvt
rzvt

Reputation: 55

Show data immediately after insert to db mysql using codeigniter MVC

I have one text box and one button, after filling in the text box and then clicking the button, the data will be saved to mysql. My question is, how do I when I click the save button, the ID of the data that I save will immediately appear on that page. I mean the ID of the data that just i insert into mysql

This is the view

<label for="userAnswer">Answer</label>
<textarea name="userAnswer" id="userAnswer" class="form-control"></textarea>
<button onclick="saveAnswer()">Submit Answer</button>

This is the js

function saveAnswer(){
    var inputAnswer = $('#userAnswer').val();
        $.ajax({
            type: "GET",
            url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
            dataType: 'json',
    });
}

This is the Controller

function saveAnswer(){
    $data = array(
        'id' => uuid(false),
        'answer' => $this->input->get_post("inputAnswer")
        );
        $this->db->insert('tableAnswer', $data);
}

Thanks

Upvotes: 0

Views: 88

Answers (4)

bhardwaj_g
bhardwaj_g

Reputation: 35

use this code:-

function saveAnswer(){
    var inputAnswer = $('#userAnswer').val();
        $.ajax({
            type: "GET",
            url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
            dataType: 'json',
            sucess:function(result){
               alert(result);
            },
    });
}

the result wll carry your id and it will be shown in alert box, and the returning of id from ajax use this code:-

function saveAnswer(){
    $data = array(
        'id' => uuid(false),
        'answer' => $this->input->get_post("inputAnswer")
        );
        $this->db->insert('tableAnswer', $data);
        $id = $this->db->insert_id;
        if($id > 0){
            echo $id;
        }
}

if you get the result don't forget to tick it right, so other can get help

Upvotes: 1

rzvt
rzvt

Reputation: 55

Views File add this code

<input type="text" id="id">

Controller File After insert, add this code

echo json_encode(array("val"=> $data['id']));

Javascript

$.ajax({
   type: "GET",
   url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
   dataType: 'json',
   success: function(val){
       document.getElementById("id").value = val.val;
   }
});

Thats it...

Upvotes: 2

Gianni Fuina
Gianni Fuina

Reputation: 43

You have to echo the id and not return it to get it from Js

echo $this->db->insert_id();

Upvotes: 0

Devang Hire
Devang Hire

Reputation: 314

after insert your data, paste below line in modal

    return $this->db->insert_id();

it will reflect last insert data ID

Upvotes: 0

Related Questions