AJAX data is not submitting to Laravel controller - Laravel 6 - php

I've set up two buttons which when clicked are just sending their values to my controller, then I am trying to send back AJAX HTML to show the users profile on the main page. I can't get the input id to make it to the controller no matter what I try.
Here's the HTML:
<ul class="signup-li">
#foreach($participants as $participant)
<button type="submit" name="id" value="{{$participant->id}}">
{{$participant->phone}}
</button>
#endforeach
</ul>
Here is my JS:
$(document).ready(function(){
$("button").click(function() {
var id = $(this).val();
console.log(id);
$.ajax({
type:'POST',
url:'/get-profile/',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: { "id" : id },
success: function(data){
console.log('hi');
},
error: function(xhr,textStatus,thrownError) {
alert(xhr + "\n" + textStatus + "\n" + thrownError);
}
});
});
});
Here is my controller function:
public function getProfile(Request $request)
{
$id = $request->input('id');
Log::info($id);
$participant = Participant::where('id','=',$id)->first();
$returnHTML = view('ajax.user-profile')->with('participant', $participant)->renderSections()['content'];
return response()->json(array('success' => true, 'html'=>$returnHTML));
}
What am I doing wrong? I try to log the request and nothing comes through. I have CSRF disabled for this route. The issue is that the participant is not found because the ID is not getting to the controller. Why isnt it making it?

You may add dataType: 'json', to your $.ajax({...}) call

Related

Laravel dosent delete record via ajax?

I'm trying to delete record using ajax, in laravel 5.4, I know this is one of the common questions and there are already lots of online solutions and tutorials available about this topic. I tried some of them but most of giving me the same error NetworkError: 405 Method Not Allowed. I tried to do this task by different angle but I'm stuck and could not found where I'm wrong, that's why I added this question for guideline.
I'm trying the following script for deleting the record.
IN Route:
Route::delete('article/delete/{article}', 'ArticleController#delete_article')->name("delete_article");
In Controller:
public function delete_article($id)
{
article::where('id', $id)->delete($id);
return response()->json([
'success' => 'Record deleted successfully!'
]);
}
IN View:
<li name="csrf-token" content="{{ csrf_token() }}">
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}">
<i class="icon-bin"></i>delete
</a>
</li>
Ajax Code is:
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: /admin/article/delete/{{article}},
type: 'DELETE',
data: {
"id": id,
"_token": token,
},
success: function (){
console.log("it Works");
}
});
});
As you can See it seems everything is right but I don't know why it doesn't work correctly?
please help me, guys.
This is work for me:
In Route
Route::post('/article/delete', 'ArticleController#delete_article');//Ajax Routes
IN Controller
public function delete_article(Request $request)
{
$id=$request['id'];
article::where('id', $id)->delete();
return response()->json(['articleDelete' => 'success']);
}
in View:
<td>
<a class="deleteRecord" data_id="{{$article->id}}">
<i class="icon-bin" style="color: black"></i></a>
</td>
In AJAX:
$(".deleteRecord").each(function () {
$(this).on("click", function () {
var $tr = $(this).closest('tr');
var id = $(this).attr("data_id");
swal({
title: "Are you sure to Delete!",
text: "***",
icon: "warning",
buttons: [
'cansle!',
'yes'
],
dangerMode: true,
}).then(function(isConfirm) {
if (isConfirm) {
$.ajax({
url: '/admin/article/delete',
type: 'post',
dataType: 'json',
data: {_token: "{{csrf_token()}}" , id:id},
success: function () {
swal({
title: "article deleted succesfuly",
icon: "success",
type: 'success',
})
$tr.find('td').fadeOut(1000,function(){
$tr.remove();
});
}
})
}
})
});
});
The problem (as far as I can see) lies here:
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}">
In your view, you make a variable named id and the value is based on data-id attrribute.
var id = $(this).data("id");
But in your a tag you don't have data-id attribute. So you have to add it (something like this):
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}" data-id="{{$article->id}}">
Also in your ajax call, teh url is incorrect (based on what you have defined in routes:
Ajax call:
url: "article/"+id
Route:
article/delete/{article}
So either change the route:
article/{article}
or change the ajax call:
url: "article/delete/"+id
And one more thing. You have to prevent default a tag action. change the event like this:
$(".deleteRecord").click(function(event){
event.preventDeault();
You are doing wrong in many places. Try this
Route
Route::delete('article/delete/{article}', 'ArticleController#delete_article')->name("delete_article");
Controller
public function delete_article($article)
{
article::where('id', $article)->delete();
return response()->json([
'success' => 'Record deleted successfully!'
]);
}
View
<button class="deleteRecord" data-id="{{$article->id}}"><i class="icon-bin"></i>delete</button>
AJAX
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "article/delete/"+id,
type: 'POST',
dataType: 'json',
data: {
_method: 'DELETE',
submit: true,
_token: token,
},
success: function (){
console.log("it Works");
}
});
});

Ajax Delete Function in Laravel doesn't work

I tried to make an ajax delete functionality in Laravel.
I cant figure out why it isnt working... There is no error but nothing happens -
Thanks for any help!
My route:
Route::post('/deleteWithAjax', 'eventController#deleteWithAjax');
My delete Button:
<button value="{{$event->id}}" class="btn btn-danger btn-dell">Delete</button>
My javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('document').on('click', '.btn-dell', function() {
var id = $(this).val();
var el = $('#{{$event->id}}');
$.ajax({
type: 'post',
url: "deleteWithAjax",
data: {
'id': id
},
success:function(data){
el.remove();
}
})
})
});
My Controller Method:
public function deleteWithAjax(Request $r){
eventModel::find ( $r->id )->delete();
return response()->json();
}
The element i want to remove is a div:
<div id="{{$event->id}}">
EDIT**
I changed the event Handler
document.getElementById("btn-dell").onclick = function()
now it gets fired - but i get an error in the console and the backend is still not called at all:
POST http://wt-projekt.test/index.php/deleteWithAjax 419 (unknown status)
send # app.js:29
ajax # app.js:29
document.getElementById.onclick # home:50
I solved the problems:
I placed the token part in the document ready function
--> No error anymore, record deleted in the DB but still in the view
I added dataType: 'text' to the ajax call
--> error also deleted in the View
Nevertheless thanks for your comments!

MethodNotAllowed on deleting an item with AJAX and Laravel

SOLUTION IN LAST COMMENT OF ANSWER
I have this function here
function delTag(e, name){
var tag_id = $(e).attr('rel');
$.ajax({
type: "DELETE",
url: '/admin/tags/'+ tag_id+'' ,
success: function(data){
$('#tags_tr'+tag_id).remove();
toastr.error('Tag '+name+' has been deleted');
console.log("dsa");
},
error: function(data){
console.log('Error:');
}
});
}
I call it like this:
#foreach($tags as $tag)
<button onclick='delTag(this, "{{$tag->name}}")' rel={{$tag->id}} type="button" data-dismiss="modal" class="btn btn-danger">Yes</button>
#endforeach
And i get this:
My record is deleted from the database correctly, but, ajax throws error. Why is this happaneing?
Here is my whole route if it helps...
Route::get('admin/', 'AdminController#getAdminIndex')->name('admin.index');
Route::delete('admin/users/{id}', 'Auth\\RegisterController#destroy')->name('admin.users.destroy');
Route::put('admin/users/{id}', 'Auth\\RegisterController#update')->name('admin.users.update');
Route::resource('/admin/posts', 'PostController');
Route::resource('/admin/roles', 'RoleController');
Route::delete('/admin/comments/{id}/{user_id}', 'CommentsController#destroy')->name('comments.destroy');
Route::resource('/admin/comments', 'CommentsController', [
'except' => ['store', 'destroy']
]);
Route::get('/administrator', 'AdminController#getAdmin')->name('admin');
Route::put('/admin/comments/approve/{id}', 'CommentsController#updateApprove')->name('admin.comments.approve');
Route::put('/admin/tags/associate/{tagName}', 'TagController#updateAssociation')->name('admin.tags.associate');
Route::put('/admin/categories/associate/{categoryName}', 'CategoryController#updateAssociation')->name('admin.categories.associate');
Route::resource('/admin/categories', 'CategoryController');
Route::resource('/admin/tags', 'TagController');
Route::get('/admin/pages/tables/{user_id}', 'AdminController#getTables')->name('admin.pages.tables');
Route::get('/admin/pages', 'AdminController#getIndex')->name('admin.pages.index');
With the ajax call you need also to provide csrf_token.
You can keep it on the page in the hidden input field, like this for example:
<input id="csrf" type="hidden" name="_token" value="{{ csrf_token() }}">
And then add it to your ajax call with key "_token". So your delTag function will become something like this:
function delTag(e, name){
var tag_id = $(e).attr('rel');
var csrfToken = $("#csrf").val(); // here you're obtaining token from the page
$.ajax({
type: "DELETE",
url: '/admin/tags/'+ tag_id+'' ,
data: {
"_token": csrfToken //Here you're passing the token
},
success: function(data){
$('#tags_tr'+tag_id).remove();
toastr.error('Tag '+name+' has been deleted');
console.log("dsa");
},
error: function(data){
console.log('Error:');
}
});
}

How to send multiple parameter AJAX in Laravel 5.2

How do I send multiple values for AJAX Laravel.
for Example:
$('#submit_').on('click', function (e) {
e.preventDefault();
var form_data = $('#create').serialize();
var form_taxonomy = 'category';
$.ajax({
headers: {
'X-CSRF-Token': $('input[name="_token"]').val()
},
type: 'post',
url: '{!! URL::route('category') !!}',
data: {formData:form_data,formTaxonomy: form_taxonomy},
success: function () {
$('#append').load('{!! URL::route('loadCat') !!}');
},
error: function (xhr, status, errorThrown) {
alert(JSON.parse(xhr.responseText).category[0]);
}
});
jQuery("#create").val('');
});
controller code:
public function create(messageRequest $request)
{
if($request->ajax()) {
$name = Input::get('formData');
$taxonomy = Input::get('formTaxonomy');
return response()->json($name, $taxonomy);
}
}
html code:
<div class="col-sm-6">
<form method="POST" action="http://localhost:8000/category" accept-charset="UTF-8"><input name="_token"
value="IzByO9fU5yeanaVCudCQpkL5bXGzUh9B4jb400iU"
type="hidden">
<div class="form-group">
<div class="form-group">
<input class="form-control text-right" id="create" name="category" type="text">
</div>
<div id="submit_"><input name="createSub" id="submit" class="btn btn-primary" value="submit" type="submit">
</div>
</div>
</form>
message request validate:
public function rules()
{
return array(
'category'=>'required|alpha|unique:taxonomies,name',
);
}
public function messages(){
return [
'category.required'=>'fill',
'category.alpha'=>'only charecter',
'category.unique'=>'dublicate'
];
}
This code not work . I used my other examples, but no one was not responsive to the problem is that I don't know only parameter data in laravel how to call the amount that would not be faced with an error and stored in the database .
You've already serialized the form, which generates the name=value&name=value query string format. It looks like you then want to add data to this query string for submission. You will need to do this somewhat manually, but it can be done like this:
$('#submit_').on('click', function (e) {
e.preventDefault();
var form_data = $('#create').serialize();
var form_taxonomy = 'category';
$.ajax({
headers: {
'X-CSRF-Token': $('input[name="_token"]').val()
},
type: 'post',
url: '{!! URL::route('category') !!}',
// manually combine your form data and your additional post data
// into one query string
data: form_data + '&' + $.param({formTaxonomy: form_taxonomy}),
success: function () {
$('#append').load('{!! URL::route('loadCat') !!}');
},
error: function (xhr, status, errorThrown) {
alert(JSON.parse(xhr.responseText).category[0]);
}
});
jQuery("#create").val('');
});
Edit
With your existing code, the issue that you're having is that your messageRequest validation says that the category field is required, but your request data does not have a category field. Because of this, your validation is failing, and will return a 422 response with a JSON object containing your validation errors.
With the updated code above, your request data now has a category field, so validation is passing, but you have some other error in your code that is generating a 500 error. You need to track this down and fix it, which may require another question.
You are using FormRequests to act as validation for that controller method. In this case, your FormRequest is: MessageRequest - which includes a validation parameter by the name of category.
When your ajax submission takes place, it is not providing the category field, and therefore failing validation.
To test, try supplying category data to the ajax data:
data: {formData:form_data,formTaxonomy: form_taxonomy, category: 'somevalue-unique-to-your-taxonomies'},
Change your data part like this :
data: {'formData':form_data,'formTaxonomy': form_taxonomy},

Laravel csrf token mismatch for ajax POST Request

I am trying to delete data from database via ajax.
HTML:
#foreach($a as $lis)
//some code
Delete
//click action perform on this link
#endforeach
My ajax code:
$('body').on('click', '.delteadd', function (e) {
e.preventDefault();
//alert('am i here');
if (confirm('Are you sure you want to Delete Ad ?')) {
var id = $(this).attr('id');
$.ajax({
method: "POST",
url: "{{url()}}/delteadd",
}).done(function( msg ) {
if(msg.error == 0){
//$('.sucess-status-update').html(msg.message);
alert(msg.message);
}else{
alert(msg.message);
//$('.error-favourite-message').html(msg.message);
}
});
} else {
return false;
}
});
This is my query to fetch data from database...
$a = Test::with('hitsCount')->where('userid', $id)->get()->toArray();
But when i click on Delete link data not deleted and show csrf_token mismatch...
The best way to solve this problem "X-CSRF-TOKEN" is to add the following code to your main layout, and continue making your ajax calls normally:
In header
<meta name="csrf-token" content="{{ csrf_token() }}" />
In script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
You have to add data in your ajax request. I hope so it will be work.
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
I just added headers: in ajax call:
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
in view:
<div id = 'msg'>
This message will be replaced using Ajax. Click the button to replace the message.
</div>
{!! Form::submit('Change', array('id' => 'ajax')) !!}
ajax function:
<script>
$(document).ready(function() {
$(document).on('click', '#ajax', function () {
$.ajax({
type:'POST',
url:'/ajax',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success:function(data){
$("#msg").html(data.msg);
}
});
});
});
</script>
in controller:
public function call(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
in routes.php
Route::post('ajax', 'AjaxController#call');
Laravel 8^
Route::post('ajax', [AjaxController::class, 'call']);
I think is better put the token in the form, and get this token by id
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
And the JQUery :
var data = {
"_token": $('#token').val()
};
this way, your JS don't need to be in your blade files.
If you are using template files, than you can put your meta tag in the head section (or whatever you name it) which contain your meta tags.
#section('head')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#endsection
Next thing, you need to put the headers attribute to your ajax(in my example, I am using datatable with server-side processing:
"headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
Here is the full datatable ajax example:
$('#datatable_users').DataTable({
"responsive": true,
"serverSide": true,
"processing": true,
"paging": true,
"searching": { "regex": true },
"lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
"pageLength": 10,
"ajax": {
"type": "POST",
"headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
"url": "/getUsers",
"dataType": "json",
"contentType": 'application/json; charset=utf-8',
"data": function (data) {
console.log(data);
},
"complete": function(response) {
console.log(response);
}
}
});
After doing this, you should get 200 status for your ajax request.
Know that there is an X-XSRF-TOKEN cookie that is set for convenience. Framework like Angular and others set it by default. Check this in the doc https://laravel.com/docs/5.7/csrf#csrf-x-xsrf-token
You may like to use it.
The best way is to use the meta, case the cookies are deactivated.
var xsrfToken = decodeURIComponent(readCookie('XSRF-TOKEN'));
if (xsrfToken) {
$.ajaxSetup({
headers: {
'X-XSRF-TOKEN': xsrfToken
}
});
} else console.error('....');
Here the recommended meta way (you can put the field any way, but meta is quiet nice):
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Note the use of decodeURIComponent(), it's decode from uri format which is used to store the cookie. [otherwise you will get an invalid payload exception in laravel].
Here the section about the csrf cookie in the doc to check :
https://laravel.com/docs/5.7/csrf#csrf-x-csrf-token
Also here how laravel (bootstrap.js) is setting it for axios by default:
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
you can go check resources/js/bootstrap.js.
And here read cookie function:
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
Add an id to the meta element that holds the token
<meta name="csrf-token" id="csrf-token" content="{{ csrf_token() }}">
And then you can get it in your Javascript
$.ajax({
url : "your_url",
method:"post",
data : {
"_token": $('#csrf-token')[0].content //pass the CSRF_TOKEN()
},
...
});
EDIT: Easier way without changing the meta line.
data : {
_token: "{{ csrf_token() }}"
}
Or
data : {
_token: #json(csrf_token()),
}
Thanks to #martin-hartmann
you have to include this line in master file
<meta name="csrf-token" content="{{ csrf_token() }}" />
and while calling ajax you have to implement csrf token ,
$.ajax({
url:url,
data:{
_token:"{{ csrf_token() }}"
},
success:function(result){
//success message after the controller is done..
}
})
if you are using jQuery to send AJAX Posts, add this code to all views:
$( document ).on( 'ajaxSend', addLaravelCSRF );
function addLaravelCSRF( event, jqxhr, settings ) {
jqxhr.setRequestHeader( 'X-XSRF-TOKEN', getCookie( 'XSRF-TOKEN' ) );
}
function getCookie(name) {
function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
return match ? match[1] : null;
}
Laravel adds a XSRF cookie to all requests, and we automatically append it to all AJAX requests just before submit.
You may replace getCookie function if there is another function or jQuery plugin to do the same thing.
who ever is getting problem with the accepted answer #Deepak saini, try to remove
cache:false,
processData:false,
contentType:false,
for ajax call.
use
dataType:"json",
In case your session expires, you can use this, to login again
$(document).ajaxComplete(function(e, xhr, opt){
if(xhr.status===419){
if(xhr.responseJSON && xhr.responseJSON.message=='CSRF token mismatch.') window.location.reload();
}
});
You should include a hidden CSRF (cross site request forgery) token field in the form so that the CSRF protection middleware can validate the request.
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.
So when doing ajax requests, you'll need to pass the csrf token via data parameter.
Here's the sample code.
var request = $.ajax({
url : "http://localhost/some/action",
method:"post",
data : {"_token":"{{ csrf_token() }}"} //pass the CSRF_TOKEN()
});
xxxxxxxOld answer deletedxxxxxxx
CLARIFICATION/UPDATE
The csrf token in the meta header is used for session management
Laravel automatically generates a CSRF "token" for each active user session managed by the application.
It is the same value as that contained in:
#csrf directive inside a form or anywhere else in a Blade template (this generates the _token hidden input field).
csrf_token() global helper function used anywhere in a controller or Blade template.
Important
For sessions that are not yet authenticated, the CSRF token is regenerated/different for every served page - i.e. new session data is generated for every loaded page.
For a session that is authenticated, the CSRF token is the same for all pages - i.e. session data is maintained across all loaded pages.
Conclusion
Include the CSRF token in Ajax request in the following way:
from the meta header or the generated hidden _token input field - useful when sending Ajax POST request with a form:
<script>
$(document).ready(function() {
let token = $('meta[name="csrf_token"]').attr('content');
// let token = $('form').find('input[name="_token"]').val(); // this will also work
let myData = $('form').find('input[name="my_data"]').val();
$('form').submit(function() {
$.ajax({
type:'POST',
url:'/ajax',
data: {_token: token, my_data: myData}
// other ajax settings
});
return false;
});
});
</script>
Call csrf_token() in a hidden element in Blade template and get the token in js - useful when sending Ajax POST request without a form:
Blade:
<span id='csrf' style='display:none'>{{ csrf_token() }}<span>
JavaScript:
<script>
$(document).ready(function() {
let token = $('#csrf').html();
$.ajax({
type:'POST',
url:'/ajax',
data: {_token: token, my_data: 'john'}
// other ajax settings
});
});
</script>
I just use #csrf inside the form and its working fine
I always encounter this error recently. Make sure to use a more specific selector when referring to a value. for example instead of $('#firstname') use $('form').find('#firstname');
Laravel 5.8
use the csrf in the ajax url(separate js file)
$.ajax({
url: "/addCart" + "?_token=" + productCSRF,
type: "POST",
..
})
guys in new laravel you just need to do this anywhere. in JS or blade file and you will have csrf token.
var csrf = document.querySelector('meta[name="csrf-token"]').content;
it is vanilla JS. For Ajax you need to do this.
var csrf = document.querySelector('meta[name="csrf-token"]').content;
$.ajax({
url: 'my-own-url',
type: "POST",
data: { 'value': value, '_token': csrf },
success: function (response) {
console.log(response);
}
});
If you are work on laravel 7.0 project and facing this error
Adding a token as part of the parameter to be sent to the controller would solve the problem just like the answers given above. This is as a result of Laravel protecting your site against cross-site attack. which requires you to generate a unique token on every form submission.
"_token": "{{ csrf_token() }}"
You can now have;
const postFormData = {
'name' : $('input[name=name]').val(),
"_token": "{{ csrf_token() }}"
};
$.ajax({
url: 'pooling'
, type: 'post'
, data: postFormData
, dataType: 'json'
, success: function(response) { consolel.log(response) }
});
Simply putting csrfmiddlewaretoken: '{{ csrf_token }}' inside data works well!!
$.ajax({
url : "url where you want to send data"
type : "POST", // http method
data : {
name:"...",
csrfmiddlewaretoken: '{{ csrf_token }}' , #this works for me
},
// handle a successful response
success : function(data){
alert('......');
},
error : function() {
..............
}
});
There also could be a case when you define your $middlewareGroups
You should use the following format:
protected $middlewareGroups = [
'web' => [],
'api' => [
'web',
'throttle:500,1'
],
'basic' => [
'auth:basic',
]
];
If you're upgrading laravel from 5 to 8, and face this error, add following to app/Http/Middleware/VerifyCsrfToken.php:
public static function serialized()
{
return true;
}
In script tag in your blade file, do like this to generate a valid form token and get it in jQuery
<script>
$(document).ready(function() {
$("#my-upload-button").click(function() {
var token = "{{ csrf_token() }}";//here getting token from blade
$.post('my-url', {
_token: token,
datra: ...
},
function(data) {
alert(data);
});
});
});
I this problem was resolved for me just by removing processData: false
$.ajax({
url: '{{ route('login') }}' ,
method: 'POST',
data: {
_token : {{ csrf_token() }},
data : other_data,
},
cache: false,
//processData: false, // remove this
...
success: function(res){
...
}
});
In your main page (someViewsName.blade.php), declare a global variable
<script>
var token = "{{ csrf_token() }}";
</script>
<script src="/path/to/your_file.js"></script>
Then, in your_file.js
$.ajax({
type: "post",
url: "http://your.url/end/point",
data: {
_token:token,
data:your_data,
},
dataType: "json",
success: function (response) {
// code some stuff
}
});
Lol, I had the same issue tried each and every solution but after that checked env again and there was one flag true which causes the issue,
SESSION_SECURE_COOKIE=true
remove this line it will fix the issue.
I actually had this error and could not find a solution. I actually ended up not doing an ajax request. I don't know if this issue was due to this being sub domain on my server or what. Here's my jquery.
$('#deleteMeal').click(function(event) {
var theId = $(event.currentTarget).attr("data-mealId");
$(function() {
$( "#filler" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Are you sure you want to delete this Meal? Doing so will also delete this meal from other users Saved Meals.": function() {
$('#deleteMealLink').click();
// jQuery.ajax({
// url : 'http://www.mealog.com/mealtrist/meals/delete/' + theId,
// type : 'POST',
// success : function( response ) {
// $("#container").replaceWith("<h1 style='color:red'>Your Meal Has Been Deleted</h1>");
// }
// });
// similar behavior as clicking on a link
window.location.href = 'http://www.mealog.com/mealtrist/meals/delete/' + theId;
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
});
So I actually set up an anchor to go to my API rather than doing a post request, which is what I figure most applications do.
<p><a href="http://<?php echo $domain; ?>/mealtrist/meals/delete/{{ $meal->id }}" id="deleteMealLink" data-mealId="{{$meal->id}}" ></a></p>

Categories