First working prototype of POST request from JavaScript to Laravel Controller

This commit is contained in:
Torsten 2022-06-11 11:19:17 +02:00
parent 420cd3ce63
commit 07ce7961c9
2 changed files with 23 additions and 58 deletions

View file

@ -220,18 +220,14 @@ class LeaguesController extends Controller
$input=$request->input(); $input=$request->input();
Log::info("Params:".sizeof($input)); Log::info("Params:".sizeof($input));
foreach ($input as $key => $value) { foreach ($input as $key => $value) {
Log::inf( $key."=>".$value ); Log::info( ">".$key."=>".$value );
} }
Log::info($request->input('user1', 'not_set')); Log::info($request->input('user1', 'not_set'));
//Log::info("Request-param:" . request('user1'));
/*
$user1_id=request('user1_id');
$user2_id=request('user2_id');
error_log("User1:".$user1_id);
error_log("User2:".$user2_id);
error_log()
*/
} }
public static function showSingleUserMatches($userId) { public static function showSingleUserMatches($userId) {

View file

@ -88,62 +88,31 @@
} }
alert("Tauschen:\n"+selected_players.join("\n")); alert("Tauschen:\n"+selected_players.join("\n"));
xmlhttp=new XMLHttpRequest() let url = '/league/swap';
let token = '{{ csrf_token() }}'
var formData=new FormData() fetch(url, {
//alert(inputElems[0].id);
formData.append('user1',inputElems[0].id)
formData.append('user2',inputElems[1].id)
let params="user1=test&user2=test2"
xmlhttp.open("POST",'/league/swap')
xmlhttp.setRequestHeader('Content-Type', 'application/json')
xmlhttp.setRequestHeader('X-CSRF-Token', '{{ csrf_token() }}')
//xmlhttp.send(params)
xmlhttp.send(formData)
return;
// For POST, we need a configuration object for the fetch call
const update = {
title: 'A blog post by Kingsley',
body: 'Brilliant post on fetch API',
userId: 1,
};
console.log("Before stringify")
const options = {
method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', "Content-Type": "application/json",
'X-CSRF-Token': '{{ csrf_token() }}' "Accept": "application/json, text-plain, */*",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-TOKEN": token
}, },
body: JSON.stringify(update), method: 'post',
}; credentials: "same-origin",
console.log(JSON.stringify(update)) body: JSON.stringify({
console.log("After stringify") user1: inputElems[0].id,
user2: inputElems[1].id
fetch('/league/swap', options) })
.then(data => { }).then((data) => {
if (!data.ok) { window.location.href = redirect;
throw Error(data.status); })
} .catch(function(error) {
return data.json(); console.log(error);
}).then(update => {
console.log(update);
}).catch(e => {
console.log("There is some error")
alert(e)
console.log(e);
}); });
} }
}) })
</script> </script>