Having 419 Ajax error in LARAVEL, how can i solve it? - ajax

I would really appreciate some help with this. I tried tons of solutions as posted in this forum, but I cannot get it to work
My ajax call is something like
$('#ref').blur(function(){
var ref = $('#ref').val();
var _token = $("input[name='_token']").val();
$.ajax({
url:"{{route('refcheck')}}",
method: "POST",
date: {ref:ref, _token,_token},
success:function (result) {
if (result==0){
$('.referror').html('<label class="text-danger"><i class="fa fa-exclamation-circle"></i> Invalid Sposor Id</label>');
$('.referror').slideDown();
$('#ref').addClass('has-error');
}
}
})
});
In Route
Route::post('/login/refcheck', 'CheckRegistraion#refCheck')->name('refcheck');
And controller
function refCheck(Request $request){
return 0;
}
My login.blade.php is
<form class="form-contact-warp form-calc-ship cb-form" method="POST" action="{{ route('register') }}">
#csrf
<input id="ref" class="form-control{{ $errors->has('ref') ? ' is-invalid' : '' }}" placeholder="Sponsor" type="text" name="ref" value="#if (request()->has('ref'))
{{request()->ref}}
#elseif(request()->has('ref')=='')
admin
#endif" required autocomplete="name" autofocus>
<div class="errordiv referror"></div>
I am getting this error
POST http://localhost/metazone/public/login/refcheck 419 (unknown status)

date: {ref:ref, _token:_token},

you have several typos. Try below
data: {ref:ref, _token:_token},
If it still give 419, do console.log(_token) to make sure your csrf token is valid

Related

Post form using AJAX in Django

I'm trying to POST form in Django using Ajax. I've already done this way before but now i cant find whats wrong with my code. When submitting the form, ajax POST's to wrong URL even though i've provided the right URL. I want to post to "/upload/videoUpload/" but it keeps on posting to "/upload".Below is the code.
HTML:
<form id="videouploadForm" method="POST" >
{% csrf_token %}
<input type="text" id="vidlc" name="video" value="submit" style="display: none" >
<input type="submit" id="sBm120" style="display: none"/>
</form>
AJAX:
<script>
$('#sBm120').trigger('click');
$(document).ready(function() {
$("#videouploadForm").submit(function(event){
event.preventDefault();
$.ajax({
method:"POST",
url:"/upload/videoUpload/",
data: {
'video': $('#vidlc').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
success: function(data){
if (data.status){
alert(data.status);
var result = " <video poster='{% static 'images/single-video.png' %}' style='height:30vh' controls='controls' width='100%' height='30%'><source src='http://gateway.ipfs.io/ipfs/"+data.filehash+"' type='video/mp4; codecs='avc1.42E01E, mp4a.40.2'></video>";
document.getElementById("upv").innerHTML=result;
}
}
});
return false; //<---- move it here
});
});
</script>
URLS.py:
path('upload/videoUpload/', uploadVid, name="uploadVideo"),
have you tried to use Django url template tags?
url:"/upload/videoUpload/", to
url:" '{% url " uploadVideo" %} ",
Hope it works!
Sorry if you dont see properly, writing from my phone :)

Laravel normal login with vuejs using axios returns error Request failed with status code 422

Am trying to use laravel and vue js with axios
Previously this was my login form
<form name="login-form" method="POST" action="{{ route('login') }}">
//username and password fields
</form>
Which works perfectly one can login
Now i would like to use vuejs in a similar way without making my app a single page app
so i have resulted to making a login component
<template>
<form name="login-form">
<input type="email" v-model="email" class="form-control" autofocus>
<input id="password" type="password" v-model="password" required>
<button type="submit"
class="btn btn-dark btn-sm"
#click.prevent="login"
:disabled="disableform">
{{submitted?"Logging you in .....":"Login"}}
</button>
</form>
</template>
Now script part
<script>
export default {
data: () => ({
email :'', password:'', remeberme:true, submitted:false
}),
methods: {
login() {
//do other stuff like disabling buttons...etc
axios.post("/login", {email:this.email, password:this.password})
.then(
(res)=>{
///showing sweet alert then
// settimout for 3 sec the
window.location.href="/dashboard";
},
(err)=>{
//show sweet alert of failed login
}
)
},
}
Now whenever i make the login post request an getting an error
Request failed with status code 422
I would like to proceed with the laravel vuejs workflow(with authentication sessions) but not an api jwt token request format.
What could be wrong or is this possible?
It's a validation error. check you laravel controller regarding post/put function.
Request failed with status code 422
When laravel fail the validation then it appears.
You need to use a csrf_field in your form, like this:
<input type="hidden" name="_token" :value="csrfToken">
And define it in your script:
data() {
return {
csrfToken: ''
}
},
created() {
this.csrfToken = document.querySelector('meta[name="csrf-token"]').content;
}

How to refer laravel csrf field inside a vue template

I have a vue template that contains a form:
<form id="logout-form" :action="href" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
In laravel, forms must have a csrf_field() defined. But within a vue component, the statement {{ csrf_field() }} means that I have a method named csrf_field in my vue instance and I am calling it.
How do I add csrf_field under this circumstance?
If you have the token in the meta tag of your header (view)
<meta name="csrf-token" content="{{ csrf_token() }}">
you could access the token using
data() {
return {
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
}
And add a hidden input field within the form and bind the csrf property to the value like this:
<form id="logout-form" :action="href" method="POST" style="display: none;">
<input type="hidden" name="_token" :value="csrf">
</form>
If you're using axios with Vue2 for your ajax requests you can just add the following (usually in your bootstrap.js file):
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};
You can use this package: npm install vue-laravel-csrf
Usage: <form v-csrf-token>
This is how i use it:
{!! csrf_field() !!}
Put that in your form.
and in your vue script you can simply
methods: {
submitForm: function(e) {
var form = e.target || e.srcElement;
var action = form.action;
get the form and his action then the data value will be:
data: $(form).serialize()
This works perfectly for me and gives no errors at all.

AJAX POST to RESTful service

I have a login form and I am looking to post the input values to a RESTful web service and then the credentials are correct I show elements and hide the form but if they are incorrect an error message appears.
I want to do this via AJAX but I am hitting a stumbling block as all i am returning is an alert box with undefined inside. Any help would be greatly appreciated.
<div class="cp_LoginPanel fade-in form">
<div class="in">
<h1>Login</h1>
<form name="login-form" id="login-form" method="post">
<label id="error">Sorry it seems your credentials are incorrect</label>
<div class="inputBlock">
<label for="username">Username</label>
<input type="text" id="username" />
</div>
<div class="inputBlock">
<label for="password">Password</label>
<input type="password" id="password" />
</div>
<input type="submit" value="Login" id="submit" />
</form>
</div>
</div>
$(document).ready(function () {
var username = $("#username").val();
var password = $("#password").val();
$("#submit").click(function () {
$.ajax({
type: 'POST',
url: "Service Here",
dataType: JSON,
data: {
"username": username,
"password": password
},
success: function (data) {
alert("success");
},
error: function (e) {
alert(e.Message)
}
});
});
});
Not that this is the answer to your problem. But im guessing you get and error and therefore try using the correct error parameters to get more information about your error.
The error function is called if the request fails. This functions receives 3 parameters.
The jqXHR object
A string describing the type of error that occurred
An optional exception object, if one occurred
Try using the code below to print out your error the correct way. Look at the example below:
error: function(jqXHR, textStatus, errorThrown) {
console.log('What is my error ' + textStatus);
console.log('Is an exception thrown ?? ' + errorThrown)
}
Hope that you get more information about your error :)
PS.
You could also look at the answer in this question. It the excact same problem as yours :)
jQuery Ajax - how to get response data in error

Ajax .load() with php value from db

Basically i have a value from a database ($learner->idnumber)
I then have a form which posts using submithandler to process.php (this edits database)
Now this is the bit im stuck on, im trying to get the php db value $learner->idnumber to update without page refresh once the form has been processed.
I have found:
$("#pinnumber").load("profile.php #pinnumber");
but im not quite sure on how to implement this.
This is my code:
<a id="pinlink">edit</a>
<div id="results"><div>
<div id="pinnumber">
'.$learner->idnumber.'
<div>
<div id="pincontent" style="display:none;">
<form name="myform" id="myform" method="POST">
<input type="text" name="idnumber" id="idnumber" size="20" value=""/>
<input type="submit" name="submit" value="Update">
</form>
<div>
$(document).ready(function(){
$("#pinlink").click(function () {
$("#pincontent").show();
});
$("#myform").validate({
debug: false,
rules: {
idnumber: "required",
},
messages: {
idnumber: "Please enter your PIN",
},
submitHandler: function(form) {
$("#pincontent").hide();
// do other stuff for a valid form
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
Any help would be greatly appreciated.
I included:
print "".$_POST['idnumber']."";
in process.php before the save to db code.
this then printed into:
<div id="results"><div>
when form was submitted.

Resources