laravel 5 ajax request controller app not working

2019-09-18 09:46发布

i want to use this code buy it stays in Procesando, espere por favor....

Jquery:

function realizaProceso(valorCaja1, valorCaja2){

        var parametros = {
            "valorCaja1" : valorCaja1,
            "valorCaja2" : valorCaja2
        };

        $.ajax({
            data:  parametros,
            url:   'ajax/pregunta',
            type:  'POST',
            beforeSend: function () {
                $("#resultado").html("Procesando, espere por favor...");
            },
            success:  function (data) {
                $("#resultado").html(data.resultado)
            }
        });

Html

    Introduce valor 1
<input type="text" name="caja_texto" id="valor1" value="0"/>


Introduce valor 2
<input type="text" name="caja_texto" id="valor2" value="0"/>

Realiza suma
<input type="button" href="javascript:;" onclick="realizaProceso($('#valor1').val(), $('#valor2').val());return false;" value="Calcula"/>
<br/>
Resultado: <span id="resultado">0</span>

Route

Route::post('ajax/pregunta', [
    'as' => 'ajax/pregunta', 'uses' => 'AjaxController@pregunta'
]);

Controller

<?php

namespace App\Http\Controllers;


use App\Http\Requests\Request;
use Illuminate\Support\Facades\Response;

class AjaxController extends Controller {
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function pregunta(){
        $resultado = Request::input('valorCaja1') + Request::input('valorCaja2');
        return response()->json(['resultado' => 'Roberto']);
    }
}

When i clic in "Calcula" button " Procesando, espere por favor..." apears in the screen but it dont load the succes code, any solution??

Thanks!!

1条回答
甜甜的少女心
2楼-- · 2019-09-18 10:27

I think that you need provide a token , i'm not sure but i believe that is necesary

in your page blabla.blade.php add

 <input type="hidden" name="_token" id="_token" value="{{{ csrf_token() }}}" />

and then in your ajax call

   var tok = $('#_token').val();

   var parametros = {
        "valorCaja1" : valorCaja1,
        "valorCaja2" : valorCaja2,
        "_token" = tok
    };

regards...

查看更多
登录 后发表回答