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']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pyinstaller打包错误
  • ¥20 cesm的气溶胶排放文件
  • ¥30 关于#wpf# devexpress的问题:选中时是黑色未选中是白色字体,想要更改未选中时字体的颜色(语言-c#)
  • ¥15 逐月累计,月份不连续,补齐月份
  • ¥15 应用简单的Python代码完成一个学生成绩管理系统
  • ¥15 用matlab求微分方程初值问题
  • ¥15 vscode下编写第三方库opencv与pcl代码时没有代码提示
  • ¥15 能够跑通不报错,如何解决?(标签-matlab)
  • ¥15 MOS在RDS较大,频率高时开关波形异常
  • ¥15 SCENIC分析报错求解答