Problem when making request with ajax in Laravel 5.4

Asked

Viewed 694 times

1

I am learning the web language for creating my website and using the Laravel 5.4 framework, and having problems with sending forms with ajax.

Every form I submit, returns me the error:

Unprocessable Entity{"Account":["The Account field is required."]}

when there are rules configured in Formrequest. I read in several places and some said it was because it wasn’t being sent in json, so I tried to find out how to do it and I tried to do it, but it still goes on. I removed the rules and var_dump the result and is returning me:

Okarray(0) { }

I have no idea where this "OK" is coming from or why the inputs are not being sent. My content:

Register.blade.php

@section('content')
    <div class="wpb_text_column wpb_content_element">
        <div class="wpb_wrapper">
            <div class="title-wrapper">
                <h3 class="widget-title" style="border-color: #34495e"><i class="fa fa-newspaper-o"></i> @lang('page.register.title')</h3>
                <div class="clear"></div>
            </div>
            <div class="wcontainer">
                <div class="formcontainer">
                    <form id="register" name="register" method="post" action="" onsubmit="$('#regresult').ajaxLoader('post', 'register', '#register'); return false;">
                        <table width="100%" style="border: 0">
                            <tr style="background: none">
                                <td width="50%" align="left">
                                    <strong>@lang('page.register.account')</strong>
                                    <input id="account" name="account" type="text" maxlength="10" tabindex="1" />
                                </td>
                                <td width="50%" align="right">
                                    <strong>@lang('page.register.pid')</strong>
                                    <input id="pid" name="pid" type="text" maxlength="7" tabindex="2" />
                                </td>
                            </tr>
                            <tr style="background: none">
                                <td align="left">
                                    <strong>@lang('page.register.password')</strong>
                                    <input id="password" name="password" type="text" maxlength="10" tabindex="3" />
                                </td>
                                <td align="right">
                                    <strong>@lang('page.register.rpassword')</strong>
                                    <input id="password_confirmation" name="password_confirmation" type="text" maxlength="10" tabindex="4" />
                                </td>
                            </tr>
                            <tr style="background: none">
                                <td align="left">
                                    <strong>@lang('page.register.mail')</strong>
                                    <input id="mail" name="mail" type="text" maxlength="30" tabindex="5" />
                                </td>
                                <td align="right">
                                    <strong>@lang('page.register.rmail')</strong>
                                    <input id="mail_confirmation" name="mail_confirmation" type="text" maxlength="30" tabindex="6" />
                                </td>
                            </tr>
                            <tr style="background: none">
                                <td align="left">
                                    <div class="g-recaptcha" style="width: 302px; margin: 0 auto" data-sitekey="{{ config('recaptcha.public_key') }}" data-tabindex="7"></div>
                                </td>
                                <td align="right">
                                    <input id="agree" name="agree" type="checkbox" tabindex="8" value="1" /> @lang('page.register.agree')<br />
                                    <input id="subscriber" name="subscriber" type="checkbox" tabindex="9" value="1" /> @lang('page.register.subscriber')
                                </td>
                            </tr>
                            <tr style="background: none">
                                <td colspan="2" align="center" width="100%" style="text-align: center">
                                    <button type="submit" style="width: 35%; margin: 0 auto;" tabindex="10">@lang('page.register.button')</button>
                                </td>
                            </tr>
                        </table>
                    </form>
                </div>
                <div id="regresult">
                </div>
                <div class="clear"></div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="https://www.google.com/recaptcha/api.js"></script>
@stop

Registerrequest.php

...

class RegisterRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
        ];
    }
}

Registercontroller.php

...

class RegisterController extends Controller
{
    public function create()
    {
        return view('page.register')
                ->renderSections()['content'];
    }

    public function store(RegisterRequest $request)
    {
        var_dump($request->all());
    }
}

web php.

// register
Route::get('register', 'Page\RegisterController@create');
Route::post('register', 'Page\RegisterController@store');

ajax.js

$.fn.extend({
    ajaxLoader: function(type, url, form) {
        var self = $(this);
        var data = '';

        if (form !== undefined) {
            data = $(form).serialize();
        }

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            type: type,
            url: url,
            data: data,
            beforeSend: function () {
                self.html('<div id="loading"></div>');
            },
            success: function(result) {
                self.html(result);
            },
            error: function(result) {
                self.html(result.statusText + result.responseText);
            }
        });
    }
});

I’ve been trying for hours to make it work and I haven’t had a positive process.

1 answer

2


Getulio,

I’m not familiar with Laravel, but I believe the problem is in the request. You set:

dataType: 'json', contentType: 'application/json; charset=utf-8'

But in the data you used jQuery serialize, which format is "querystring". I believe that if you change the contenttype to: 'application/x-www-form-urlencoded; charset=UTF-8' and remove the attribute dataType: 'json',should work .

Try this (Removing the taxes dataType and contenttype ajax will use the defaults values that is form-urlencoded):

        $.ajax({
        type: type,
        url: url,
        data: data,
        beforeSend: function () {
            self.html('<div id="loading"></div>');
        },
        success: function(result) {
            self.html(result);
        },
        error: function(result) {
            self.html(result.statusText + result.responseText);
        }
    });

Or you would need to convert querystring to json object before assigning it to 'date'.

  • I tested it that way too and it didn’t work. I used a function to convert querystring to json, but it didn’t work either. I have no idea where the problem is anymore. I was "sure" that it was in ajax, but I debugged and saw that the data are being sent and received in Aravel, but when I enable the Rules, I get error 422.

  • Have you ever tried not to use serialize? It doesn’t seem like it, but it doesn’t hurt to try. For example, return the attributes <code>dataType: 'json', contenttype: 'application/json; charset=utf-8'</code> and in the date pass element by element: <code>data: {id: $("#id"). val(), name: $("#name"). val() }</code>

  • 1

    The problem was in sending in json. I put to send normally, I kept the serialize and the rest followed the way I said and now it’s working. Thank you for your help! :)

  • Glad it all worked out Getulio!

Browser other questions tagged

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