Delete data after save inside modal bootstrap 3 - javascript

I have 2 pb to resolve with my form inside modal bootstrap 3
First : My data is saved twice
Second : When I save a data how to delete the data in input and textarea inside myform or if I reload the modal
Thanks
first : catagories.php ==> call a modal
<style>
.modal-dialog {
width: 900px!important;
}
</style>
<a data-toggle="modal" href="<?php echo FILENAME_MANUFACTURERS_POPUP;?>" data-target="#myModal"><?php echo osc_image (DIR_WS_ICONS . 'create.gif', TEXT_CREATE) ?></a>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body"><div class="te"></div></div>
</div> <!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
**second : inside my modal :manufacturers_popup.php**
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<form name="ajaxform" id="ajaxform" action="manufacturers_popup_ajax.php" method="post">
<input> .......</input>
<textarea>........</textarea>
</form>
<script type="text/javascript" src="ext/javascript/bootstrap/js/bootstrap_ajax_form.js" /></script>
third : my ajax files : bootstrap_ajax_form.php
$(document).ready(function() {
$("#simple-post").click(function() {
$("#ajaxform").submit(function(e) {
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax( {
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#ajaxform").submit(); //SUBMIT FORM
});
});

Several things wrong here.
A submit handler will bind to the submit event of the form, you don't need to do it inside a click handler for the submit button.
You don't want to trigger the submit the way you are doing , that is what is causing the second save. WHen you click on a submit button inside a form, it will automatically trigger the form submit.
Try it this way:
$(function () {
$("#ajaxform").submit(function (e) {
e.preventDefault(); //STOP default action do this first in case any errors thrown in code
var form = this;
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code class="prettyprint">' + data + '</code></pre>');
/* cleanup now */
form.reset()
},
error: function (jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
}
});
});
});

To clear your form Data you can use the below function
function clearFormFields(div){
$('#'+div).find('input:text, input:hidden, input:password, input:file, select, textarea').val('');
$('#'+div).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}
Add this function to your JS, and in your case you can call clearFormFields("ajaxform") when ever you want to clear the form fields
In case, If you need to clear your form data on every time hiding the Modal, you can bind it on your Bootstrap modal as
$('#myModal').on('hidden', function () {
clearFormFields("ajaxform");
})
see the other events on a Bootstrap modal here
In case the above function didn't clear your CKeditor text field, you can use the CKEditor API method setData see the detailed documentation here
Good Day

Ok, thanks for all orientation.
I found the solution
$(function () {
$("#ajaxform").submit(function (e) {
e.preventDefault(); //STOP default action do this first in case any errors thrown in code
var form = this;
$("#simple-msg").html("<img src='images/icons/loadingAnimation.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code class="prettyprint">' + data + '</code></pre>');
/* clear ckeditor instance */
for(k in CKEDITOR.instances){
var instance = CKEDITOR.instances[k];
instance.setData( '' );
}
// cleanup now
form.reset()
},
error: function (jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
}
});
});
});

Related

Bootstrap modal ajax form submited many times

I call form in modal using ajax, and using a modal button .save-modal the form is submitted using ajax. There are many submissions for the form and I don't know why?
The following code in the page -form- requested by the modal:
```
#section('content')
<h1>kk</h1>
<div id="modal">
{!! Form::model('App\Solution',['url' => $actionPath, 'id' => 'sForm', 'class' => 'form-inline']) !!}
<div class="form-group">
{!! Form::label('title', __('Title')) !!}
{!! Form::text('title',$solution->title,['class' =>'form-control']) !!}
#php ($eleE = $errors->first('title'))
{{-- #include('layouts.form-ele-error') --}}
</div>
<div class="form-group">
{!! Form::label('description', __('Description')) !!}
{!! Form::textarea('description',$solution->description,['class' =>'form-control']) !!}
#php ($eleE = $errors->first('description'))
{{-- #include('layouts.form-ele-error') --}}
</div>
{!! Form::close() !!}
<script>
$(document).ready(function(){
$(".save-modal").click(function(e){
alert('many time alert') //
e.preventDefault();
$.ajax({
url: '{{$actionPath}}'+'/?'+Math.random(),
type: "POST",
data: $("#sForm").serialize(),
success: function(data){
$("#modal-body").html($(data).find('#flash-msg'))
$("#actions-modal").modal('hide')
//return true;
},
error: function(xhr, status, response){
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
// $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText );
errors = xhr.responseJSON
console.log(errors)
$("#errors").html('');
$.each(errors,function(key, val){
console.log(key)
$("#errors").append('<span class="has-error help-block">'+val+'</sapn>')
//return false;
})
xhr.responseJSON = null;
}
return false;
}
})
return false;
})
});
</script>
</div>
#endsection
The alert after $(".save-modal").click(function(e){... is alerted many time, specially when closing the modal and open it again with repeating trying of save invalidated entries the increase in alert is not fixed i.e it is the sum of invalidated data submission trying in the previous opening of the modal.
The following is the modal code on the base page:
$(".action-create").click(function(e){
e.preventDefault();
alert($(this).attr('href'))
mhd = $(this).attr('title');//$(this).text()+' {{__("for Cavity")}}'+' '+$(this).attr('title');
href = $(this).attr('href')
//console.log(href)
$("#actions-modal").on('show.bs.modal', function(){
$("#modal-hd").html('<h4 style="display: inline">'+mhd+'</h4>');
$("#modal-body").html('<h4>{{__('Loading')}}<img src="/imgs/loading.gif" /></h4>')
gg(href)
})
$("#actions-modal").modal({
backdrop: 'static',
keyboard: false
});
});
$("#actions-modal").on('hidden.bs.modal', function(){
$("#modal-body").html('');
$(this).data('bs.modal', null);
//$(this).children('#errors').html('');
$("#errors").html('');
return false;
});
gg = function gg(){
$.ajax({
type: "GET",
url: href,
dataType: 'html',
success: function(data){
//console.log(data)
required = $(data).find("#modal");
$("#modal-body").html(required);
},
error: function(xhr, status, response ){
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText+ " With custom message:<br> "+ xhr.responseText );
//console.log(xhr)
}
}
});
return false;
}
I have tried to add return false in many parts of the code to cut any extra evaluation, I also tried to add random number to the ajax URL Math.random() but It seems that it executed many times.
There is also another form call on the same page called using the modal, and sometimes it be saved in addition to the called form!
When you call form using ajax then you should keep in mind that javascript/jquery code of document ready is executed every time you receive response.
so, when you first open you model ".save-modal" click event is binded. when close and reopen the model. again request goes to server ajax content loaded in browser window and again a click event is binded. This way you end up with multiple anonymous function binded to single event. all will execute on same event.
solution 1 (recomanded): Declare function in saperate js file or inline which is included in main page (not ajax). Then instead of binding click event using jQuery. call function from onclick property of your ".save-modal" button.
solution 2: declare a global variable "IsAjaxExecuting". Test if this variable is true then return from you save function (this will stop mutliple execution). if it is not true then make it true. execute you ajax function. when response received then make it false again. eg.
var IsAjaxExecuting= false; // new code
$(document).ready(function() {
$(".save-modal").click(function(e) {
if(IsAjaxExecuting) return; // new code
IsAjaxExecuting = true; // new code
alert('many time alert');
e.preventDefault();
$.ajax({
url: '{{$actionPath}}' + '/?' + Math.random(),
type: "POST",
data: $("#sForm").serialize(),
success: function(data) {
IsAjaxExecuting = false; // new code
$("#modal-body").html($(data).find('#flash-msg'))
$("#actions-modal").modal('hide')
//return true;
},
error: function(xhr, status, response) {
IsAjaxExecuting = false; // new code
if (status == "error") {
var msg = "Sorry but there was an error: ";
// $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText );
errors = xhr.responseJSON
console.log(errors)
$("#errors").html('');
$.each(errors, function(key, val) {
console.log(key)
$("#errors").append('<span class="has-error help-block">' + val + '</sapn>')
//return false;
})
xhr.responseJSON = null;
}
return false;
}
})
return false;
})
});

Multiple dynamic forms submit and run function after

I'm having troubles to get my function work properly. There are actually two problems I have.
1) Sometimes the script only adds 1 of eg 7 forms.
2) When updating the page my other function is called for every form submitted instead of just once.
So I have code that creates the form(s) if for example a user clicks a button.
var pp_total_change = function(){
.. .... .
$('.pp_count').each(function(){
.........
pp_total_list_items += "<li><form action='cart/add/"+$(this).attr("labelid")+"' method='post' id='form_"+$(this).attr("labelid")+"'><span>"+$(this).attr("labelname")+"</span><span class='amt'>"+$(this).val()+"</span><span>€ "+pp_total_price.toString().slice(0,-2)+","+pp_total_price.toString().slice(-2)+"</span></form></li>";
// which results in ->
<form id="form_51847052" method="post" action="cart/add/51847052">...text...</form>
<form id="form_51847053" method="post" action="cart/add/51847053">...text...</form>
<form id="form_51847054" method="post" action="cart/add/51847054">...text...</form>
etc...
Then a function which submit the forms
$('.temp-cart .addToCart').bind('click',function(){
$('.temp-cart form').each(function(){
var qty = $(this).find('.amt').text();
var qty2 = parseInt(qty);
var url = $(this).attr('action')+'/?quantity='+qty2+'/';
$.ajax({
url: url,
type: "post",
data: $(this).serialize(),
success: function(response, textStatus, jqXHR) {},
error: function(jqXHR, textStatus, errorThrown) {},
complete: function() {
updateStuff();
}
});
});
Then a function updateStuff() that need to get fired once when all forms are done submitting.
function updateStuff(){
updateCartAjax();
$('.order .pp_count, .pp_countsum .pp_count').val(0);
$('.order .submit').popover('destroy').button('reset').animate({'opacity':'1'},200);
$("html,body").stop(true, true).animate({scrollTop: 0}, 333);
$(".pp_count").val('0');
$("#pp_order_total ul li").remove();
$("#pp_order_total ul").text('U heeft hiernaast nog geen producten geselecteerd.');
}
So the problem I'm facing is that when a users "creates" for example 7 forms then only one of those 7 forms are submitted. When I click the submit button a second time then all forms are submitted. I thought thi shas something to do with the id's but that wasn't the case.
Second how do I run the updateStuff function only once after all forms are submitted?
Any help greatly appreciated...
function deploy(){
return new Promise(function(resolve,reject){
var count= $('.temp-cart form').length;
$('.temp-cart form').each(function(){
var qty = $(this).find('.amt').text();
var qty2 = parseInt(qty);
var url = $(this).attr('action')+'/?quantity='+qty2+'/';
$.ajax({
url: url,
type: "post",
data: $(this).serialize(),
success: function(response, textStatus, jqXHR) {},
error: function(jqXHR, textStatus, errorThrown) {},
complete: function() {
count--;
if(count==0)
resolve();
}
});
});
});
}
$('.temp-cart .addToCart').bind('click',function(){
deploy().then(function(){
updateStuff();
})
}

jQuery validation submitHandler not work in $.ajax post form data

I have Send data using $.ajax and validation with jQuery validation plugin like this :
<div class="" id="ajax-form-msg1"></div>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
JS:
jQuery(document).ready(function ($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [4, 20],
},
},
submitHandler: function (form) {
$("#ajax-1").click(function (e) {
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false
}).done(function (data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
});
}
});
});
In action my form validate using jQuery validation but after validation not submit and not send data.
how do fix this problem?!
DEMO HERE
The submitHandler is expecting a submit and you have a click event inside it and then an ajax call.
If you have a button type="submit" inside a form you don't even need a click event, the plugin will do the validation automatically. So just make the ajax call inside the submitHandler.
If you need to bind the action to a button using the click event, the proper approach should be something like this:
$('#button').click(function(){
var form = $('#myform').validate({...}); #store the validator obj
if (form.is_valid()){
// submit using ajax
} else {
// dont do anything
}
});
Call form.submit() at the end of your done function.
See: http://jqueryvalidation.org/validate/
Also, you do not need $("#ajax-1").click() because the submitHandler will be called automatically when you click on that button anyways. You can test this yourself by putting a console.log as the first line of submitHandler. Then fill out the form and press the button. See if it prints out your log message.
In submitHandler you are handling the submit , then again why did you write click event?
Here is the fix.
jQuery(document).ready(function($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [2, 20],
},
},
submitHandler: function(a, e) {
//a is form object and e is event
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false,
success: function(data) {
console.log(data)
},
error: function(err) {
console.log(err)
}
}).done(function(data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function(jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
Use success and error call backs to get data or error messages.
Note: Here (In StackOverflow) you will get 404 Page Not Found error when you submit. So try in your local.

Custom title on modal button while using a onclick on it

I have a modal button that call a ajax function. I pass an "id" as argument of the function.
<div class="modal-footer" >
<button type="button" class="btn btn-default" data-dismiss="modal">Cierra</button>
<button type="button" class="btn btn-danger" id="myModalId" data-customer-id="myModalId" onclick="myCall(this)" >Erase</button>
</div>
"myModalId" is the the parameter I have to pass to the mycall funtion using data-customer-id.
the mycall script is:
function myCall(self) {
self = $(self);
var point = $('#myModal #'+self.data("customer-id")).text();
//alert(point);
var request = $.ajax({
url: "./php/deleteLocation.php",
type: "GET",
data: { pointPHP: point},
success: function(response) {
location.reload();
}
});
request.done(function(msg) {
$("#mybox").html(msg);
$('#myModal').modal('hide');
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
$('#myModal').modal('hide');
});
}
I works but the title of the button is the same of the argument (ie 231), while I want a custom title like "Erase".
Where is my foult?

What would cause an ajax request to fire multiple times from a jQuery dialogue button

I have a partial View that creates the following html:
<div id="tabs-3" style="display: block;">
<div id="My_List">
</div>
<button id="create-log" role="button"> Create new Comment </button>
<div id="dialog-log">
<input type="hidden" value="6265" id="My_ID"/>
<div><label>Title</label><input id="My_Title" type="text" value=""/></div>
<div><label>Message</label><textarea id="My_Message">...</textarea></div>
</div>
</div>
The partial View also renders the following script block just below the html.
<script>
$(function () {
$("#dialog-log").dialog({
autoOpen: false, modal: true, height: "auto", width: "auto", title: "Add Comments to the Log",
position: { my: "center top", at: "center top", of: window },
buttons: {
"Create Comment": function () { UTIL.CreateComment($("#My_ID").val(), $('#My_Title').val(), $('#My_Message').val(), $(this)); },
Cancel: function () { $(this).dialog("close"); }
}
});
$("#create-log").button().click(function () {
$("#dialog-log").dialog("open");
});
});
</script>
The layout View includes a Utility.js file. It declares a script literal that facilitates the ajax call in the dialogue's "Create Comment" click event.
var UTIL = {
HandleAjaxError : function (jqxhr, textStatus, errorThrown, fn) {
switch (textStatus) {
case "timeout": alert(fn + "\n\nStatus:server timeout"); break;
case "error": alert(fn + "\n\nStatus:general error \nError Thrown:" + errorThrown); alert("object status: " + jqxhr.status + "\nresponse text \n>>>\n" + jqxhr.responseText + "\n<<<\n"); break;
case "abort": alert(fn + "\n\nStatus:abort"); break;
case "parsererror": alert(fn + "\n\nStatus:parsererror \nError Thrown:" + errorThrown); alert(jqxhr.responseText); break;
}
//alert(jqxhr.responseText);
},
CreateComment: function ($Id, $Title, $Message, $dlg) {
var mydata = "ID=" + $Id + "&Title=" + $Title + "&Message=" + $Message;
var jqxhr = $.ajax({ url: "/Log/Create/", type: "POST", dataType: "html", data: mydata
}).done(
function (returnhtml) {
$('#My_List').html(returnhtml);
$('#My_Title, #My_Message').val("");
$dlg.dialog("close");
}).fail(function (jqxhr, textStatus, errorThrown) { UTIL.HandleAjaxError(jqxhr, textStatus, errorThrown); })
}
}
So what happens in the browser is that sometimes - for reasons that I cannot explain - multiple ajax calls are fired when the user clicks the "Create Comment" button created by the dialog. This occurs randomly, but frequently... enough to make me worry.
What's more is that the number by which ajax calls are repeated varies - sometimes it's 3-5 and other times it's 11-15 ...
My question is more related to technique since I cannot replicate the behavior in any way, though it happens periodically in the production environment.
I need reputation of 10 to post the screenshot ...
As pointed out by Kevin B the issue might simply be that people keep pressing the button.
You should include a "sending" option when the button is pressed and then disable it.
This can be accomplished in multiple ways, but the easiest is to set a flag:
CreateComment: function ($Id, $Title, $Message, $dlg) {
// avoid multi-sending
if($dlg.data().sending)
return;
$dlg.data().sending = true;
var jqxhr = $.ajax({ url: "/Log/Create/", type: "POST", dataType: "html", data: mydata
}).done(
function (returnhtml) {
// reset sending flag so in when opening the dialog again, another comment can be sent
$dlg.data().sending = false;
$('#My_List').html(returnhtml);
$('#My_Title, #My_Message').val("");
$dlg.dialog("close");
}).fail(function (jqxhr, textStatus, errorThrown) {
$dlg.data().sending = false;
...
This way it checks if the dialog is already sending data and will not run until the data is actually sent (on the done/fail the variable is reset)
This should take care of browser bugs or multi-clicking.

Categories

Resources