I'm sending value named text
from my <script>
tag that is in a .blade.php
file to controller by using POST
Ajax request. If I do not write $.post
function then it gives me output of text value in console. BUT when I write this Ajax request to send data to controller value do not pass. In short, I want to pass value from View to Controller and I am unable to do that. I have tried all YouTube tutorials and previous Stack Overflow questions. I also visited Laracasts but problem is not solved. Am I doing something wrong? Please help. Thank you.
shopReq.blade.php:
{{csrf_field()}}
<script>
$(document).ready(function(){
$('.ourItem').click(function(event){
var text=$(this).text();
$('#addItem').val(text);
console.log(text);
$.post('shopReq',{'text':text,'_token':$('input[name=_token]').val()}),function(data){
console.log(data);
});
});
});
</script>
Web.php:
Route::post('shopReq','UserController@special');
Controller:
class UserController extends Controller
{
public function special(Request $request){
$articles = DB::table('shoppingtrips')->get();
echo"DONE";
// return $request->all();
}
}
Try the below ajax
syntax:
$.ajax({
url: 'your route',
method: 'post',
data: {
key1: value1
// you can send more such key value pair here
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response){
}
});
Don't forget to add CSRF-TOKEN
, otherwise you will get the 500 (Internal Server Error) as it is required with post request.
in your layout.blade.php
file add this to your head tag:
<script type="text/javascript">
// laravel ajax helpers
var APP_URL ={!! json_encode(url('/')) !!};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
}
});
</script>
Then, in your view, do this:
<script>
$(document).ready(function(){
$('.ourItem').click(function(event){
var text=$(this).text();
$('#addItem').val(text);
console.log(text);
$.ajax({
url: APP_URL+'/shopReq',
method: 'post',
data: {
text: text
},
success: function(response){
console.log(response);
}
});
});
});
</script>
In your controller, do this:
class UserController extends Controller
{
public function special(Request $request){
$text = $request->input('text');
// do stuff with $text
}
}