2

Hello i wnat to send my data with ajax to my controller.

My CODE

AJAX

  $.ajax( {
    type:'POST',
    header:{
      'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
    },
    url:"{{route('race.post')}}",
    data:{
      _token: "{{ csrf_token() }}",
      dataType: 'json', 
      contentType:'application/json', 
    }


})
.done(function() {
    alert('success');
})
.fail(function() {
    alert("error");
});

CONTROLLER

 public function Points(Request $request){
    $test = $request->input('data');
    return "$test";
}

ROUTE

Route::post('updateC', ['uses' =>'RacesController@Points', 'as' => 'race.post']); 

And there are the errors what i get.

Console

Network-preview

Network-Response

Patrik
  • 41
  • 1
  • 1
  • 5
  • I think You have separate .js file for ajax. that's why your route and csrf_token is not working. – ThataL Mar 07 '19 at 09:48
  • That's true i have separetad js file for ajax. – Patrik Mar 07 '19 at 09:49
  • Thats why it is not working. for csrf_token use meta tag. and for url pass url as parameter to javascript onclick, or Onchange function. can i see your .js fiile when the ajax will call.. – ThataL Mar 07 '19 at 09:52
  • try my answer as below. I have changed the code by comparing previous and current question of you. – ThataL Mar 07 '19 at 10:05

8 Answers8

7

I just removed the slash at the end of url and it began working... /managers/games/id/push/ to:

$http({
  method: 'POST',
  url: "/managers/games/id/push",
Harry Bosh
  • 3,611
  • 2
  • 36
  • 34
  • OMG, this is what was happening to me! I can't believe I have lost 3 hours looking for the error! Thanks! – Janbalik Oct 02 '20 at 14:42
  • Thanks a ton Harry, I was searching for a solution for last half an hour. It worked – Arshi Oct 01 '21 at 11:44
  • This solution possibly works when your server configuration is different than laravel valet config. My endpoint works fine on valet hosted local environment even when there is '/' at the end but on my serverpilot deployment behind cloudflare, it was failing with 405. – İlter Kağan Öcal Oct 09 '21 at 11:12
1

add this one in your layout.blade file

<meta name="csrf-token" content="{{ csrf_token() }}">

then use this one in your js code

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

i hope this will help!!

sandip bharadva
  • 629
  • 1
  • 6
  • 19
1

First thing is we put two routes in one for displaying view and another for post ajax. So simple add both routes in your route file.

routes/web.php

Route::get('ajaxRequest', 'RacesController@Points');

Route::post('ajaxRequest', 'RacesController@Points');

Include this meta tag inside your view

<meta name="csrf-token" content="{{ csrf_token() }}" />

Include javascript code inside your ajax call

$.ajaxSetup({

    headers: {

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

    }

}); 
Optimaz Prime
  • 857
  • 10
  • 11
0

Since you are working in a JavaScript file and not in a Blade file, the route() helper method is not working, and the route 'race.post' isn't parsed to an url.

Try to change the url to this:

url: '/updateC'

When you want to use the route() helper in your JavaScript, you have to add the script to a Blade file, and json_encode the value, you can read more about this in this answer.

piscator
  • 8,028
  • 5
  • 23
  • 32
  • When i used this way `url: '/updateC'` it just say method 405(Method not allowed). – Patrik Mar 07 '19 at 09:39
  • Try to run `php artisan route:list` and compare the route with the one in your console / network tab. Adapt the route in your ajax call to the one that is shown in your route list. – piscator Mar 07 '19 at 09:40
  • It say to use `createPoints` but when i used it the error is 419(Unknown status). – Patrik Mar 07 '19 at 09:45
  • @Patrik check my answer (comment) from your previous question. – ThataL Mar 07 '19 at 09:45
  • 1
    Nice, that means this issue is resolved. A 419 means the `csrf_token` is wrong. Does this meta tag exist in your blade file: ``? Try to log if jQuery finds the value of the csrf token. – piscator Mar 07 '19 at 09:49
0

I have different way to use it: AJAX

data = {
        selectmanufacturer: selectmanufacturer,
        categories: selectCategory,
        _token: "{{csrf_token()}}",
        productName: productName
      };
     $.ajax({
        url: '{{URL::to('/all-products-data')}}',
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function (response) {
        },
          error: function (response) {
            alert(response);
          }
        });

Controller:

public function Points(Request $request){
    $test = $request->all();
    return "$test";
}

I hope It will be helpful to you

Kinjal
  • 91
  • 2
  • 9
0

The URL you’re posting to doesn’t look right in the console output you posted. In your AJAX code, you have this:

url:"{{route('race.post')}}"

But that’s just getting interpreted as is, it’s not getting interpreted as the value of that route in Laravel.

You’ll need to make sure that your JavaScript code is in a Blade template if you want Blade tags parsed.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
0

not type: "POST", method :'POST" try the below code i have modified. ref: Reference Link HTML code

<button onClick="onBtnClick()" data-url="{{route('race.post')}}"></button>

Updated Code

function onBtnClick(){
    var token = $('meta[name="csrf-token"]').attr('content');
    var url = $(this).attr("data-url");    
    $.ajax( {
        method:'POST',
        header:{
          'X-CSRF-TOKEN': token
        },
        url: url,
        data:{
          _token: token,
          dataType: 'json', 
          contentType:'application/json', 
        }        
    })
    .done(function() {
        alert('success');
    })
    .fail(function() {
        alert("error");
    });
}
ThataL
  • 165
  • 3
  • 12
0

Check if your laravel route is correctly set for this request. In my case, I had a $.ajax url: "crop-image-upload" and a Route::post('crop-image-upload ', 'CropImageController@uploadCropImage'); But the request was sent to http://127.0.0.1:8000/news/crop-image-upload So I had to change my route to Route::post('/news/crop-image-upload ', 'CropImageController@uploadCropImage');

So, in your case, try to add a literal url on ajax like this:

url:"/races/updateC"

and add 'races/' in the route like this:

Route::post('/races/updateC', ['uses' =>'RacesController@Points', 'as' => 'race.post']);