使用AJAX将数据发送到Coder Igniter控制器函数会导致500内部服务器错误


Using AJAX to send data to Coder Igniter controller function results in a 500 Internal Server Error

我正在尝试使用AJAX将数据从Code Igniter视图发送到控制器,该控制器将根据需要处理数据。我使用JQuery插件(Handontable)收集数据,当用户点击"保存"按钮时,它会从表中提取所需的数据并执行ajax函数。

$.ajax({
    url: "/survey/save",
    data: {"data": data},
    type: "POST",
});

我可以将它发送到一个常规的.php文件,该文件使用$_POST收集数据,但不使用我的控制器。

public function save() {
    $data = $this->input->post('data');
    $myFile = "testFile.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");    
    for ($i = 0, $size = count($data); $i < $size; ++$i) {
        fwrite($fh, $data[$i][0]."'t".$data[$i][1]."'t".$data[$i][2]."'n");
    }
    fclose($fh);
}

上面的代码不是我真正希望控制器做的,但如果能成功执行这些代码,我就可以随心所欲了。

我觉得这与ajax函数的URL有关,但我对所有这些语言都非常陌生,可能忽略了一些简单的东西。请让我知道我是否应该包括任何其他代码!

嘿,你必须在ajax url中更改url的格式必须是绝对路径,例如

视图中,ajax应该是这样的

$.ajax({
        url:'<?php echo site_url('survey/save'); ?>',
        type: 'post',
        data:  "data="+data,
        beforeSend:function(){
                //before send code for e.g. put a loader
        },
        success:function(result){ 
            // success result code goes here
        },
        error:function(jqXHR, status, error){
            if(status!='error')
                alert(error);   
        }
    });

现在,在控制器中,您可以获得数据

$data=$this->input->post('data');

还有一件事,当你使用fopen进行时,你必须使用相对路径

//您已使用

$myFile = "testFile.txt";
//instead of that you have to use
$myFile="./YOUR_FOLDER_NAME/YOUR_FILE_NAME";

您可以在config.php中进行设置

$config['base_url'] = '';

回答我自己的问题,以防对他人有所帮助。问题出在我的csrf设置上。我意识到关闭csrf保护解决了这个问题,但我不想关闭csrf防护。我认为CI可能已经发布了一个白名单来解决这个问题,但是我只是编辑了我的配置文件如下:

if(stripos($_SERVER["REQUEST_URI"],'/survey') === FALSE)
{
    $config['csrf_protection'] = TRUE;
}
else
{
    $config['csrf_protection'] = FALSE;
} 

如果您已经在CI Application/config文件夹中完成了配置文件

$config['base_url'] = 'http://yourwebsite.com/';

那么你的网址是

"<?php echo base_url();?>survey/save", 

尝试此代码的非常简单的方法:

首先,您必须在application/confiq.php中设置baseurl或使用.htaccess

您的脚本:

<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function m_ajax()
{
   var ids = $("#all_users").val();
   $.ajax({
      type:"POST",
      url: base_url+"history/home/get_users",
      data: "userid=" + ids,
      success: function(result){
        $("#m_ajax").html(result);
    }
    });
}
</script>

在你的控制器中,你可以获得userid的值作为后

 $userid = $this->input->post('userid');

您可以根据执行其他操作。