Vue Laravel submit form using button in other component - laravel

I have two components:
Header.vue:
<button type="submit" #click="clickNext">Next</button>
methods:{
clickNext(){
Bus.$emit('submitForm');
}
}
And Home.vue
<form method="POST" ref="my-form">
<input type="text" name="email" id="email" />
</form>
created() {
Bus.$on('submitForm', () => this.$refs['my-form'].submit(this.send()))
},
methods: {
send() {
console.log("send!");
}
}
I need send form (with component Home.vue) using button which is in Header.vue component.
When I click Next button Laravel REFRESH PAGE and return error:
Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
No message

You have to have CSRF token in every form that does any method except GET.
Read on it in official docs

Related

How to submit form in Vue 3 only when function is called

Does anyone know how I can submit a sign out form in Vue 3 only when a function is called?
I have inserted related code below:
<form
#submit.prevent="handleSignOut($event)"
method="post"
action="/logout">
<input type="hidden" name="_token" :value="csrf">
<button type="submit">
Sign out
</button>
</form>
// handle sign out
const handleSignOut = function (e) {
// submit sign out here
}
if you're using javascript:
add a tag ref on your html form <form ref="myForm" #submit.prevent="handleSignOut($event)" method="post" action="/logout">
this.$refs.myForm.submit()
if you'e using typescript:
add a tag ref on your html form <form ref="myForm" #submit.prevent="handleSignOut($event)" method="post" action="/logout">
you need to declare const myForm = ref<HTMLFormElement>()
myForm.value.submit();

Sharing reCaptcha token between alpine and livewire

I am trying to build a reCapture component for a Laravel application using Livewire and Alpine and I can't figure out how to pass the recaptcha token value into the livewire component to complete the validation.
If I understand correctly this is because when I submit the form I am setting a hidden input value (recaptchaToken), however, livewire can not access hidden inputs so I need to use wire:model to bind to the data.
How can I pass the recaptchaToken.value in the submitForm() method, or how do I set the $recaptchaToken value with wire:model
<form x-data="{
execute(){
grecaptcha.ready(() => {
grecaptcha.execute('{{ env('RECAPTCHA_SITE_KEY') }}', { action: 'contact' })
.then((token) => {
{{-- how can i bind to wire:model instead of setting input.value ??? --}}
this.$refs.recaptchaToken.value = token;
})
})
}
}"
x-on:submit.prevent="execute" class="flex-col gg"
{{-- how can I access the recaptchaToken.value to pass into the submitForm() method ??? --}}
wire:submit.prevent="submitForm()">
<input wire:model="recaptchaToken" type="hidden" name="recaptchaToken" x-ref="recaptchaToken">
<button type="submit" class="w-fc btn primary">SUBMIT</button>
</form>

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 validate Laravel 4 form (html) with js framework

I am developed a laravel web application with forms. My client is not satisfied with laravel form validation because its validating from server side and reload the page, its taking more time. I want to validate form from client side.. which js framework is most suitable for laravel 4. I need the laravel form validation methords like min,max,numeric,alphanumeric,alpha. With custom validation error messages.
Also please give the best tutorial link for your suggestion. ?
Have you considered making an AJAX call to the backend, making use of Laravel's form validators, as the user tabs to the next input field? That way the form is validated prior to submit.
I manage the validation from you can use any framework and any CMS try it.
p{color:red;}
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#register-form").validate({
rules: {
roll: {required : true, minlength : 2,digits: true},
lastname: {required : true},
agree: "required"
},
messages: {
roll: {required :"<p>Please enter roll</p>", minlength : "<p>Must be at least 2 characters</p>",digits :"<p>Please enter integer Numper Only</p>" },
lastname: {required :"<p>Please enter lastname</p>" },
agree: "Please accept our policy"
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
<form method="post" action="<?php echo base_url(); ?>classname/functionname/" id="register-form" novalidate="novalidate" />
<input class="form-control" type="text" name="roll" value="">
<input class="form-control" type="text" name="lastname" value="">
</form>

Jquery validation spring mvc

I have a "Create an account" form that is handled by spring. I am using jquery to auto-update some of the fields.
<script type="text/javascript">
$().ready(
function() {
$("#item1").keyup(function() {
var text= (this).value;
//modify text
$("#item4").val(text);
});
});
</script>
<form:form action="${form_url}" method="POST" modelAttribute="object" enctype="${enctype}">
<label for="Item1">Item1:</label>
<input type="text" id="item1" name="item_1"/>
<br></br>
<br></br>
<label for="Item2">Item2:</label>
<input type="text" id="item2" name="item_2"/>
<br></br>
<br></br>
<label for="Item3">Item3:</label>
<input type="text" id="item3" name="item_3"/>
<br></br>
<br></br>
<label for="Item4">Item4:</label>
<input type="text" id="item4" name="item_4"/>
</form:create>
<input id="proceed" type="submit" value="Save"/>
Upon pressing the submit button I need to make sure the first field "item1" is not empty. I haven't found a solution to this uses spring forms. Thanks in advance!
There are many ways to implement such validation. It is recommended you do both client and server side.
For client side you can simple create a click listener to the submit button
$('.submitbutton').click(function(e) {
e.preventDefault();
if($('#item1').val().trim() != '') $('.myform').submit()
else { $('.item1_error').show();
}
Or (even better) use 3rd party validation library
For the server side you can use hibernate-validator and add #NotEmpty annotation to your form bean
public class MyForm {
#NotEmpty private String item1;
// ...
}
Then on your controller handler method just decorate the parameter with #Valid. Any errors can be checked through the BindingResult object
#RequestMapping(..)
public String myhandler(#Valid #ModelAttribute("object") MyForm myForm, BindingResult binding) {
if(binding.hasErrors()) {
// ...
}
}

Resources