Laravel 5.8 ajaxupload POST 419 (unknown status) - php

I have a problem. I want to upload img using ajaxupload but i can`t do it, i always get exception POST 419 (unknown status). I do everything using to the documentation but I have no idea.
So, my route:
Route::post('/products/image','ProductController#image');
In main layouts I have:
<meta name="csrf-token" content="{{ csrf_token() }}">
My form.blade.php
<form action="{{route('')}}" method="post">
#csrf
<div class="box box-danger box-solid file-upload">
<div class="box-body">
<div id="single" class="btn btn-success"
data-url="products/image" data-name="single">
Chose
</div>
<div class="single"></div>
And my app.js:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if($('div').is('#single')){
var buttonSingle = $("#single"),
buttonMulti = $("#multi"),
file;
}
if(buttonSingle){
new AjaxUpload(buttonSingle, {
action: '/admin/' + buttonSingle.data('url') + "?upload=1",
data: {name: buttonSingle.data('name')},
name: buttonSingle.data('name'),
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext))){
alert('Exception');
return false;
}
buttonSingle.closest('.file-upload').find('.overlay').css({'display':'block'});
},
onComplete: function(file, response){
$res = JSON.parse(response);
if($res['error']){
alert($res['error']);
buttonSingle.closest('.file-upload').find('.overlay').css({'display': 'none'});
return false;
}
setTimeout(function(){
buttonSingle.closest('.file-upload').find('.overlay').css({'display':'none'});
response = JSON.parse(response);
$('.' + buttonSingle.data('name')).html('<img src="/images/' + response.file + '" style="max-height: 150px;">');
}, 1000);
}
});

You should have something like that in header section
<meta name="_token" content="{{ csrf_token() }}"><meta>
or
<meta name="csrf-token" content="{{ csrf_token() }}">
And this is a common script which should load in any DOM element
<script>
$(function () {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});
});
</script>
Note: Use correct name name="_token" or name="csrf-token"

I had exactly same issue with Dropzone upload
Please don't forget to add enctype="multipart/form-data" as form attribute
And try to send this token data like that
data: {
_token: $('meta[name="csrf-token"]').attr('content'),
name: buttonSingle.data('name')
},

Related

Laravel 419 Error - VerifyCsrfToken issue when using Ajax

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'})

Laravel ajax request with csrf

I'm using Laravel 7.2.0, trying to send an ajax request but I have a problem.
I'm trying to pass the csrf token from the meta but it give me 419 error.
It only works if I add #csrf on the form as below, but the controller dont get an ajax request.
The form:
<form id="formto" method="POST" action="{{ route('selectedtodolist') }}">
#csrf
<p>{{$Todo->name}}</p>
<br>
<input id="id_todolist" name="id_todolist" value="{{$Todo->id}}" type="hidden">
<input type="submit">
</form>
Head:
#push('head')
<!-- Scripts ajax -->
<script src=" {{ asset('js/components/Selectedtodolist.js') }} "></script>
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
#endpush
Jquery ajax:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(() => {
$("#formto").submit((e) => {
let that = e.currentTarget;
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
success: function() {
alert("work");
}
})
.done((data) => {
console.log(data);
})
And the controller: (give me 404 error cause of this 'if'):
public function __invoke(Request $request)
{
if ($request->ajax()) {
$this->validate($request, [
'id_todolist' => 'bail|required|email'
]);
return response()->json ();
}
abort(404);
}
route: Route::post('selectedtodolist', 'SelectedlistController')->name('selectedtodolist');
Thank you in advance

Validate if value in input field is an Instagram URL in blade.php

I am using blade.php in my development, and I have a concern in validating if the input is a valid instagram url. I have tried doing this:
<form class="search_form" id="apply" action=" method="post">
#csrf
<label>
<input type="url" pattern="https?://.+" required id="instagram" value="" placeholder="Instagram Post URL (Paste Here)">
</label>
<div class="flex_box">
<button class="btn pink applyfnsh_btn" type="button" id="save">Confirm</button>
</div>
</form>
UPDATE this modal is displayed after validation
<div class="applyfnsh_modal">
<div class="applyfnsh_box">
<div class="modal_close">
<img src="../../assets/images/close.png" alt="close">
</div>
<p>Success</p>
</div>
</div>
modal.js
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
location is here
<script src="{{ url('/assets/js/modal.js') }}"></script>
And by the way, I'm using ajax in saving data to db so that page is not refreshed.
<script>
$(document).on("click", "#save", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url : $("#instagram").val(), user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
});
</script>
This isn't working and even processes the data when the button is clicked even if the input is not a url or empty.
Is there a way to do it without making a function?
here it is :
$(document).on("click", "#save", function() {
var instagramLink = $('#instagramLink').val();
var pattern = new RegExp('https://www.instagram.com/p/(.+?)', 'g');
if((instagramLink != undefined || instagramLink != '') && instagramLink.match(pattern)){
alert(instagramLink + 'is valid');
/*
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url :instagramLink, user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
*/
}else{
alert('Please Enter Valid Instagram Link');
$('#instagramLink').val('');
// show modal
$('.applyfnsh_modal').modal('open');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<form class="search_form" id="apply" action="" method="post">
<label>
<input type="url" required id="instagramLink" value="" placeholder="Instagram Post URL (Paste Here)" class="form-control"/>
</label>
<div class="flex_box">
<button class="btn btn-primary" type="button" id="save">Confirm</button>
</div>
</form>
</body>
</html>
update-2 : remove your existing scripts :
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
display modal using this way when it is required to display :
to OPEN MODAL : $('.applyfnsh_modal').addClass('open');
to CLOSE MODAL : $('.applyfnsh_modal').removeClass('open');
so
if (validation successfull){
// submit form using AJAX
}else{
$('.applyfnsh_modal').addClass('open');
}
also create one function to close modal :
$(document).on('click','.modal_close',function(){
$('.applyfnsh_modal').removeClass('open');
});

POST 419 (unknown status) laravel error

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() }}",

Laravel 5.4 $.post() jquery.min.js:4 POST 500 (Internal Server Error)

This is my first time using jquery post function in laravel. I am using laravel 5.4. i want to submit data via jquery.
Here's my blade template view:
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<form class="form-horizontal" method="POST" action="{{ route('doctor.register') }}">
{{ csrf_field() }}
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
On click ajax
</form>
</body>
Route:
Route::post('/ajax', 'TestController#ajax')->name('test.ajax');
JS file:
$(document).ready(function() {
$( "#ajaxclick" ).click(function() {
var token = $("#token").val();
var identity = 5;
$.post( "/ajax", { id: identity, token: token },
function( data ) {
console.log( "ajax working");
console.log( data.id );
}, "json");
});
});
Controller:
public function ajax(Request $request)
{
$id = $request['id'];
$id = $id + 1;
return response()->json(array('success'=>true, 'id'=>$id));
}
But when i click on tag it gives me 500 (Internal Server Error) in console log.
Now, how can i pass data via post function ? Any help ?
Solved::
I have edited my JS file like the following:
$(document).ready(function() {
$( "#ajaxclick" ).click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var token = $("#token").val();
var identity = 5;
$.post( "/ajax", { id: identity, token: token },
function( data ) {
console.log( "ajax working");
console.log( data.id );
}, "json");
});
});

Categories