Using ajax serialize in Laravel

4

What I need

When the user clicks the send button, ajax will call a method of a class to check if the typed text already exists and in a table. It returns the result, if false it leaves the form to be sent and the field is registered in the bd, otherwise it will present an alert with the typed text and that it already exists.

What I did

I created the form using the blade and made the type="button" in pure html for not finding it in the Laravel documentation.

home.blade.php

{!! Form::open(array('action' => 'HomeController@gerarPdf','method' => 'POST')) !!}
    {!! Form::text('numeroDocumento[]', null,array(
        'placeholder' => 'Código da Entidade',
        'maxlength' => '5',
        'required' => ''
    )); !!}
    <input type="button" value="Gerar Código" name="submitBarcode" id="submitBarcode" required/>
{!! Form::close() !!}

routes.php

Route::post('verificarBarcode', 'HomeController@verificarBarcode');

js

$('#submitBarcode').click(function () {
        $.ajax({
            type: 'post',
            url : 'verificarBarcode',
            cache: false,
            dataType: 'json',
            data: $('#formBarcodeId').serialize(),
            success : function(msg){
                if (msg.status == 0) {
                    alert("Tem Coisa Repetida");
                }
                else{
                    alert("Não Tem Coisa Repetida");
                }
            },
            error:function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText);
            }
        });
    });,

When I click on submit it gives this alert with all html result code. I copied the code to an empty page and it resulted in that image. Why is he giving this token problem?

    
asked by anonymous 27.02.2015 / 14:03

1 answer

4

I do not know if just 'checkingBarcode' works in your url within ajax.

Try using:

url: "{{ URL::to('verificarBarcode') }}";

So I realized the problem is that ajax finds the function in laravel.

I made a simple ajax code with laravel and it worked, try to do that, if it does not work I would say it is some outstanding basic configuration of laravel, but try the code below to test the connection:

Javascript

$(function(){
    $.ajax({
        type: 'post',
        url : 'verificarBarcode',
        cache: false,
        data: { name: 'rodrigo' }
    }).done(function(msg){
        alert(msg)
    });
});

Route:

Route::post('verificarBarcode', 'HomeController@verificarBarcode');

Function on Controller:

function verificarBarcode(){
    return 'olá mundo';
}
    
02.03.2015 / 22:54