Closing Modal when using ajax and validation - javascript

i have run into a little issue for closing a data modal with bootstrap i have showed a bit of code below basically at the current stage the ajax validates the form via the input submit field this works however it doesn't close the modal it resides in
so my question how can i utilize the same ajax code but allowing the data modal to close on submission please bare in mind the modals id is webapp_customers_modal but is dynamic with a number on the end as its used in multiple places
this is the preferred method i would like to use but doesn't submit the form
<button type='submit' data-dismiss='modal'data dismiss='modal'>Save</button>
This is the current form submit im using this works but doesn't close the modal
<input type='submit' class='btn btn-info' value='Save' >
this is the ajax code
<script>
$(function() {
$('form.frm_details').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: '/limitless/functions2.php',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if(data.status == '1')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
if(data.status == '2')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
webapp_get_customers();
}
}
});
});
});
</script>

If you only have one of your modals open at a time you can add a common class, like my-modals to them and then use this in you script. This way you don't need to keep track of your dynamic created id's.
$('.my-modals').modal('hide');

Why not close modal using javascript? Give your modal an Id
$('#myModal').modal('hide'); //This closes modal with id 'myModal'
PS: you can add the above code inside success callback.

Related

How to close the second bootstrap modal when submit and keep on the first modal?

I am using Laravel 5. I have a page which contains 2 bootstrap modals in 1 page of PHP; modal on modal like in the picture below. My problem is when I click submit on the second modal, it will redirect to the blank page. I want that second modal is closed and the first modal is still in there. And I am trying using ajax and I am not good at it.
This is my submit button on the second modal:
<button type="submit" id="shipmat_btn" class="btn btn-success">Submit</button>
This is my controller code:
public function MaterialShipmentAdd(Request $request)
{
$shipment = new Shipment;
$shipment->setConnection('SUPPLYCHAIN');
$shipment->MAT_ID = $request['sip_material_add'];
$shipment->MAT_NAME = $getmatname[0]->MAT_NAME;
$shipment->SIP_QUANTITY = $request['sip_quantity_add'];
$shipment->SIP_CREATED_AT = date('Y-m-d H:i:s');
$shipment->save();
}
The ajax code:
$('#shipmat_btn').submit(function(e) {
$.ajax({
url: "MaterialShipmentAdd",
type: "POST",
cache: false,
success: function(data){
$('#myModal2').modal('hide');
}
});
});
Your question isn't that much clear about your problem yet from I understand,
The reason you get redirect to a blank page because your form is submitting using HTML. You need to prevent that by adding e.preventDefault() inside $('#shipmat_btn').submit
You can hide the you first modal when the second modal started to show up by using show event. just like this,
$("#myModal2").on('show.bs.modal', function () {
$('#yourModal1Id').modal('hide');
});
hope this helps!

Ajax works after I press submit twice

Very brief, this is my php code in myPage.php:
<div class="table-responsive" id="items">
<table class="table" id="myTable">
<thead><tr><th>item<th>status<th>options</thead>
<tbody>
[...]
echo "<tr><td>$item<td>$status<td>to-be-added
[...]
echo "<tr><td colspan='3'>";
echo "<form method='post' id='newitem'>";
echo "<input type='hidden' id='uid' name='uid' value='$uid'>";
echo "<div><button type='submit' class='btn btn-info' id='submitbtn'>new item</button></div>";
echo "</form>";
[...]
And this is my .js file ajax code:
$(document).ready(function () {
$('form').submit(function (event) {
$('#errors').remove(); // remove the error text
$('#success').remove(); // remove the success text
var formData = $("#newitem").serialize();
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
if (!data.success) {
$('form').append('<div id="errors" class="alert alert-warning"></div>');
if (data.errors.validitem) {
$('#errors').append('<p>' + data.errors.validitem + '</p>');
}
} else {
$('#addresses').append('<div id="success" class="alert alert-success">' + data.message + '</div>');
$("#myTable").load("mypage.php #myTable");
}
})
.fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
I Don't show the process.php function as that is not most likely the problem.
When I first load the page and press submit following things happen:
a new item is created via ajax
table gets populated with new entry w/o page refresh but using the load option: *$("#myTable").load("mypage.php #myTable");*
in conclusion, everything works as expected!
Note: only after I add the table load the problem appears. $("#myTable").load("mypage.php #myTable");
Without this reload of the table after submit, submit always work, just that the table doesn't show real time the changes and I need to do F5 ... which is not the plan.
After the load of the table, when I press the button again, nothing appears to happen, except that my success message disappears.
At this stage I need to press the button twice. Only after I press submit a second time, the ajax executes ok and table shows the new item created.
This behavior is consistent for all next submits. All execute only after second submit.
I need some help here please. What is happening?
I want to reload only a section of the myPage.php, so only the full table #myTable or whole div #items, with all the validation functions I have in myPage.php
I don't want to recreate full table in the process.php and send it over via POST as I have seen some recommend in other forums.
The issue is here : $("#myTable").load("mypage.php #myTable");
mypage.php is your main page. And you load it once. Then, inside the table, you use that .load() to overwrite it all. Which is no good.
You then have a brand new table where no handler is binded to the submit button. So on submit button click (second time), the form is submitted using the "normal behavior" of a <form> element... And the page is fully reloaded.
As a possible solution, I would use .load() on the form... Not the table, like this:
$("#newitem").load("mypage.php #newitem");
But you should try $("#newitem").reset() and just remove #error and #success... Instead of that .load().
EDIT
Second taugth:
Try $(document).on("submit", "form", function (event) {
instead of $('form').submit(function (event) {
That is delegation... So your submit button always will be binded to the function, even if it is overwritten.

Two submits one ajax one regular form

I have this form that i am trying to submit with ajax as well as the regular submit the regular submit is for creating a pdf and the ajax submit is for showing an html example for showing the preview which both work just fine if i use them both individually or use the create pdf before the preview submit but if sumbit for pdf after the preview submit it's not functional, nothing happens like regular submit button is disabled. My code is attached as folows, Do note both work fine just the regular post doesn't work if i use ajax submit first.
<script type="text/javascript">
$('#submitpdf').submit(function() {
return true;
});
$('#submitpreview').click(function() {
$('#form').submit(function(event) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('GET'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false;
});
});
</script>
and here is the HTMl of the form tag and the submit buttons:
<form action="dopdf.php" name="formular" id="form" method="GET" enctype="multipart/form-data">
<input type="submit" id="submitpdf" value="Create PDF" name="print" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
<input id="submitpreview" type="submit" value="Preview!" name="preview" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
</form>
One other thing to note is that with ajax i want to submit to "test.php" and with regular submit i want to submit to "dopdf.php".
The code for submitPreview button click does not look correct to me ( on the click handler, you are basically registering the submit event code!). Try changing to this clean version. Also, make sure to wrap your event handler code inside the document.ready event to avoid other issues.
Also you need to read the method attribute of the form, not GET attribute.
$(function(){
$('#submitpreview').click(function(e) {
e.preventDefault(); // prevent the default form submit behaviour
var _this=$(this).closest("form");
$.ajax({ // create an AJAX call...
data:_this.serialize(), // get the form data
type: _this.attr('method'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
});
});
Since your form action value is set to dopdf.php, when user clicks that button, It will be submitted to dopdf.php. You do not need any additional jQuery click handler for that.
you could do the following
your script like this
$('#form').submit(function() {
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('GET'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
});
and the form as it is. don't change it

jquery hide only hiding one button

function Login(){
contentType: "get",
dataType: 'json',
success: function(data) {
$("#login").hide(); //hide the login button
$("#logout").show(); //show the logout button
$.mobile.changePage("#home"); //show the menu
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
console.log(r);
alert("Error:" + r.error.text);
}
});
}
I have the above function to hide the login button however using jqm i have many login buttons on different pages all with the same id. When this function is accessed however only one of those buttons is deleted. It has something to do with every log in button having the same id however im not sure of any other way where i can delete all log in buttons without them having a different id and then hiding all on each individual page
A feature of IDs is that there is supposed to be one and only one element with a given ID. You might try using a class instead. Your HTML would change to be something like this:
From:
<button id="login" class="foo">Login</button>
to:
<button class="foo login">Login</button>
and your new jquery hide would be:
$(".login").hide();
Instead of using just the ID as the selector, how about accompany the element tag as well?
$('button#login').hide();
Or multiples!
$('button#login, div#login, input#login').hide();
JSFiddle: http://jsfiddle.net/wyze/HS3zS/1/

jQuery fadeIn div after page reload

i have a form that stores user data via an ajax call.
On success i normally have a div fade in with a success message. However i want to reload the page so that the page is updated, and then fade in the success message.
I was using a .load() to update the div, and then toggle the form to hide itself etc. But the .load was causing some other js scripts to not work after it was called etc so for now im going to just reload the page.
However, i want to show the success message div after the page has been reloaded.
This is an example:
if (check) {
$.ajax({
type: "POST",
url: "process/updateuserpref.php",
data: $('.updatepref').serialize(),
dataType: "json",
success: function(response){
if (response.updatePrefSuccess) {
location.reload();
$('#successdisplay').fadeIn(1000);
$('#successdisplay').delay(2500).fadeOut(400);
}
}
});
}
I know obviously the
$('#successdisplay').fadeIn(1000);
$('#successdisplay').delay(2500).fadeOut(400);
Doesnt currently work, but any help on how i can do what i want?
Thanks, Craig.
Instead of simple reloading you could sent a GET variable with the reload, then check if the GET variable exist show the success message if not, do nothing
I do the same thing, so this is how I do it:
intead of reload() I do:
window.location.href = document.location.protocol +"//"+ document.location.hostname + document.location.pathname + '?success=1';
Then in my PHP script I do a conditional output:
<?php if( $isset( $_GET['success'] ) && $_GET[ 'success' ] == 1 ) { ?>
<div id="successdisplay">
Changes performed Successfully
</div>
<?php }?>

Categories