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

Asked

Viewed 6,902 times

0

Everybody, good afternoon, everybody !

I’m setting up a local manager, and I’m having trouble searching the required fields, 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_local 500 (Internal Server Error)

follows 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_places:

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;
    })

3 answers

1

Hello @João Lima, all right?!

Looking at the code, apparently everything is normal. Ideally you would use a block try and catch to carry out the manipulation of exceptions.

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 manipulate 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);
}

0

Hey, Beauty John?

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

It may occur for some specific reasons, such as:

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

I suggest you check the routes.

0

Hi, I’ve answered something similar, this is the link and the answer below, I hope it helps: More specific error 500

Creating an asynchronous version and asking PHP to show 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 corrects the delay you said you had to try to make this asynchronous URL practical, maybe this will 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 errors.

I solve it like this, but there may be better ways.

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.