ThiTle
ThiTle

Reputation: 35

Passing data from Laravel 7 view to controller via Ajax

I need to pass only one value from view to controller,using Ajax(in View home.blade.php). All solutions are for Laravel 5's and it's not helpful.

Ajax from home.blade.php:

$datee="hello";

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

 $.ajax({
    type        : 'POST',
    url         : "insert2",
    contentType: "text",
    data:      datee ,
    dataType: 'json'
  });

Route:

Route::post('/insert2/{datee}', 'EditContdroller@show1');
Route::get('/home', 'HomeController@index')->name('home');

And EditController's method:

  public function show1(Request $request){

                         $data= $request->datee;
//some work with $data...
                         return $json_Value;

    }

I get Error 404 Post .../insert2 not found.Have you any idea,please?

Upvotes: 0

Views: 2383

Answers (1)

tomJO
tomJO

Reputation: 371

Route::post('/insert2/{datee}', 'EditContdroller@show1');

url:"insert2",

Your post route requires additional parameter, but you request without parameter

It should be url: "insert2/something"

Now in Controller the "something" you passed will become variable {datee}

If you want to make the parameter optional, you should add question mark to {datee} making it {datee?} then your AJAX request should work: (I added '?' question mark to the date)

Route::post('/insert2/{datee?}', 'EditContdroller@show1');

You are passing:

data: datee,

It doesn't work like this.

To pass the datee, I would recommend doing so:

Remove the {datee} part

Route::post('/insert2', 'EditContdroller@show1');

In your AJAX request modify your data like this:

data: { datee: datee },

In your Controller access datee value like this:

$datee = $request->input('datee');

Upvotes: 1

Related Questions