2

I've got a problem with sending data from javascript to my controller. There is my Ajax:

var point = JSON.stringify(points);

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

    $.post('http://localhost/updateC', {
        data: point,
        dataType: 'json', 
        contentType:'application/json', 
    })
    .done(function() {
        alert('success');
    })
    .fail(function() {
        alert("error");
    });

}

Routes:

Route::get('/home', 'HomeController@index')->name('home');
Route::resource('/races','RacesController');
Route::post('updateC', 'RacesController@Points');

And there is my RacesController:

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

And the error is saying that has been blocked by CORS-polices.

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Patrik
  • 41
  • 1
  • 1
  • 5
  • You need to add the x-csrf-token header, check out the documentation: https://laravel.com/docs/5.7/csrf – Joost Meijer Mar 04 '19 at 10:09
  • What is the data you have to post?... or show your form? – Inzamam Idrees Mar 04 '19 at 10:10
  • data are my points that i've created points[currentid] = {id: currentid, x: event.offsetX, y: event.offsetY}; currentid++; – Patrik Mar 04 '19 at 10:12
  • have you added `` in your ajax sending page. and please screenshot of your Browser console. Ajax request. – ThataL Mar 04 '19 at 10:16
  • I've tried in and still doesn't work.But here is my error [link](https://imgur.com/a/JRIwRae) – Patrik Mar 04 '19 at 10:24
  • @Patrik `Route::post('updateC', ['uses' =>'RacesController@Points', 'as' => 'race.post']); $.post("{{route('race.post')}}", {` Change the above code and try. If your access domain and ajax url domain is not same then url is also blocked. Your access url is 127.0.0.1 and ajax url is localhost. (ref your screenshot) – ThataL Mar 04 '19 at 10:48
  • Well i've done same searching by my self and the main error is now solved.I've tried your solution now and there is this other error [link](https://imgur.com/a/kd88h5N).And there is my new ajax ` $.ajax( { url:"{{route('race.post')}}", type:'POST', data:{ _token: "{{ csrf_token() }}", _method:'PUT', points:point, dataType: 'json', contentType:'application/json', } })` – Patrik Mar 04 '19 at 10:57
  • why you use `_method:'PUT'` this should be POST in route POST. screenshot of ajax respone from network tab it will help to understand the error. – ThataL Mar 04 '19 at 11:06
  • Someone told me when updating someting you should use method PUT so i tried it. There is the response [link](https://imgur.com/a/9bUFiOR). – Patrik Mar 04 '19 at 11:18
  • Ok if you use PUT method then in route also need to define as Route::PUT. change it and give it a try. also check the log file about the error. and the response image u uploaded is only the data u sent to server. but i need the response from the server. where error exeption is thrown. – ThataL Mar 04 '19 at 11:23
  • https://stackoverflow.com/questions/10883211/deadly-cors-when-http-localhost-is-the-origin check this – techie_28 Mar 05 '19 at 07:52
  • I've done some changes and the error disappear but another show up.. and it is this one [link](https://imgur.com/a/PFcDlsL). – Patrik Mar 05 '19 at 08:58
  • send screenshot eg. [https://imgur.com/DxBOpnF](https://imgur.com/DxBOpnF) – ThataL Mar 05 '19 at 11:28
  • Welll the are the screenshots and it looks interesting. [preview](https://imgur.com/a/LZQi0LN) and [response](https://imgur.com/a/iyNVpfd) – Patrik Mar 06 '19 at 10:11
  • its is because of csrf_token() if u used {{csrf_token()}} in .js file it will not compiled not going to work. ** – ThataL Mar 07 '19 at 09:24

4 Answers4

0

go the middleware folder, the verifycsrftoken file,

app/Http/Middleware/VerifyCsrfToken.php

and add this url to the except array

protected $except = [
   ....
   http://localhost/updateC
];

to handle exceptions to your ajax post requests, then you can then use the

Barryvdh Laravel Cors package to get rid of cors issue,

if you are using laravel 5.6, you dont need any CORs package for that,

just create a CORs Middleware

namespace App\Http\Middleware;
use Closure;
class Cors {

    public function handle($request, Closure $next) {
        $allowedOrigins = ['http://oursite.com', '*.myost.net','*','www.aminu.*'];
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        if (in_array($origin, $allowedOrigins)) {
            return $next($request)
                ->header('Access-Control-Allow-Origin', $origin)
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With, cache-control,postman-token, token')
                ->header('Access-Control-Allow-Credentials',' true');
        }
        return $next($request);
    }
}

and add middleware to the kernel.php file

protected $middleware = [
    ......
    \App\Http\Middleware\Cors::class, //added here
];
Ande Caleb
  • 1,163
  • 1
  • 14
  • 35
  • You may want to specify in your route the used middleware: `Route::post('/updateC', array('middleware' => 'cors', 'uses' => 'RaceController@point'));`, after registering this middleware in your `app\Http\Kernel.php` file. Source: https://stackoverflow.com/questions/33076705/laravel-5-1-api-enable-cors – Kévin Bibollet Mar 04 '19 at 10:34
  • I've registered it and used your Route and it still doesn't work. – Patrik Mar 04 '19 at 10:40
0

You have to add csrf token in your data property of ajax post like this:

data: {
    "_token": "{{ csrf_token() }}",
    "point": point
}
Inzamam Idrees
  • 1,955
  • 14
  • 28
0
app/Http/Middleware/VerifyCsrfToken.php

and add this route to the except array

protected $except = [
   'updateC'
];
Stefan
  • 8,819
  • 10
  • 42
  • 68
Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
0

Ajax code

var abc = 'hello world';

$.ajax({
    type: "GET",
    url: 'http://your url',
    data : { abc : abc }
    success: function (data) {

        // write your code
    },
    error: function (data) {
        // write your code
    }
});
Vipul Prajapati
  • 203
  • 2
  • 4