How do I post a form in laravel 5 using ajax

0 votes

I want to be able to show errors using jquery after validation but I have no idea how to access the object sent to my controller; so I dont even know what to 'return' in the controller. Can someone please walk me through this?

This is a part of my view

<meta name="_token" content="{{ csrf_token() }}" />            
<div class='row'>
        {!! Form::open(['url'=>'register','id'=>'sign-up','class'=>'col-md-6 col-md-push-4 form-horizontal'])!!}

            <div class='form-group'>
                {!! Form::label('first_name', 'First Name:',['class'=>'col-xs-12 col-md-3']) !!}
                <div class= 'col-xs-12 col-md-6'>
                    {!! Form::text('first_name', null, ['class' => 'form-control'])!!}
                </div>
            </div>
            <div class='form-group'>
                {!! Form::label('last_name', 'Last Name:',['class'=>'col-xs-12 col-md-3']) !!}
                <div class= 'col-xs-12 col-md-6'>
                    {!! Form::text('last_name', null, ['class' => 'form-control'])!!}
                </div>
            </div>
            <div class='form-group'>
                {!! Form::label('email', 'Email Address:',['class'=>'col-xs-12 col-md-3']) !!}
                <div class= 'col-xs-12 col-md-6 '>
                    {!! Form::text('email', null, ['class' => 'form-control'])!!}
    <div class='form-group'>
            {!! Form::label('password', 'Password:',['class'=>'col-xs-12 col-md-3']) !!}
                <div class= 'col-xs-12 col-md-6'>
                    {!! Form::password('password', null, ['class' => 'form-control'])!!}
                </div>
            </div>

                    <div class='form-group'>
            {!! Form::label('password_confirmation', 'Confirm Password:',['class'=>'col-xs-12 col-md-3']) !!}
                <div class= 'col-xs-12 col-md-6'>
                    {!! Form::password('password_confirmation', null, ['class' => 'form-control'])!!}
                </div>
            </div>
                    </div>  <div class='btn btn-small'>
                {!! Form::submit('Join Us!',['class'=>'btn btn-success btn-sm form-control'])!!}
            </div>

        {!! Form::close() !!}
        </div>

.js file:

$(function(){

$('#sign-up').on('submit',function(e){
    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    })
    e.preventDefault(e);

        $.ajax({

        type:"POST",
        url:'/register',
        data:$(this).serialize(),
        dataType: 'json',
        success: function(data){
            console.log(data);
        },
        error: function(data){

        }
    })
    });
});

controller:

<?php 

namespace App\Http\Controllers;

use App\Http\Requests\CreateRegisterRequest;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\HttpResponse;
use Input;
class UserController extends Controller
{

    public function create(CreateRegisterRequest $request)
    {

    }

    public function show()
    {
        return view('user.profile');
    }

}

Form Request:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateRegisterRequest extends Request
{
    public function authorize()
    {
        return true;
    }
public function rules()
    {
        return [
            'first_name' =>'required',
            'last_name'=>'required',
            'url'=>'url',
            'description',
            'email'=>'unique:users,email|email',
            'password'=>'min:6|confirmed',
            'password_confirmation'=>'min:6'


        ];
    }
}
Jun 11, 2020 in Java-Script by kartik
• 37,510 points
2,460 views

1 answer to this question.

0 votes

Hello @kartik,

You can solve this error by follow this three steps:

1.In your example you use POST, so let's go with that. 

  • You already called the JQuery serialize method, so that's all you need to do. In your Laravel controller, simply take the argument Request $request for the method
  •  The Laravel method $request->input() will give you a key/value array of all the parameters sent in the request. You can then handle them accordingly.

2.In your Laravel controller, you can add the following line at the end of your method to return some JSON:

return response()->json($data);

In this example, $data is an array containing the JSON you want to return. In PHP, we can represent a JSON string as an array of key/value pairs, like so:

$data = [
    'success': true,
    'message': 'Your AJAX processed correctly'
];

3.You need to register the route to your controller. Then, you can simply call that URI using the JQuery AJAX object and then the injected variable data will be whatever was returned from the controller, in this case a JSON string.

Hope this is helpful!!

Thank You!!

answered Jun 11, 2020 by Niroj
• 82,880 points

Related Questions In Java-Script

0 votes
1 answer

How do I include a JavaScript file in another JavaScript file?

Hello @kartik, It is possible to dynamically generate ...READ MORE

answered Jul 27, 2020 in Java-Script by Niroj
• 82,880 points
571 views
0 votes
1 answer

How do I send a cross-domain POST request via JavaScript?

Hello @kartik, Follow this steps: Create an iFrame, put a ...READ MORE

answered Jul 27, 2020 in Java-Script by Niroj
• 82,880 points
1,332 views
0 votes
1 answer

How do I POST urlencoded form data with $http without jQuery?

Hello @kartik,  I think you need to do ...READ MORE

answered Jul 27, 2020 in Java-Script by Niroj
• 82,880 points
11,888 views
0 votes
1 answer

How do I add arbitrary html attributes to input fields on a form?

Hello @kartik, If you are using ModelForm, apart from ...READ MORE

answered Jul 27, 2020 in Java-Script by Niroj
• 82,880 points
656 views
0 votes
1 answer

Error:Sending Form file with form using AJAX

Hello @kartik, Don't pass the files into the ...READ MORE

answered Jun 16, 2020 in PHP by Niroj
• 82,880 points
3,445 views
0 votes
1 answer

How to return AJAX response Text?

Hello @kartik, What you need to do is ...READ MORE

answered Jun 18, 2020 in Java-Script by Niroj
• 82,880 points
11,083 views
0 votes
1 answer

How do I modify the URL without reloading the page?

Hii @kartik, HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you ...READ MORE

answered Jun 20, 2020 in Java-Script by Niroj
• 82,880 points
5,056 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,880 points
21,898 views
0 votes
1 answer

How do I turn a string to a json in Node.js?

Hello Kartik, Use the JSON function  JSON.parse(theString) ...READ MORE

answered Apr 24, 2020 in Java-Script by Niroj
• 82,880 points
778 views
0 votes
1 answer

How to send data in request body with a GET when using jQuery $.ajax()?

Hello @kartik, Sending the data in your scenario,I ...READ MORE

answered Jun 18, 2020 in Java-Script by Niroj
• 82,880 points
18,109 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP