I would like to send an array with elements to my laravel controller with vanilla JS, (I don't want to use Jquery). But I can't get it work... I found several solutions on web with trying to make a json object and so on but nothing wanted to work...
This is my code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
alert('sent');
}
};
xhttp.open("GET", '{{route('profile.toggleCategory', $user)}}', true);
xhttp.send(categories);
and my laravel controller:
public function toggleCategory(Request $request, User $user)
{
dd($categories = $request->categories);
$user->categories()->sync(collect($categories));
}
I changed a few things and now it is working!
The working code:
web.php:
Route::post('{user}/togglecategory', 'Site\ProfileController@toggleCategory')->name('toggleCategory');
Javascript code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
alert('send');
}
};
xhttp.open("POST", '{{route('profile.toggleCategory', $user)}}', true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
xhttp.send("categories="+categories);
});
Laravel Controller:
public function toggleCategory(Request $request, User $user)
{
$categories = explode(',', $request->categories);
$user->categories()->sync($categories);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.