I'm reaching Laravel 419 error while using Ajax and I don't have any idea about what is causing this.
I saw on other posts it has to do something with csrf token, but I have no form so I don't know how to fix this.
My code:
function check_login_auth(id) {
var email_address = $("input[name=l_email_address]").val();
var password = $("input[name=l_password]").val();
var token = $("meta[name=csrf-token]").attr("content");
$.ajax({
type: "POST",
url: baseurl+"route",
data: {
email:email_address,
password:password,
_token:token
},
dataType: 'json',
beforeSend: function() {
$('#l_loading_gif').show()
$('#l_login_form').hide()
},
success: function (data) {
// console.log(data)
},
});
} else {
$('#s_error').append('<p style="color: red">something went wrong.</p>')
}
}
Thanks you in advance!
You are calling POST method so You need to pass csrf_token in headers.
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
Your ajax looks like below.
$.ajax({
type: "POST",
url: baseurl+"route",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data: {
email:email_address,
password:password,
_token:token
},
dataType: 'json',
beforeSend: function() {
$('#l_loading_gif').show()
$('#l_login_form').hide()
},
success: function (data) {
// console.log(data)
},
});
If you're calling it in js file then pass the csrf token in meta tag.
<meta name="csrf-token" content="{{ csrf_token() }}">
And headers like
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
First you have to get the csrf-token value in proper way
var CSRF_TOKEN = document.getElementById("csrf_token").value;
<input type="hidden" name="_token" id="csrf_token" value="{{ csrf_token() }}">
or
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
or
var CSRF_TOKEN = form.find("input[name='_token']").val();
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Then you have to pass this data in
data: {
email:email_address,
password:password,
_token: CSRF_TOKEN
},
When you are making post requests to laravel it expects a csrf token to protect your requests even if you do not use form. I suggest you to switch to axios since it is easily configurable.
with axios you can do something like this
axios.defaults.headers.common['X-CSRF-TOKEN'] = 'your token here';
axios.post('/url', {
firstName: 'something',
lastName: 'something'})
Related
I'm trying to create a personal messaging system in laravel, and apart of this system is being able to send messages in a form without refreshing the entire page.
I've been following some youtube tutorials, and this is the Ajax script I have so far.
<form id="form{{$dm->id}}">
{{ csrf_field() }}
<input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
<script>
$('form{{$dm->id}}').ready(function (){
$('form{{$dm->id}}').on('submit', function( event ) {
event.preventDefault();
$.ajax({
type: 'post',
url: '{{ route("sendMessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
});
});
</script>
</form>
Instead of sending a POST request to the controller, it sends a GET request and just redirects.
This is my first time messing with Ajax/Javascript in general, so I don't know exactly why this isn't working.
Controller script:
public function sendM(Request $request, $id)
{
$validatedData = $request->validate([
'message' => 'required|string|max:255|min:4',
]);
$dm = Dm::find($id);
$mess = new Message;
$mess->Authid = Auth::user()->id;
$mess->Userid = $dm->Userid;
$mess->Dmid = $dm->id;
$mess->message = $request->input('message');
$dm->messages()->save($mess);
$dm->touch();
}
Route entry:
Route::post('/sendmessage/id{id}', 'SettingsController#sendM')->name('sendMessage')->middleware('verified');
Any help is very much appreciated! (Note: Sorry if it is something really obvious)
In the $.ajax call, you need to set the method to post instead of the type.
$.ajax({
method: 'post',
url: '{{ route("sendMessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
As an aside, jquery is often considered to be on the way out. You may want to look into what some alternatives to jquery would look like, such as vue.js or react. Specific to the ajax aspect, Laravel has built in axios support.
Not sure if it solves your problem, but you must also add the csrf token to the headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
(if the token is in a meta tag of course)
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
<form id="form{{$dm->id}}">
{{ csrf_field() }}
<input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
<script>
$('form{{$dm->id}}').ready(function (){
$('form{{$dm->id}}').on('submit', function( event ) {
event.preventDefault();
$.ajax({
type: 'POST', //Check your JQ version.
method: 'POST', //Check your JQ version.
contentType:"multipart/form-data; charset=utf-8",
//url: '{{ route("sendMessage", $dm->id) }}',
url: '{{ route("sendmessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
});
});
</script>
</form>
I want to delete data from a database with an ajax call but it's showing an error.
CSRF token mismatch
In header:
<meta name="csrf-token" content="{{ csrf_token() }}">
In blade:
<button class="deletePhoto" data-id="{{ $photo->id }}" data-token="{{ csrf_token() }}">Delete</button>
AJAX call:
$('.deletePhoto').click(function () {
var id = $(this).data('id');
var el = this;
$.ajaxSetup({
headers:{
'X_CSRF_TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/photo/delete/'+id,
type: 'DELETE',
dataType: 'JSON',
data:{
'id': id,
},
success: function () {
$(el).closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})
})
Controller:
public function destroy($id)
{
$photo = Photo::find($id);
$photo->delete();
}
This is what I usually do : [AJAX CALL]
$.ajax({
url: '/photo/delete/'+id,
type: 'DELETE',
dataType: 'JSON',
data:{
'id': id,
'_token': '{{ csrf_token() }}',
},
success: function () {
el.closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})
I am trying to delete image from folder using ajax and in route using delete method .In controller trying to delete image using image name in laravel.
Route:
Route::delete('remove-social/{filename}', 'Webadmin\Socials#removesocial');
Controller:
public function removesocial($filename){
File::delete('public/assets/uploads/Social/' . $filename);
}
View :
<a href="javascript:removesocialimage()" style="color: white;text-decoration: none;" class="btn btn-red">
<i class="glyphicon glyphicon-trash "></i> Remove</a> </label>
<script>
function removesocialimage() {
if (j('#file_name').val() != '')
if (confirm('Are you sure want to remove social icon?')) {
j('#loading').css('display', 'block');
var form_data = new FormData();
form_data.append('_method', 'DELETE');
form_data.append('_token', '{{csrf_token()}}');
j.ajax({
url: "remove-social/" + j('#file_name').val(),
data: form_data,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');
j('#file_name').val('');
j('#loading').css('display', 'none');
},
error: function (xhr, status, error) {
alert(error);
alert(xhr.responseText);
}
});
}
}
</script>
Include this in your views head:
<meta name="csrf-token" content="{{ csrf_token() }}">
And do this ajax setup before making network calls:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
try to change route delete to post method
Route::post('remove-social/{filename}', 'Webadmin\Socials#removesocial');
if you want to used delete method then your ajax look like
add in head html tag
<meta name="csrf-token" content="{{ csrf_token() }}">
js code
j.ajax({
url: "remove-social/" + j('#file_name').val(),
data: form_data,
headers: {
X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'DELETE', //POST TO DELETE
contentType: false,
processData: false,
success: function (data) {
j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');
j('#file_name').val('');
j('#loading').css('display', 'none');
},
error: function (xhr, status, error) {
alert(error);
alert(xhr.responseText);
}
});
i want to submit my form using ajax following is my javascript
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
url: "http://localhost/shago/register/submit",
data: user_firstname,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
i have included meta tag in form like
<div id="individual" class="hid">
<form method="POST" id="individual_form" name="individual_form" action="{{ route('register.submit') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
and in controller i have just returned a message but i am getting
POST http://localhost/shago/register/submit 419 (unknown status)
above error can you please help me ,let me know for any other inputs i know it is mostly caused by csrf token
(i have declared submit route in web.php and also api.php file)
Try this
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
url: "http://localhost/shago/register/submit",
data: {// change data to this object
_token : $('meta[name="csrf-token"]').attr('content'),
user_firstname:user_firstname
}
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
You can add below code to your master file
<script>
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
1) Use the meta tag in head section
<meta name="csrf-token" content="{{ csrf_token() }}">
2) Set header in ajax , like
header:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
3) Send CSRF token with data
data:({_token : $('meta[name="csrf-token"]').attr('content'),
name:name,category:category}),
or CSRF token can be written as
"_token": "{{ csrf_token() }}",
I have form to POST data to Controller and update database
The form in my orders.blade.php
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<select name="selectdb" required>
<option value="" disabled selected>Select Delivery Boy</option>
#foreach($delvery_boys as $delvery_boy)
<option name="selectdb" data-oid="{{$order->id}}" value="{{$delvery_boy->id}}">{{$delvery_boy->name}}</option>
#endforeach
</select>
<button type="submit" class="assigndb-btn btn-floating waves-effect waves-light">
<i class="material-icons">send</i>
</button>
</form>
I am doing an ajax POST request of form data to controller in my orders.blade.php
$(document).one("click", ".assigndb-btn", function () {
$('form').submit(function(event) {
event.preventDefault();
var order_id = $(this).find(":selected").data('oid');
var delivery_boy_id = $(this).find(":selected").val();
var delivery_boy_name = $(this).find(":selected").text();
$.ajax({
url: '{{ url('/manager/assign_orders') }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
And in my OrdersController.php i have the logic to updated the posted data
public function assignDeliveryBoy(Request $request)
{
$assign_delivery_boy = Order::where('id', $request->order_id)->update(['delivery_boy_id' => $request->delivery_boy_id]);
$data = [
'success' => true,
'message' => 'Order has been asigned'
];
return response()->json($data);
}
My Route is
Route::group(['prefix' => 'manager', 'middleware' => ['auth','roles'], 'roles' => 'manager'], function() {
Route::post('/assign_orders', 'OrdersController#assignDeliveryBoy')->name('assignOrder');
});
When i submit the form it suppose to hit the assign_order route and update the database
But in my console i am getting the html code of the page from where i submit the form basically it is executing GET instead of POST
As i checked in browser network whent the response is
Request URL:http://localhost:8000/manager/orders //but i am posting to http://localhost:8000/manager/assign_orders
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
i really don't understand what is wrong
thank you
Try this code.
$.ajax({
url: "{{ url('/manager/assign_orders') }}",
type: 'POST',
data:{
"order_id":order_id,
"delivery_boy_id":delivery_boy_id,
'_token':'{{ csrf_token() }}'
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
Let me know if it works.
Try this:
$.ajax({
url: '{{ route('assignOrder') }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
$.ajax({
url: '{{ route("assignOrder") }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id,'_token':'{{ csrf_token() }}'},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});