doudun3040 2017-03-22 07:33
浏览 18
已采纳

codeigniter使用ajax更新数据库然后显示

I would like this function:

After I select an option I want to update right away the database and then show it right away also inside a certain div. How can I achieve this?

Here's my HTML:

<select id="category1" name="cat1">
    <option>Hardware</option>
    <option>Software</option>
    <option>Network</option>
</select>

AJAX code:

$('#category1').on('change',function(){
    var data = $("cat1").val();
    var ticket = '<?php echo $ticket_details[0]["cTicketNo"];?>';
    if(data){
        jQuery.ajax({
            type: "POST",
            dataType: 'json',
            url: "<?php echo base_url();?>User/TicketView/update_cate",
            data: {data: data,ticket: ticket},
            success:function(response){
                alert('successful');
            },
            error: function(response){
                alert('tangina!');
            }
        });
    }

});

Controller:

function update_cate(){
    $this->TicketView_m->update_cat1();
    redirect($_SERVER['HTTP_REFERER']);
}

Model:

function update_cat1(){
    $ticket_id = $_POST['ticket'];
    var_dump($cat = $_POST['data']);

    $this->db->set('vCategory',$cat);
    $this->db->where('cTicketNo',$ticket_id);
    $this->db->update('tconcerns');
}

THanks for all the help!

  • 写回答

1条回答 默认 最新

  • doudong2149 2017-03-22 08:06
    关注

    Drop that redirect($_SERVER['HTTP_REFERER']);, You don't need that.

    First of all, AJAX will allow you to send data to server without redirecting to another page.

    Based on your AJAX dataType. It is JSON. So for you to get the result, You have to encode it to JSON like json_encode(['result' => 'things you want to show']).

    Then you can access it in your response like this:

    success:function(response){
        alert('successful');
        var res = response.result; //Access the JSON
        $("#certainDiv").html( res ); //Print to the div you want
    }
    

    And it is also better to get the post request in your controller then pass it to your model:

    function update_cate(){
        $ticket_id = $this->input->post('ticket');
        $cat1      = $this->input->post('cat1');
        $this->TicketView_m->update_cat1($ticket_id, $cat1);
    
        echo json_encode(['result' => 'things you want to show']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?