AJAX Post request in laravel 5.4 - ajax

Have anyone got issue in ajax post request in laravel 5.4. I am unable to get request data in controller.
Ajax request is something like this:
$.ajax({
data: { 'selected_data':[2,4,5] },
type: "POST",
url: "{{ url('test') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (res) {
console.log(res)
},
});
In controller method, i am just doing
dd($request->all());
But getting empty array. can anyone help me with this issue?
Thanks!

Instead of this:
$.ajax({
data: { 'selected_data':[2,4,5] },
type: "POST",
url: "{{ url('test') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (res) {
console.log(res)
},
});
Try this:
$.ajax({
data: { selected_data:[2,4,5], _token: "{{csrf_token()}}" },
type: "POST",
url: "{{ url('test') }}",
success: function (res) {
console.log(res)
},
});

Related

laravel send json object by ajax

$.ajax({
url: '{{ route('add.orders') }}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: JSON.stringify({
myArr : myArr
}),
cache: false,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
})
my controller:
public function addOrders(Request $request) {
return $request->myArr;
}
I'm getting this one:
this is myArr:
How can i reach the object? Why it seems [object Object]
Can i reach myArr[0].id
İf you help me i will be glad, thank you.
You have to use like below
for(var i=0;i<data.length;i++){
console.log(data[i].id);
console.log(data[i].food_title);
}
$.ajax({
url: "{{ route('add.orders') }}",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{ myData: JSON.stringify(myArr),_token:"{{ csrf_token() }}" },
cache: false,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log(data);
}
});
#At Controller
public function addOrders(Request $request) {
dd($request->all());
}

Problem with AJAX Post request in laravel

I have a select box and when each item is selected, a ajax request is sent.
but my code does not work. i'm get status 404 and this error is displayed in the console
exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException", file: "F:\\source\\boiler\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\RouteCollection.php", line: 179, …
my route :
Route::group(['namespace' => 'BuyCrypto' , 'prefix' => 'crypto'], function() {
Route::post('/calculateBuyAmount' , [BuyCryptoController::class , 'calculateAmount'])->name('calculate.amount');
});
ajax code :
$("select#user_select_crypto").change(function(e) {
$('#calculat_user_buy').block({
message: '<i class="icon-spinner4 spinner"></i>',
overlayCSS: {
backgroundColor: '#fff',
opacity: 0.8,
cursor: 'wait'
},
css: {
border: 0,
padding: 0,
backgroundColor: 'transparent'
}
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
$.ajax({
url: "panel/crypto/calculateBuyAmount",
dataType: 'json',
data: {
user_select_crypto: $("input[name=user_select_crypto]").val(),
user_value_request: $("input[name=user_value_request]").val(),
},
success: function(result) {
console.log(result)
},
error: function(result) {
console.log(result)
},
});
});
what is problem?
this is because laravel not getting the full URL of your giving route. you have to give the correct route. for this, you can use your named route like below.
url: "{{ route('calculate.amount') }}",
or in case you are in a javascript file and can't use blade than just give URL with / slash. all is going to work. Its happen with a post request.
you can give URL like below
url: "/panel/crypto/calculateBuyAmount",
Updated
Now you facing methodNotAllowedException because now you sending a get request because you are not mentioning in ajax side you are doing a post request. by default ajax will send a get request. so you need to tell ajax use post method. like that type: "POST" like below
$.ajax({
url: "/panel/crypto/calculateBuyAmount",
dataType: 'json',
type : 'POST'
data: {
user_select_crypto: $("input[name=user_select_crypto]").val(),
user_value_request: $("input[name=user_value_request]").val(),
},
success: function(result) {
console.log(result)
},
error: function(result) {
console.log(result)
},
});
In this kind of situation, it is good to use named route as you give your route a name.
$.ajax({
url: "{{ route('calculate.amount') }}", // use your name route here
type : 'POST', // need to add your request type post
dataType: 'json',
data: {
user_select_crypto: $("input[name=user_select_crypto]").val(),
user_value_request: $("input[name=user_value_request]").val(),
},
success: function(result) {
console.log(result)
},
error: function(result) {
console.log(result)
},
});

Ajax get response body data name with space

I am able to read specific data from responses with ajax GET example by using data.investing.
but one of my data name is unrest and war and i am unsure how do i write it inside my javascript, as i tried data.unrest and war and it didnt work.
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: "https://agile-bayou-24340.herokuapp.com/users/getTodayData",
contentType: 'application/json',
dataType: 'json',
responseType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'application/json',
},
success: function (data) {
console.log(data.investing[0].title);
$('#div1').html((data.investing[0].title));
},
error: function (error) {
console.log("Error");
}
});
});
});
this is my current code
You can parse Json to Array and use key's
success: function (data) {
data = $.parseJSON(data)
console.log(data['investing'][0]['title']);
$('#div1').html((data['investing'][0]['title']));
},

Can not pass value from Ajax to controller

My AJAX:
$.ajax({
url: '{{ URL::to('dashboard') }}',
type: 'GET',
data: { cid: val },
dataType:'JSON',
success: function(result) {
},
error: function(){
$('#status-msg').addClass('alert alert-danger');
$('#status-msg').text('Fejl!!');
}
});
My Route:
My Controller:
public function dashboard(){
if (Request::ajax()){
$cid = Input::get('cid');
var_dump(json_encode($cid));
} else {
echo "XX";
}
}
The cid is not passing to controller, the request AJAX is not working.
have you try change your ajax type to POST ?
$.ajax({
url: '{{ URL::to("yourURL") }}',
type:'POST',
data:"cid="+$(this).val()+"&_token=" + $("input[name=_token]").val(),
dataType:'JSON',
success:function(result){
},
error: function() {
}
});
Edit:
try to pass _token if you use {{Form::open}}.
hope this will help.
Try this:
$.ajax({
url: '<?php echo base_url() ?>index.php/contorller_name/method_name',
type: 'POST',
data: { cid: val },
dataType:'JSON',
success: function(result) {},
error: function() {
$('#status-msg').addClass('alert alert-danger');
$('#status-msg').text('Fejl!!');
}
});

KendoUI re-posts when delete is used

When new entry added into datagrid, and if page is not refreshed but some rows deleted,
tornado receives same added data as post, along with delete method
Why is that happening? I have differnt transport methods for each:
transport: {
read: {
url: '/api/notes/',
dataType: 'json',
type: 'GET',
},
create: {
url: '/api/notes/',
dataType: 'json',
type: 'POST'
},
update: {
url: '/api/notes/',
dataType: 'json',
type: 'PUT',
},
destroy: {
url: function(row) {
return '/api/notes/' + row.id;
},
type: 'DELETE',
},
ok, doing $("#grid").data("kendoGrid").dataSource.read(); on create.complete fixed it.

Resources