使用ajax

时间:2017-02-03 14:51:35

标签: javascript php jquery ajax codeigniter

我想问为什么我的codeigniter在添加数据时会在保存过程时变为错误500内部服务器。我对此问题一无所知,请帮助我。

这是视图中的ajax代码

function save()
{
    $('#btnSave').text('menyimpan...'); //change button text
    $('#btnSave').attr('disabled',true); //set button disable 
    var url;

    if(save_method == 'add') {
        url = "<?php echo site_url('edulibs/ajax_add')?>";
    } else {
        url = "<?php echo site_url('edulibs/ajax_update')?>";
    }

    // ajax adding data to database
    $.ajax({
        url : url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {

            if(data.status) //if success close modal and reload ajax table
            {
                $('#modal_form').modal('hide');
                reload_table();
            }
            else
            {
                for (var i = 0; i < data.inputerror.length; i++) 
                {
                    $('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                    $('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
                }
            }
            $('#btnSave').text('Simpan'); //change button text
            $('#btnSave').attr('disabled',false); //set button enable 


        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('menambahkan / update data error');
            $('#btnSave').text('Simpan'); //change button text
            $('#btnSave').attr('disabled',false); //set button enable 

        }
    });
}

这是我的控制器

public function ajax_add()
    {
        $this->_validate();
        $data = array(
                'nama' => $this->input->post('nama'),
                'nim' => $this->input->post('nim'),
                'pembimbing1' => $this->input->post('pembimbing1'),
                'pembimbing2' => $this->input->post('pembimbing2'),
                'subyek' => $this->input->post('subyek'),
                'judul' => $this->input->post('judul'),
                'tanggal' => $this->input->post('tanggal'),
                'tautan' => $this->input->post('tautan'),

            );
        $insert = $this->edulibs->save($data);
        echo json_encode(array("status" => TRUE));
    }

1 个答案:

答案 0 :(得分:0)

首先在控制器中使用site_url()加载url帮助器。就像这样......

$this->load->helper('url');

application/config/autoload.php

中加载帮助器

在ajax的成功函数中使用JSON.parse()将你的json响应解析为object.Like this

success: function(response)
        {
            var data = JSON.parse(response);//OR var data = eval(response);
            if(data.status) //if success close modal and reload ajax table
            {
                //code here
            }
            else
            {
                //code here
            }