Bootstrap modal stay open after form submit and page refresh - javascript

I hava a bootstrap modal form that i use to send a 4 field message. After the submit button is press i want to show the user a "thank you" message. But instead of that my form is closing and the page is refreshing.
How can i do for the modal form to stay open in order to display below the submit button the message.
Thank you!
<section class="modal-form">
<!-- Modal Video first page -->
<div class="modal fade" id="participa-modal" tabindex="-1" role="dialog" aria-labelledby="participa-modal">
<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">Participă la un demo!</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id="form" method="post" class="contact" action="" enctype="multipart/form-data" data-parsley-validate>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="homepage_firstname" id="homepage_firstname" class="form-control-contact" placeholder="Nume" required>
</div>
<div class="form-group">
<input type="email" name="homepage_email" id="homepage_email" class="form-control-contact" placeholder="Email" required>
</div>
<div class="form-group">
<input type="text" name="homepage_phone" id="homepage_phone" class="form-control-contact" placeholder="Telefon" data-parsley-type="number" minlength="10" maxlength="10" required>
<input type="hidden" name="inner_message" id="inner_message" value="Participare demo curs!">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control-contact" name="homepage_message" id="homepage_message" placeholder="Scrisoare de intentie"></textarea>
</div>
</div>
</div>
<div class="form-actions">
<input type="hidden" name="homepagesubmitted" value="TRUE" />
<button type="submit" class="btn orange sign-in-btn">Înscrie-te</button>
</div>
<?php echo $homepage_send ?>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- End Modal Video first page -->
</section>
UPDATE:
Ok. So i've manage to make it work the following code $(function () {
var frm = $('#participa-modal');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
location.reload();
}
});
ev.preventDefault();
});
});
The quetion is how can i replace alert('ok') to point for a thank you in the same pop-up under the SEND button.

$(".modal-body form").submit(function(e) {
var url = "ActionScript.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
$(this).html("Thank you!!!");
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
check the above code for your requirement
Terms Used
$(".modal-body form") class and child form selector in order to target your submitting form
.submit( to trigger event on submit of your form
type: "POST" is for secure traversing of data, by method post
.serialize() is to gather (assemble) and send the posting data
success: is a callback in order to proceed while the submission is successful.

Related

Ajax form gets submitted twice when i click on submit button second time

Simple bootstrap 5 (with validation) contact form with Ajax call gets executed only when i hit submit button second time and it also save data twice. this form is inside modal form and this behavior happened when i added Ajax function to code..
I am not sure what is stopping form submission successfully after validation, form gets submitted only when i hit submit button second time and it save same data twice.
based on references i used e.stopImmediatePropagation(); but there behavior didnt change
<!-- Modal -->
<div class="modal-form modal fade" id="modal-form" data-bs-backdrop="static" tabindex="-1"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Register you interest</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="form-body">
<div class="row">
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<p>Fill in the details below, we will get back to you!</p>
<form id="contactForm" class="requires-validation" action="sendemail.php" method="POST" novalidate >
<div class="col-md-12 mb-3">
<input class="form-control" type="text" name="name" placeholder="Full Name" required>
<div class="valid-feedback">Full Name field is valid!</div>
<div class="invalid-feedback">Full Name field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<input id="phone" type="tel" name="phone" class="form-control"
onkeypress="return isNumber(event)" required>
<div class="valid-feedback phoneinvalid" id="phoneinvalid"></div>
<div class="invalid-feedback">Phone field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<textarea class="form-control" name="message" id="message" placeholder="Your Message"></textarea>
</div>
<div class="form-button mt-3">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-success-msg"></div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
JS Part
(function () {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
console.log("form.checkValidity() "+form.checkValidity());
if (!form.checkValidity()) {
// form.classList.remove('was-validated')
//event.preventDefault();
//event.stopPropagation();
e.stopImmediatePropagation();
form.classList.add('was-validated')
return;
}
else
{
console.log("This line should execute only if Form is validated");
AjaxCallSaveData();
form.classList.add('was-validated')
}
}, false)
})
})();
function AjaxCallSaveData()
{
console.log(" I am AjaxCall Function");
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
phone: $("#phone").val(),
message: $("#message").val(),
};
$.ajax({
type: "POST",
url: "SaveData.php",
data: formData,
dataType: "json",
encode: true
}).done(function (data) {
console.log(data);
if (!data.success) {
console.log("alert alert-warning");
} else {
console.log("alert alert-success");
$(".form-success-msg").add("display","block");
$("form").html(
'<div class="alert alert-success">' + data.message + "</div>"
);
}
});
event.preventDefault();
});
}

Ajax modal submit parse json response for errors in form, error message repeating itself over both fields

I've got a modal window that is submitting a form to a database via ajax and if an error occurs it will return a json response. This has been working well on modal windows with only one input field, but I have another modal window with 2 fields and the json response correctly returns error messages, for instance:
As you can see, both fields with the error are in the response. Like I said, my script works fine and will show the error for a form with only one text input, but I have two in this form (ignore the first select element, it is pre-filled via ajax). Here's my script that handles the ajax success and error responses:
$(document).ready(function () //function to process modal form via ajax
{
$('.modal-submit').on('submit', function(e){
e.preventDefault(); //prevent default form submit action
var data = $(this).serialize();
var type = $(this).find('input[name="type"]').val(); //get value of hidden input
var url = $(this).attr('action'); //get action from form
var modal = $(this).closest('.modal');
var modalInput = $(this).find('.form-row input'); //get input from form
var modalId = $(this).closest('.modal').attr('id');
$.ajax({
url:url,
method:'POST',
data:data,
success:function(response){
refreshData(newId = response.id, modalId); // set newId to the id of the newly inserted item, get modalId
modal.modal('hide'); //hide modal
$(modalInput).val(''); //clear input value
},
error:function(response){
$.each(response.responseJSON.error, function (i, error) {
console.log(data);
console.log(response.responseJSON.error);
$(modalInput).addClass('input-error');
$('#' + modalId + ' .backend-error').html(error[0]); //return error from backend
});
}
});
});
});
Here's the html for the modal window with multiple inputs:
<!-- Add New Model Modal -->
<div class="modal fade" id="modelModal" tabindex="-1" role="dialog" aria-labelledby="modelModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modelModalLabel">Add new asset model</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" class="modal-submit" autocomplete="off" action="{{ action('AddAssetController#addDescriptor', ['type' => 'model']) }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="type" value="model">
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="inputManufacturerModel">Manufacturer *</label>
<div class="input-group">
<select name="inputManufacturerModel" id="inputManufacturerModel" class="form-control" required="required" onclick="refreshData()">
<option value="0">Select manufacturer...</option>
</select>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="inputModelNew">New model name *</label>
<div class="input-group">
<input type="text" name="inputModelNew" id="inputModelNew" class="form-control" placeholder="Add manufacturer model name" required="required">
</div>
<div class="backend-error"></div>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="inputModelNoNew">New model # *</label>
<div class="input-group">
<input type="text" name="inputModelNoNew" id="inputModelNoNew" class="form-control" placeholder="Add manufacturer model #" required="required">
</div>
<div class="backend-error"></div>
</div>
</div>
<div class="float-right">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- / Add New Model Modal -->
Result of error response:
Do I need to loop over the errors? How do I get the relevant error to show under the correct input field?
In ajax error don't use this
$(modalInput).addClass('input-error') because this will add the class to all modal's input and this will set the error to all modal's input. $('#' + modalId + ' .backend-error').html(error[0]);
Use input Id to set error like in your case $('#inputModelNew').parent('.input-group').siblings('.backend-error').addClass('input-error').html(error[0])

Javascript Show thankyou modal after model submit

Hi i have model with feedback form. After model submit should show another thank you model also need to store local storage. Help me.
<div id="myModal2" class="modal fade" role="dialog">
<form action="" method="post" onSubmit="popUpToggle();" id="myModal2" >
<div class="form_fields feedbackfield">
<textarea id="txtMessage" name="txtMessage" rows="5" class="form-control contact-input" placeholder="Message *" required></textarea>
</div>
<div class="form_fields">
<input type="submit" class="contact-submit" name="SUBMIT" value="SUBMIT">
</div>
</form>
</div>
<div id="myModal4" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="popupHead3">
Thank you for your feedback
</div>
</div>
Javascript :
setTimeout(function() {
if(localStorage.getItem("modalPopup")){$("#myModal2").modal('hide');}
else{$('#myModal2').modal('show');}
}, 5000);
function popUpToggle(){
localStorage.setItem("modalPopup", "commit");
}
You can try AJAX for form submit and then use
$('#myModal4').modal({show: 'true'});
Please try below code.
$("#myModal2").submit(function(){
event.stopPropagation();
event.preventDefault();
$.ajax({
type: "POST",
url: /* submit url or form action url */,
data: $(this).serialize(),
success: function(d){
/* do here what you want to do */
$("#myModal4").modal({show: "true"});
},
dataType: "JSON"
});
});

Update table after insert a new row to database with AJAX

I'll try to be as clear as I can. I'm trying to code a CRUD. I have a table that shows all the info about products. To register a new item I have a form in a modal and it sends the data with AJAX to a .php file called 'registro.php' where the data is inserted into the MySQL table.
I'd like to make that after clicking the 'Submit' button of the new-item form, the table auto-realoaded showing the new row too without refreshing the page.
The INSERT INTO is working fine but after inserting a new item, the <table> that displays all the data just disappears
So, this is my form # index.php
<div class="modal fade" id="myModalNorm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" id="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">×</span>
<span class="sr-only">Cerrar</span>
</button>
<h4 class="modal-title" id="myModalLabel"> Registrar un artículo </h4>
</div>
<div class="modal-body">
<!-- Modal form -->
<form name="nuevo_registro" id="nuevo_registro" action="" onsubmit="registrarNew(); return false">
<div class="form-group">
<label for="descripcion">Descripción</label>
<input type="text" class="form-control" id="descripcion" name="descripcion" placeholder="Descripción del artículo"/>
</div>
<div class="form-group">
<label for="precio">Precio</label>
<div class="input-group">
<span class="input-group-addon">Bs.</span>
<input type="text" class="form-control" id="precio" name="precio" placeholder="Precio"/>
</div>
</div>
<div class="form-group">
<label for="existencia">Existencia</label>
<input type="text" class="form-control" id="existencia" name="existencia" placeholder="Unidades en existencia"/>
</div>
<button type="submit" name="submit" id="submitmodal" class="btn btn-default">Guardar</button>
</form>
</div>
</div>
</div>
</div>
This is the ajax code at the bottom of index.php
$(document).ready(function() {
$('#nuevo_registro').submit(function(e){
e.preventDefault();
$.ajax({
url: 'registro.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#myModalNorm').modal('toggle');
$('#lista_articulos').fadeOut('slow', function(){
$('#lista_articulos').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
And this is registro.php where the data is inserted into the MySQL table
<?php
if ( $_POST ) {
require_once 'dbconnection.php';
$descripcion=$_POST['descripcion'];
$precio=$_POST['precio'];
$existencia=$_POST['existencia'];
$query = "INSERT INTO producto (descripcion, precio, existencia, estado) VALUES ('$descripcion', '$precio', '$existencia', 'A')";
$conexion->query($query);
$conexion->close();
}
?>
Hope you can help me and thank you so much.
I needed to do that, one day, and here's my solution:
Send data to PHP file and INSERT to the mysql database
Get the last inserted ID, find all available data regarding that row
Make an array out of that data and json_encode it
On the main page with the table, find the table and prepend or append the data you just received.

Bootstrap modal does not activate

I want to create a Navbar button that calls a bootstrap modal which contains a form. I found a gist at https://gist.github.com/havvg/3226804, and I'm trying to adapt it to my needs. I haven'y completed filling out the ajax portion of the script, but I notice that the modal does not activate. i want to press the button on the navbar and have the modal form pop up. What am I doing wrong?
<div class="hide fade modal" id="rating-modal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">button</button>
<h2>Your Review</h2>
</div>
<div class="modal-body">
<!-- The async form to send and replace the modals content with its response -->
<form class="form-horizontal well" id="modalForm" data-async data-target="#rating-modal" action="AjaxUpdate/modal" method="POST">
<fieldset>
<!-- Form Name -->
<legend>modalForm</legend <!-- Text input-->
<div class="control-group">
<label class="control-label" for="old">Old password</label>
<div class="controls">
<input id="old" name="old" type="text" placeholder="placeholder" class="input-xlarge">
<p class="help-block">help</p>
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="new">New password</label>
<div class="controls">
<input id="new" name="new" type="text" placeholder="placeholder" class="input-xlarge">
<p class="help-block">help</p>
</div>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer"> Cancel
</div>
</div>
<script src='js/jquery.js'></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
// $('form[data-async]').live('submit', function(event) {
$('#modalForm').on('submit', function (event) {
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function (data, status) {
$target.html(data);
}
});
event.preventDefault();
});
});
</script>
Try removing the class hide from your div:
<div class="fade modal" id="rating-modal">

Categories

Resources