Laravel ajax form validation - php

I want to send a short form with email by ajax.
Code below adds a hidden input with name='_token'
{!! Form::open(['route'=>'registerCheck', 'id'=>'register_form', 'novalidate'=>'novalidate']) !!}
In js script I add data to request:
$.ajax({
method:'POST',
url: $form.attr('action'),
data:{
'_token': $form.find('[name="_token"]').val(),
email: $('#email').val(),
user: $this.attr('id'),
}
})
How can I authenticate it and which namespaces should I include to do this?

First add this meta
<meta name="csrf-token" content="{{ csrf_token() }}" />
then in your script add this
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
finally change your request to this
$.ajax({
method:'POST',
url: $form.attr('action'),
data:{
_token: CSRF_TOKEN,
email: $('#email').val(),
user: $this.attr('id'),
}
})

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

Ajax returns GET request instead of POST

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>

CSRF token mismatch Laravel ajax delete data

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

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

$.ajax( type: "POST" POST method to php

I'm trying to use the POST method in jQuery to make a data request. So this is the code in the html page:
<form>
Title : <input type="text" size="40" name="title"/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=f.title.value;
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
And this is the php code on the server :
<?php
$title = $_POST['title'];
if($title != "")
{
echo $title;
}
?>
The POST request is not made at all and I have no idea why. The files are in the same folder in the wamp www folder so at least the url isn't wrong.
You need to use data: {title: title} to POST it correctly.
In the PHP code you need to echo the value instead of returning it.
Check whether title has any value or not. If not, then retrive the value using Id.
<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=jQuery('#title').val();
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
Try this code.
In php code, use echo instead of return. Only then, javascript data will have its value.
try this
$(document).on("submit", "#form-data", function(e){
e.preventDefault()
$.ajax({
url: "edit.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
$('.center').html(data);
}
})
})
in the form the button needs to be type="submit"
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
function signIn()
{
var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
$.ajax({
type: 'POST',
url: "auth_loginCode.jsp",
data: {Username: Username, Password: Password},
success: function (data) {
alert(data.trim());
window.location.reload();
}
});
}
contentType: 'application/x-www-form-urlencoded'

Categories