Ajax request with Error Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Guys, good afternoon !

I am setting up a location manager, and I am having trouble querying the required fields, it is returning Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Jquery.js: 9664 post http://localhost/project/restrict/ajax_save_locais 500 (Internal Server Error)

Follow my code:

Form:

<div class="form-group">
                    <label class="col-lg-2 control-label">Local</label>
                    <div class="col-lg-10">
                        <input id="local_name" name="local_name" class="form-control" maxlength="100">
                        <span class="help-block"></span>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-lg-2 control-label">Imagem</label>
                    <div class="col-lg-10">
                        <img id="local_img_path" src="" style="max-height: 400px; max-width: 400px;">
                        <label class="btn btn-block btn-primary">
                            <i class="fa fa-upload"></i>&nbsp;&nbsp;Importar imagem
                            <input type="file" id="btn_upload_local_img" style="display: none;" accept="image/*">
                        </label>
                        <input id="local_img" name="local_img">
                        <span class="help-block"></span>
                    </div>
                </div>

Function is_duplicated:

    public function is_duplicated($field, $value, $id = NULL) {
    if (!empty($id)) {
        $this->db->where("locais_id <>", $id);
    }
    $this->db->from("locais");
    $this->db->where($field, $value);
    return  $this->db->get()->num_rows() > 0;
}

Function ajax_save_locais:

public function ajax_save_locais() {


    if (!$this->input->is_ajax_request()) {
        exit("Nenhum acesso de script direto permitido!");
    }

    $json = array();
    $json["status"] = 1;
    $json["error_list"] = array();

    $this->load->model("local_model");

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

    if (empty($data["local_name"])) {
        $json["error_list"]["#local_name"] = "Nome do local é obrigatório!";
    } else {
        if ($this->local_model->is_duplicated("local_name", $data["local_name"], $data["locais_id"])) {
            $json["error_list"]["#local_name"] = "Nome do local já existente!";
        }
    }

    if (!empty($json["error_list"])) {
        $json["status"] = 0;
    } else {

        if (!empty($data["local_img"])) {

            $file_name = basename($data["local_img"]);
            $old_path = getcwd() . "/tmp/" . $file_name;
            $new_path = getcwd() . "/public/images/locais/" . $file_name;
            rename($old_path, $new_path);

            $data["local_img"] = "/public/images/locais/" . $file_name;
        }

        if (empty($data["locais_id"])) {
            $this->local_model->insert($data);
        } else {
            $locais_id = $data["locais_id"];
            unset($data["locais_id"]);
            $this->local_model->update($locais_id, $data);
        }
    }
echo json_encode($json);

JavaScript:

function showErrorsModal(error_list) {
clearErrors();

$.each(error_list, function(id, message) {
    $(id).parent().parent().addClass("has-error");
    $(id).siblings(".help-block").html(message)
})

}

$.ajax({
            type: "POST",
            url: BASE_URL + "restrict/ajax_save_locais",
            dataType: "json",
            data: $(this).serialize(),  
            beforeSend: function() {
                clearErrors();
                $("#btn_save_locais").siblings(".help-block").html(loadingImg("Verificando..."));
            },
            success: function(response) {
                clearErrors();
                if (response["status"]) {
                    $("#modal_locais").modal("hide");
                } else {
                    showErrorsModal(response["error_list"])
                }
            }
        })
        return false;
    })
Author: João Lima, 2019-04-23

3 answers

Hello @ João Lima, all right?!

Looking at the code, apparently everything is normal. Ideally you would use a block try and catch to perform exception handling.

You can also add the error parameter in your ajax configuration to handle this exception on the front-end. Example:

try {
    if (empty($data["locais_id"])) {
        $this->local_model->insert($data);
    } else {
        $locais_id = $data["locais_id"];
        unset($data["locais_id"]);
        $this->local_model->update($locais_id, $data);
    }
} catch (\Exception $e) {
    $errorMessage = $e->getMessage();
    die($errorMessage);
}

And you can handle this exception with ajax:

success: function(response) {
    clearErrors();
    if (response["status"]) {
        $("#modal_locais").modal("hide");
    } else {
        showErrorsModal(response["error_list"])
    }
},
error: function (error) {
    console.log(error.responseText);
}
 1
Author: Victor Carnaval, 2019-04-23 17:28:35

Hey, Beauty John?

Error 500 (Internal Server Error), is a type of http status that the webservice (Apache/Nginx or IIS) returns when it fails to specify the actual error that occurs internally while accessing the site, or, in your case, the server response.

It can occur for some specific reasons, such as:

Setting parameters incorrectly through a file .htaccess; High use of resources or timeout; Incorrect file permissions (Linux); High number of simultaneous accesses on the site; URL and PHP directive rewriting errors.

I suggest you check the routes.

 0
Author: Hiury B. Bressanelli, 2019-04-23 16:40:22

Hi, I already answered something like that, this is the link and the answer below, I hope it helps: Error 500 more specific

Creating an asynchronous version and asking PHP to show the errors:

#início do arquivo
error_reporting(E_ALL);
ini_set('display_errors', 'on');
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/erro.log"); 

/ / I'm not sure if this fixes the delay you said You had to try to make this asynchronous URL practical, it might help:

$.ajax({
    statusCode: {
        500: function() {
        console.log(versao-assincrona.php?var1&var2...);
        }
      }
   });

This gives me speed, as Error 500 appears and I already test the asynchronous URL in another tab with php displaying the error.

I solve like this, but it can have better ways.

I hope I helped

 0
Author: Leonardo Negrão, 2019-04-23 19:17:56