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.
Related
I have an Javascript on click event that will loop all of the json to store it to database with ajax and before that i already add some modal to popup before the loop is running. but the problem is the modal doesn't pop up before the loop is running and pop up after the loop is running this is my code
this i my javascript
$.fn.dataTable.ext.buttons.Mapping = {
text: 'Save To Database',
action: function (e, dt, node, config) {
$('#modal-respondent-upload').modal('show');
var filename = $("#xlf").val().replace("C:\\fakepath\\", "");
var obj = jQuery.parseJSON(output);
$.each(obj.hasil, function (key, value) {
var dataRespondent = {
json: JSON.stringify(value),
importSessionDataID: 1
}
console.log(dataRespondent);
var respondentID = simpleAjaxRequest(dataRespondent, "/UploadExcel/CreateRespondent/", "Import Respondent Data");
});
}
};
function simpleAjaxRequest(data, url, text) {
var id = 0;
$.ajax({
type: 'POST',
url: url,
data: data,
async: false,
success: function (data) {
//moveProgressBar(10, text);
id = data;
}
});
return id;
}
and my modal is like this
<div class="modal fade" role="dialog" id="modal-respondent-upload">
<div class="modal-dialog">
<div class="modal-content">
<h1><span id="kondisi-data-modal">0</span>/<span id="jumlah-data-modal">0</span></h1>
</div>
</div>
</div>
So this is the form I have
<form action="javascript:void(0);" class="form-inline" id="receive-order-form"> By Receiving you agree that you have received the item <b> {{ x.item_name }} </b> at the store. </br> Order Id <b> {{ x.order_id }} </b></br><input class="btn btn-primary center-block" onclick="execute({{x.linq_order_num}})" type="submit" id= 'receive-btn' value="Receive" ></form>
On submit the remote call gets executed and I get the success pop up but somehow the screen gets stuck like this. Page becomes unresponsive.
Execute Function Definition:
function execute(linq_order_num) {
var result = "";
var tableRow=document.getElementById("order_num1_"+String(linq_order_num));
var modalId = "exampleModal1_" + "{{ linq_order_num }}";
jQuery.ajax ({
url: "/receive-order/",
type: "POST",
data: JSON.stringify({"linq_order_num":linq_order_num}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){
result = data;
$("#modalId").modal('hide');
$('#alert_placeholder').html('<div class="alert
alert-success"><a class="close" data-
dismiss="alert">×</a>
<span>Successfully received the product</span>
</div>');
var htmlElement = document.getElementById("deliver-
order_"+ String(linq_order_num));
var cln = htmlElement.cloneNode(true);
cln.style.display = null;
tableRow.cells[7].innerHTML = cln.outerHTML;
}
});
return result;
}
how can I solve this ?
Assuming you were wanting to hide the modal id referenced in:
var modalId = "exampleModal1_" + "{{ linq_order_num }}";
Change:
$("#modalId").modal('hide');
Into:
$("#" + modalId).modal('hide');
In the current version, you are trying to hide the element with id="modalId" in the HTML.
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?
I've following HTML code:
<a href="#" id="promotion_status_1">
<button type="button" class="btn btn-default brmodalbtn" data-toggle="modal" data-target="#BrandImageModal" id="1">On</button>
</a>
<div class="container">
<div class="modal fade" id="BrandImgeModaal">
<div class="modal-dialog">
<div class="modal-content">
<form id="form" enctype="multipart/form-data" role="form">
<input type="text" class="form-control" name="brand_id" id="brand_id" value="{$data.id}">
<input type="text" name="admin_url" id="admin_url" value="http://localhost/abc.com">
<input type="text" name="op" value="upload_brand_image">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Brand Image</h4>
</div>
<div class="modal-body">
<div id="messages"></div>
<input type="file" name="file" id="file">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
jQuery AJAX Code :
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
//data : formdata ? formdata : form.serialize() + '&' + $.param({'op':'upload_brand_image'}),
contentType : false,
processData : false,
success: function(response) { alert(response); return;
if(response.error == 1) {
$('#BrandImageModal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
},
dataType:"JSON"
});
e.preventDefault();
});
PHP Code:
$request = $_REQUEST ;
switch( $op ) {
case "upload_brand_image":
$ret = $objManufacturer->UploadBrandImage($request, $_FILES, $allowed_image_extension, $manuf_error_messages);
if(!$ret) {
$error_msg = $objManufacturer->GetAllErrors();
$response = array(
"error" => 1,
"error_message" => $error_msg
);
echo(json_encode($response));
} else {
if(!empty($_FILES['file']['name'])) {
upload_file_now( $_FILES['file'], $brand_image_path, $t, $brand_name, $ext);
}
}
die;
break;
}
The $error_msg array contains following content :
Array
(
[domain_id] => Please select domain
[brand_name] => Brand name can't be blank
[brand_name_invalid] => Brand name is not valid, it should be alphabetic
[email] => Brand email can't be blank
[email_invalid] => Brand email is not valid
[brand_image] => Brand image can't be blank
[brand_image_format] => Please upload brand image in a proper format
[brand_image_size] => Brand image size is greater than 5 MB
[brand_image_dimesnions] => Only upload brand image having dimensions >= 940 X 370 px
[details] => Brand details can't be blank
)
I'm not able to print the messages contained in this array in bootstrap modal.
Where I'm doing wrong? Would someone please help me in this regard?
Thanks
just change the success code...
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
//data : formdata ? formdata : form.serialize() + '&' + $.param({'op':'upload_brand_image'}),
contentType : false,
processData : false,
success: function (response) {
alert('successful : ' + response);
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
dataType:"JSON"
});
e.preventDefault();
});
Remember, json data is passed from server to broswer as text, in order to use it sensibly you need to convert it to a proper JSON object using $.parseJSON()
So try
success: function(response) {
response = $.parseJSON(response);
if(response.error == 1) {
Also modern browsers all have a javascript debugger associated with them. Get used to using it. Then you can set a breakpoint on the first line of the success: method and view the contents of the returned data, and pretty much everything else thats in scope as well.
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>');
}
});
});
});