AJAX Form won't update after being submitted - ajax

I have been toubleshooting an ajax request for a contact form. The form will load field errors with an ajax request, but it wont submit the form after the response. One thing to note is that I am trying to submit the form with a button outside the form tag, but even with one inside the tag it only submits once.
My ajax script:
$('#modal-form').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(data) {
if (!(data['success'])) {
// Here we replace the form, for the
form.replaceWith(data['form_html']);
$('#modal-form').off("submit");
}
else {
// Here you can show the user a success message or do whatever you need
$('#myModal').modal("hide");
}
},
error: function () {
$('#error-div').html("<strong>Error</strong>");
}
});
});
My form:
{% load crispy_forms_tags %}
<div class="container">
<!-- Modal -->
<div class="modal fade container-fluid" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><span class="glyphicon glyphicon-envelope"></span> Email Me</h4>
<div id="success-div"></div>
</div>
<div class="modal-body">
<div class="row-fluid">
<div id="form">
<form id="modal-form" class="form-horizontal" method="POST" action="{% url 'emailme_success' %}">
{% csrf_token %}
{% crispy emailme_form emailme_form.helper %}
</form>
</div>
</div>
</div>
<div class="modal-footer">
<div id="error-div" class="pull-left"> </div>
<button name="submit" type="submit" class="btn btn-success pull-right" id="modal-submit" form="modal-form"><span class="glyphicon glyphicon-send"></span> Send</button>
</div>
</div>
</div>
</div>
</div>

Related

Page expired when submitting form

I am using a modal, and when opens the modal then close it, then open it again to add user, it says page expired upon submitting.
here is the my modal with my form
<div class="modal fade" wire:ignore.self id="studentModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Patient Registration</h5>
#if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{
Session::get('message') }}</p>
#endif
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="closeReset1" onclick="resetInput()"></button>
</div>
<!-- START FORM -->
<form action="add" method="POST">
#csrf
<!-- START MODAL BODY -->
<div class="modal-body">
</div>
<div class="modal-footer"
</div>
</form>
</div>
</div>
here is my route
Route::post('/add', [App\Http\Livewire\UHispatients::class, 'savePatient'])->name('registerPatient');
if you are using the naming route and check your model fillable
<form action="{{route('registerPatient')}}" method="POST">
#csrf
<!-- START MODAL BODY -->
<div class="modal-body">
</div>
<div class="modal-footer"
</div>
<button type="submit">submit</button>
</form>
As I can see, you just forgot to put action for your form in your modal.
If you submit using the submit button, then your problem is using the route path "add" instead of using the route path or route name.So as your route has name you can use it like this :
<form action="{{route('registerPatient')}}" method="POST">
#csrf
<!-- START MODAL BODY -->
<div class="modal-body">
</div>
<div class="modal-footer"
</div>
<button type="submit">submit</button>
</form>
If you're submitting your form with Ajax, then the csrf tag should be sending with your Ajax request. So, your Ajax header should be like this :
<script type="text/javascript">
$('#YOUR_FORM_ID').on('submit',function(e){
e.preventDefault();
let name = $('#name').val();
$.ajax({
url: "{{route('registerPatient')}}",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
name:name,
},
success:function(response){
console.log(response);
},
error: function(response) {
console.log(response);
}
});
});
</script>

Frontend validation on Fortify Login in Laravel with AJAX

I'm using Fortify to manage users authentication and I have a modal form for the login. My problem is every time I submit the form I can't see any errors because the page refreshes and closes the modal with the login form.
I would like to know if this validation is possible in the frontend without refreshing the page so the modal won't close. I've tried with Ajax but I can't find the right way to manage this or even in which controller I'm supposed to handle the if statement for the response.
I'll be really thankful if anyone could help me.
Here's my modal:
<!-- LOGIN Modal -->
<form action="{{ route('login') }}" method="post">
#csrf
<div class="modal fade" id="login" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" >
<div class="modal-content">
<div class="modal-header">
<h5>Login</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3 row">
<div class="col-sm"><br>
<input type="text" class="form-control" name="email" value="Email">
</div>
</div>
<div class="mb-3 row">
<div class="col-sm">
<input type="password" class="form-control" id="inputPassword" name="password" value="Password">
</div>
</div>
<div class="d-grid gap-2">
<button type="submit" id="btn-login" class="btn btn-login">Continuar</button>
</div>
</div>
<div class="modal-footer">
<label><u>Recuperar password</u></label>
</div>
</div>
</div>
</div>
</form>
And here's the Ajax:
$(document).ready(function() {
$("#btn-login").click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("input[name='email']").val();
var password = $("input[name='password']").val();
$.ajax({
url: config.routes.zone,
type: 'POST',
data: { _token: _token, email: email, password:password },
success: function(data) {
if ($.isEmptyObject(data.error)) {
window.location.href = {{ route('login') }};
} else {
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function(key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
});

Bootstrap 4 destroy a modal when it is closed

I'm looking for a solution on my problem. I'm using bootstrap4 on laravel project. I have a modal that has a button which close it self and open a new modal. This is the code:
$("#newAddressBtn").on('click', function () {
$('#modalAddressees').modal('hide')
$('#modalAddressees').on('hidden.bs.modal', function () {
// Load up a new modal...
$('#modalNewAddress').modal('show');
})
});
Inside this new modal (modalNewAddress) I have a button that dismiss it. But when I dismiss it, I would to destroy it self because if I need to re-open it again, I would to start with empty data inside (such us the first show).
I wrote this code but nothing happens:
[....]
.on('core.form.valid', function () {
$.ajax({
url: "{{ route("addresses.store") }}",
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')},
dataType: "JSON",
data: $("#addressForm").serialize(),
type: "POST",
success: function (data) {
destroyModal("#modalNewAddress");
},
error: function (data) {
console.log('error ' + data);
}
});
});
[....]
function destroyModal(modal){
$(modal).modal('dispose');
}
This is the code of the modal:
<div class="modal fade" tabindex="-1" role="dialog" id="modalNewAddress">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">New Address</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" id="addressForm" action="{{ route("addresses.store") }}" class="needs-validation" novalidate="">
{{ csrf_field() }}
<div class="form-group row">
<label for="name" class="col-sm-3 col-form-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="name" id="name" value="" placeholder="Name" required="">
</div>
</div>
<span class="float-right">
<button type="submit" id="save" class="btn btn-primary">Save</button>
</span>
<input type="hidden" name="ajax">
</form>
</div>
<div class="modal-footer bg-whitesmoke br">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
How can I solve the problem? Could you please help me?
You're not supposed to destroy the modal but recycle it.
The usage pattern would be as follows:
the modal does not contain data, but data fields you can reach with jQuery, such as:
<div id="adress-nome"></div>
<!-- more fields ... -->
before you open the modal, you populate it with a function, such as:
function updateModal(data)
{
$("#address-nome").val(data.nome);
// more data ...
}
function openModal(data)
{
updateModal(data);
$("#address-modal").modal("show");
}
when you're done with the modal, just hide it
when you re-open it, it will contain the new data

Can't pass Vue variable to hidden input v-model in view(v-for)

I'm new to Vue JS and I'm building an application with Laravel Spark and trying to utilize Vue as much as possible.
I have a form to simply add an 'Asset Type' with a component. Once the Asset Type is successfully created, a list of properties is grabbed from the database and set to a 'data' attribute. In my view(I'm using an inline template), I have a 'v-for' that creates a form for each property that has two hidden inputs for the property id and the type id, and one "Add" button that assigns the property to the newly created type.
THE PROBLEM:
I can't seem to assign the value of the hidden inputs within the view while using v-models. When I submit one of the forms, the form request data always returns the initial data value from the new SparkForm object.
In other words, I need to assign the hidden input values within the v-for loop in the view.
Here's my component:
Vue.component('new-asset-type', {
props: [],
data() {
return {
// type_id: this.type_id,
properties: this.properties,
newAssetType: new SparkForm({
label: null,
enabled: false,
}),
assignPropForm: new SparkForm({
prop_id: "",
type_id: "",
}),
};
},
methods: {
createType: function () {
Spark.post('/asset-types', this.newAssetType)
.then(response => {
this.type_id = response.type_id;
axios.get('/getTypeNotProps/' + this.type_id).then((response) => {
this.properties = response.data;
console.log(this.properties);
});
})
.catch(response => {
console.log("fail");
});
},
assignProp: function () {
Spark.post('/asset-properties/add', this.assignPropForm)
.then(response => {
console.log(response);
})
.catch(response => {
console.log("fail");
});
}
}
});
And here's my view:
#extends('spark::layouts.app')
#section('content')
<new-asset-type inline-template>
<div class="container">
<!-- Application Dashboard -->
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Add a New Asset Type</div>
<div class="panel-body" id="addTypeForm">
<div class="form-horizontal">
<div class="form-group" :class="{'has-error': newAssetType.errors.has('label')}">
{{ Form::label('label', 'Label', ['class' => 'col-md-4 control-label']) }}
<div class="col-md-6" >
<input type="test" name="label" v-model="newAssetType.label">
<span class="help-block" v-show="newAssetType.errors.has('label')">
#{{ newAssetType.errors.get('label') }}
</span>
</div>
</div>
<div class="form-group">
{{ Form::label('enabled', 'Enabled?', ['class' => 'col-md-4 control-label']) }}
<div class="col-md-6">
<input type="checkbox" name="enabled" v-model="newAssetType.enabled" >
</div>
</div>
<!-- Submit -->
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button class="btn btn-primary" #click="createType" :disabled="newAssetType.busy">
Create Asset Type
</button>
</div>
</div>
<div id="assignProps" v-if="newAssetType.successful">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Add Property
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Property to Asset Type</h4>
</div>
<div class="modal-body">
<assign-asset-prop v-for="property in properties" class="panel panel-info property-item">
<div class="panel-heading">#{{ property.label }}</div>
<div class="panel-body"><strong>Input Type: </strong>#{{ property.input_type }}
<div class="pull-right">
<input type="hidden" name="prop_id" v-bind:value="property.p_id" v-model="assignPropForm.prop_id">
<input type="hidden" name="type_id" v-bind:value="property.p_id" v-model="assignPropForm.type_id">
<button class="btn btn-primary" #click="assignProp" :disabled="assignPropForm.busy">
Add
</button>
</div>
</div>
</assign-asset-prop>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</new-asset-type>
#endsection
Thanks to the helpful comments, I learned that I shouldn't have been using hidden inputs at all. Instead, I simply passed the variables to the function on the click event.
<button class="btn btn-primary" #click="assignProp(type_id, property.p_id)" >
Add
</button>
Then in my component
methods: {
assignProp: function (type_id, property_id) {
var assignPropForm = new SparkForm({
propvalue: property_id,
typevalue: type_id,
});
Spark.post('/asset-properties/add', assignPropForm)
.then(response => {
console.log(response);
})
.catch(response => {
console.log("fail");
});
}
}
You need store variables at local data() dep., and geting it by getters function.

bootstrap 3 modal breaking on AJAX response - mvc4

My bootstrap modal footer just doesn't show up.
Main View
<div class="modal fade" id="ModalId">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" data-dismiss="modal">Log</button>
</div>
<div class="modal-body">
<div id="form">
<div id="ModalBodyId">
#Html.Partial("PartialViewName");
</div>
</div>
</div>
<div class="modal-footer"> // this part doesn't show up
<button type="button" data-dismiss="modal" onclick="SaveNow()";>Edit</button>
</div>
</div>
</div>
</div>
Here is what loads the partial view into the modal. I had to add the below code for the validation to work. The validation works fine now, however i do not see the button which is contained inside the modal footer.
$("#ModalId").click(function () {
var form = $("#ModalBodyId").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
$.ajax({
url: "/ControllerName/ActionName",
type: "GET",
data: $("#ModalBodyId").serialize(),
cache: false
});
});
If i remove the #Html.Partial("PartialViewName"); from modal-body then the modal-footer shows up.

Resources