有没有办法在PHP出错的情况下停止ajax进程?

时间:2016-04-15 18:32:44

标签: php ajax codeigniter-3

我遇到了Firefox 45的问题。它总是说$_FILES['imagem']未定义且为null,即使之前已经从数据库中选择并显示了图像。仅在版本45中,我认为这是一个错误。

编辑过程是通过Ajax调用的,感谢这个错误,ajax会永远加载。我想知道是否有办法停止其过程并在视图中显示错误。

$FILES = $_FILES;
$count = count($_FILES['imagem']['name']) - 2;

for ($i = 0; $i <= $count; $i++) {
    $_FILES['imagem']['name'] = $FILES['imagem']['name'][$i];
    $_FILES['imagem']['name'] = $FILES['imagem']['name'][$i];
    $_FILES['imagem']['type'] = $FILES['imagem']['type'][$i];
    $_FILES['imagem']['tmp_name'] = $FILES['imagem']['tmp_name'][$i];
    $_FILES['imagem']['error'] = $FILES['imagem']['error'][$i];
    $_FILES['imagem']['size'] = $FILES['imagem']['size'][$i];

    if (isset($_FILES['imagem']) && $_FILES['imagem']['name'] !== '') {
        $config['file_name'] = $id . '_' . $_FILES['imagem']['name'];
        $config['upload_path'] = './uploads/carros/imagens/';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['overwrite'] = true;

        $imagem = array();
        $imagem['id_carro'] = $id;
        $imagem['imagem'] = $config['file_name'];

        $this->upload->initialize($config);
        $this->upload->do_upload('imagem');
        $this->Imagens_carro_model->insert($imagem);
    }

    //
    // Apagar caso haja.
    if ($this->input->post('nome_imagem')[$i] === '') {
        $this->Imagens_carro_model->delete($this->input->post('id_imagem')[$i]);
    }
}

以上是生成错误的代码的一部分:

  

严重性:注意

     

消息:未定义的索引:imagem

     

文件名:controllers / Carros.php

     

行号:161

     

...

我想我无法对error做任何事情,因为它实际上是成功的,并且当它没有找到imagem索引时,错误发生在PHP部分中。建议?

1 个答案:

答案 0 :(得分:0)

如果您从PHP发送精选回复,则可以检查回复,例如,成功的操作发送json响应(例如,这可能不是问题的准确答案,但是一个帮助OP处理ajax错误处理想法的想法:

if(somethingWasSuccessfull) {
    $response = [
        'success' => true,
        'message' => 'something was successful!'
    ];
}
else {
    $response = [
        'success' => false,
        'message' => 'something was not successful!'
    ];
}

echo json_encode(($response);

因此,当您在客户端收到done/success回调的回复时,您可以检查success的值,例如:

$.ajax(...)
.done(function(response) {
    // Request succeeded
    // Probably parse the response
    if(response.success) {
        // Successfull, status code is 200
    }
    else {
        // Not successfull, status code is 200
    }
})
.fail(function(response) {
    // Error happened..., status code is not 200
})
.always(function(response) {
    // Perform some common tasks
});