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?
Related
I'm have an html table with modal column (see image below for your reference)
Upon click the Order modal, I can access the its ID using onclick event in JavaScript
(var customer_id = $(this).val();)
I wanted to access and used it in my Add function using ajax but I'm having an error of "customer_id is not defined" when I tried to use it. Is there a way to fix it or do it properly.
This is my script
<script>
$(document).ready(function () {
// START OPEN CART MODAL FUNCTION
$(document).on('click', '.viewCart', function (e) {
e.preventDefault();
var customer_id = 0;
var customer_id = $(this).val();
console.log(customer_id);
$.ajax({
type: "GET",
url: "/get-cart/"+customer_id,
dataType: "json",
success: function (response) {
if (response.data != null) {
console.log(response);
$('.OrderTbody').html("");
$.each(response.data, function (key, item) {
$('.OrderTbody').append('<tr>\
<td>' + item.p_name + '</td>\
<td>' + item.c_qty + '</td>\
<td class="total">' + item.p_amt + '</td>\
<td><button type="button" value="' + item.c_id + '" class="btn btn-danger deleteListBtn btn-sm">Delete</button></td>\
\</tr>');
});
}
}
});
});
// END OPEN CART MODAL FUNCTION
// START ADD DATA FUNCTION
$(document).on('click', '.addToCart', function (e) {
e.preventDefault();
var data = {
'store': $('.sel_store').val(),
'product': $('.sel_product').val(),
'quantity': $('.sel_qty').val(),
// HOW TO INPUT Customer ID here, I tried this but im having an error of
// customer_id is not defined
'customer_id': customer_id,
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/cart-list",
data: data,
dataType: "json",
success: function (response) {
}
});
});
// END ADD DATA FUNCTION
});
</script>
In case that chosen attributes are the same, after clicking "Save button" - button disappears.
(it disappears from code, got deleted)
[Image before clicking][1]
[Image after clicking][2]
Most confusing thing is that, add button was coded the same but it works well...
I've got no clue what might be the case here.
Button:
<input type="button" height="20" class="btn btn-warning" onclick="return saveEdit()" value="Save" />
function saveEdit() {
var elem = $('#Domain_Edit');
$.ajax({
url: "/Domain/DomainEdit",
type: "post",
data: elem.serialize(),
cache: false,
success: function (result) {
if (result.redirectTo) {
alert(window.location.href = result.redirectTo + '?siteMessage=' + result.siteMessage);
}
else
{
$(elem).html(result);
}
},
error: function (xhr, status, error) {
$(elem).html('<div class="alert alert-danger" role="alert">' + xhr.status + " " + xhr.statusText + '</div>');
}
});
}
Code of button on page:
<input type="button" height="20" class="btn btn-warning" onclick="return btnSave('89515a0b-a671-4eff-a0eb-61c1d268f696')" value="Save">
function btnSave(id) {
var elem = $("." + id).closest('#DomainTrust_Edit');
$.ajax({
url: "/Domain/DomainTrustEdit",
type: "post",
data: $("." + id).closest('#DomainTrust_Edit').serialize(),
cache: false,
success: function (result) {
if (result.redirectTo) {
// The controller action returned a JSON object with the redirectTo property
window.location.href = result.redirectTo + '?siteMessage=' + result.siteMessage;
} else {
// The controller action returned a partial view with the form and the errors so update of the containing FORM with it is needed.
$(elem).html(result);
}
},
error: function (xhr, status, error) {
$(elem).html('<div class="alert alert-danger" role="alert">' + xhr.status + " " + xhr.statusText + '</div>');
}
});
}
Is your button located inside the #Domain_Edit element?
Since .html(result) replaces all html inside #Domain_Edit so if your button is inside that element, that would explain why it got removed.
I have searched for this issue and although some of the solutions work none of them fit my issue.
I am creating links dynamically using ajax calls. When any of the links (styled as button) is clicked I need to show http:\\<IP-address> in the modal.
When links are created and I use "inspect" and copy what is rendered and paste it on top of the page and click it, it does show the content in modal pop up, so I know the script that displays content in modal works. But when I click on actual, dynamically created, links it opens the pop up with no content.
Here is a watered down version of what I have and what I have tried:
Modal popup:
<div class="modal fade" id="printerInfoModal" role="dialog" aria-labelledby="mainModalLabel" aria-hidden="true">
<div class="modal-dialog fade in">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<asp:Label ID="lblModalTitle" runat="server" ClientIDMode="Static" Text=""></asp:Label></h4>
</div>
<div class="modal-body">
<iframe src="" id="modeliframe" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>
</div>
<div class="modal-footer">
<button id="btnCloseModal" class="btn btn-info" data-dismiss="modal" aria-hidden="true" aria-label="Close">Close</button>
</div>
</div>
</div>
</div>
// Get a list of printers and for each get its status, printer property includes IP address
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Services/ps.asmx/GetPrinterMapping",
cache: false,
data: "",
success: function (response) {
if (response !== "") {
try {
jResponse = JSON.parse(response.d);
$.each(jResponse, function (index, value) {
var printer = value;
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Services/ps.asmx/GetPrinterStatus",
cache: false,
data: JSON.stringify({ PrinterHostnameIPAddress: printer.IPAddress }),
success: function (result) {
if (result !== "") {
var printerIP = 'http://' + printer.IPAddress;
//var redir = 'openInfo("' + printerIP + '")';
if (status == "Ready") {
$('<div/>', { class: 'col-sm-2' })
.append($('<a/>', { id: 'printer' + printer.IDN, class: 'form-control btn btn-success btn-block extLink', style: 'margin-bottom:5px', href:printerIP, text: status.replace(/\"/g, '') }))
.appendTo($('#printerStatusTable'));
// Not sure if below two lines work!
//It seems I cnnot add data-target: 'xxx' in attributes list part of "append"
$('#printer' + printer.IDN).attr('data-target', '#printerInfoModal');
$('#printer' + printer.IDN).attr('data-toggle', 'modal');
},
error: function (result) {
},
failure: function (result) {
}
});
})
$('#printerStatusTable').find('a').attr('data-target', '#printerInfoModal');
$('#printerStatusTable').find('a').attr('data-toggle', 'modal');
// Another think I tried
$('#printerStatusTable').find('a').attr('onclick', 'blah(' + $(this).attr('href') + ');');
JS:
// this function is hit if I copy/paste the html of the the link/button and click it; otherwise it is not called
$('.extLink').click(function (e) {debugger
e.preventDefault();
var frametarget = $(this).attr('href');
//clearIframe();
targetmodal = '#printerInfoModal';
$('#modeliframe').attr("src", frametarget );
});
function blah(){debugger
var frametarget = $(this).attr('href');
targetmodal = '#printerInfoModal';
clearIframe();
$('#modeliframe').attr("src", frametarget );
}
function blah(frametarget){debugger
//var frametarget = $(this).attr('href');
targetmodal = '#printerInfoModal';
clearIframe();
$('#modeliframe').attr("src", frametarget );
}
function clearIframe() {
var iframe = $('#modeliframe');
var html = "";
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
}
This works, when I add the link manually; what I actually see when I click on the ajax-created link/button and select "inspect":
<a class="form-control btn btn-block extLink btn-success" id="printer10" style="margin-bottom: 5px;" href="http://1.2.3.4" data-toggle="modal" data-target="#printerInfoModal">Ready</a>
Can anyone see what am doing wrong or what I am missing?
So, if you are adding the button dynamically after the page loads, you'll need to target the document with your click handler like this:
$(document).on('click', '.extLink', function() {
// Do what you want when the button is clicked.
});
This is because when your page loads all of your Jquery handlers are attached to the DOM. If the element doesn't exist, then you are attaching them to nothing basically.
After successing ajax request and saving data in database i have problem when i try to remove active class from button. On click i show spinner and when ajax finish i want remove active class. On click spinner start but never stop. I try to debug it with alert() inside success and i get message. WHat can be problem?
submiteComment: function() {
$("body").on("click", '.submit-comment', function(e) {
e.preventDefault();
var post_id = $(this).data('post');
var comment_text = $(".comment_text");
if($.trim(comment_text).length) {
$(this).addClass('active');
$.ajax({
type: "post",
url: baseurl + '/comment/create',
data: {'post': post_id, 'comment_text': comment_text.val()},
success: function() {
$(this).removeClass('active');
alert("Success");
}
})
}
});
},
And html:
<button type="submit" class="btn btn-xs btn-default submit-comment has-spinner" data-post="<?= $post->post_id;?>">
<span class="spinner"><i class="fa fa-spinner fa-spin"></i></span>
Comment
</button>
Are you sure that the this in $(this).removeClass('active'); is equal to your DOM element when your code is executed? Looks like you need rewrite part of your code as
success: (function() {
$(this).removeClass('active');
alert("Success");
}).bind(this)
you can assign $(this) as a var outside of ajax like
var $this = $(this);
$this.addClass('active');
$.ajax({
type: "post",
url: baseurl + '/comment/create',
data: {'post': post_id, 'comment_text': comment_text.val()},
success: function() {
$this.removeClass('active');
alert("Success");
}
})
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>');
}
});
});
});