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);
}
});
Related
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'})
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'm trying to add an image to a post with Ajax / Laravel 5.4.
This is my HTML:
<form class="comments-form" action="/upload/comments/{{$post->id}}" method="post" data-id ="{{$post->id}}" enctype="multipart/form-data">
#csrf
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
Here is the Ajax code:
$('.add-comment').click(function(){
var comment_data = $('.comments-form').serialize();
var post_id = $('.comments-form').data('id');
var formData = new FormData('.comments-form');// i think here is problem
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,formData,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
This doesn't work – what am I doing wrong?
The FormData constructor takes a form not a string(you passes a css selector)
var formData = new FormData($('.comments-form').get(0));
If you use FormData in this way all fields in the form will be automatically added to the FormData object.
If there are items outside of the form fields that needs to be sent use the append method
formData.append('comment_data', $('.comments-form').data('id'));
When passing a FormData object to jQuery ajax you pass it alone and add processData and contentType set to false
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: formData,
contentType: false,
preocessData: false,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
If you want to store data using ajax.. you shouldn't need to put your action in your form component
<form class="comments-form" data-id ="{{$post->id}}">
{{ csrf_field() }}
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
</form>
I think if you want to submit your form, better to use jquery submit method
$('.add-comment').submit(function(){
var post_id = $('.comments-form').data('id');
var comment_data = new FormData($(".comments-form")[0]);
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,
dataType: 'json'
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
you can solve it as the following:
var formData = new FormData($("#FormId")[0]);
$.ajax({
url: '/upload/comments/' + post_id,
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: 'application/json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function (data, textStatus, jqXHR) {
console.log(data);
$('.all-comments').append(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error');
}
});
return false;
the formData variable contains all data of the form if you want to send the post id with the data sent you can put hidden field inside form called post id
like this
<input type="hidden" name="post_id" value="{{$post->id}}">
and then apply the above code
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);
}
});