Template chiamata Ajax Laravel
Updated at: 17/05/2018


Chiamata AJAX

public function salva_conferma_doc(Request $request) {
    $out = array("stato" => "KO", "message" => "", "campi_errati" => array());
    $model_name = $this->model_name;

    try{
        $this->existing_obj = $existing_obj = $model_name::findOrFail($request->input('obj'));
        $id = $this->existing_obj->getKey();
    }catch(\Exception $e){
        $out["message"] = "Item not found";
        return json_encode($out);
    }

    $id_doc = $request->input('id');

    //##########  permessi  #################

    if(\Auth::user()->cant("approva_allegato",  [$existing_obj,$id_doc])){
        $out["message"] = "permission denied";
        return json_encode($out);
    }

    //varie azioni che deve fare

    $out["stato"] = "OK";
    return json_encode($out);
}

In JS

$.ajax({
    url: url,
    method: "POST",
    data: datastring,
    dataType: "json",
    success: function (json_risposta) {
        if (json_risposta.stato === "OK"){
            //quello che deve fare
        }else{

        }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        //messaggio o gestione dell’errore
        console.log("Status: " + textStatus);
        console.log("Error: " + errorThrown);
    }
});