Using ajax serialize in Laravel

Asked

Viewed 541 times

4

What I need

When the user clicks on the submit button the 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 it is false it lets the form 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 Blade and did the type="button" pure html for not finding 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 the send it gives this Alert with all the html code of the result. I copied the code to an empty page and it resulted me in this image. Because he is giving this problem with the token ? inserir a descrição da imagem aqui

  • Where does the #formBarcodeId ?

1 answer

4


I don’t know if only 'check' works in your 'url' inside ajax.

Try to use:

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

From what I understand the problem is the ajax find the function in the Laravel.

I made a code in simple ajax with Laravel and it worked, try it, if it doesn’t work I would say it is some basic configuration pending from 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 in the Controller:

function verificarBarcode(){
    return 'olá mundo';
}
  • So I get "You don’t have permission to access /Barcode/public/{{ URL::to('verifiBarcode') }} on this server."

  • Try putting Route::any instead of :post

  • Certinho, fera. I was forgetting to put in the form the id formBarcodeId.

Browser other questions tagged

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