I thought this would be easy enough but it's giving me problems. I tried searching other answers to solve this, but to no avail. I have a list of buttons where the id value is dynamic.
<a href="#" class="btn btn-default notesButton" data-id="<?php echo $id; ?>"
role="button">Notes</a>
Then have JavaScript where I want to opent the modal window and get the id as a variable that I can echo in the window or use in a query.
$(document).ready(function(){
$(".notesButton").click(function(){
$("#notesModal").modal();
var myOrderId = $(this).data('id');
});
});
Finally, I try to echo myOrderId in the modal, or use it in a query. But, it doesn't show.
<div id="notesModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Order Notes</h4>
</div>
<div class="modal-body">
<?php echo $myOrderId; ?>
</div>
</div>
</div>
</div> <!-- end modal -->
Once I'm able to echo this value, then it should be easy to use it in an sql query inside the window, but for now I can't get the value to echo in the modal window. Any suggestions please?
$("#notesModal").on("show.bs.modal", function(evt) {
var $btn = $(evt.relatedTarget);
var $modal = $(evt.target);
var $content = $modal.find(".modal-body");
$content.text( $btn.data("id") );
});
PHP is server side language, javascript is client-side language, so it is called afterwards.
var myOrderId is javascript, not PHP variable.
You can try it out here: jsfiddle
Learn more about Bootstrap Modals in documentation.
EDIT: Regarding SQL query:
If you want to use your id as a paramter in SQL query when modal shows, again, you do not do that client, but server side. According to varying modal content chapter of documentation, general approach is:
Store varying data in the element which shows modal (you already do that with your data-id)
Now you have two different approaches:
POST AJAX call to your server within .on('show.bs.modal', function(){}) second parameter, where you send the data you store in the button (data-id), query your DB server side and respond with required results, which you can use before modal shows in AJAX callback function;
prepare all the SQL data beforehand, render it as JSON document within element which show.bs.modal, as let's say data-sql, and then use it in the second parameter of .on('show.bs.modal', function(){})method, accessing it like: $(evt.relatedTarget).data("sql");
Related
I have an asp.net web forms website that I am trying to enhance by adding popup modals that show the rental rates for equipment available to rent. On most pages, the rates are 'static' and are posted at the top of the page for all the equipment on that page. However on a few pages, the rates cannot be ‘static’ at the top because each piece of equipment has different rates, thus the need for the popup.
I have created a user control (I'll call 'Rate Card') that does the database lookups and rate calculations for the equipmentID passed to it, and it then creates a formatted DIV (complete with stylings, disclaimers, and links to the Terms and Conditions). For the 'static' pages, I simply insert this DIV in my document’s asp:placeholder and I'm done. For the other pages, I would like to keep using my Rate Card user control as the contents of the popup.
Here is what I have tried:
asp:buttons using the 'onClick' to initiate server side code to generate the Rate Card. It is then inserted into a block of bootstrap modal code in the document, and finally the server side calls some javascript code (via ClientScript.RegisterStartupScript) that displays the modal popup. This works, however the webpage reloads each time you click on the View Rates button, and scrolls back to the top. If I try to check for 'isPostBack' and just return if it is, the page still reloads and all I have is the header and footer from my site master.
I started coding to put the bootstrap modal block inside an asp:UpdatePanel, but after reading several different posts, it seems the page would still reload.
So what I am wanting to accomplish is to have the user click an element beside the name of a piece of equipment (button, link, label, div, etc.) and have the something trigger the Rate Card to be generated, and then display as a modal popup.
My programming background is C# mainly for WinForms client applications, but have some experience with asp.net websites. So, I may need some extra guidance and examples.
Thanks in advance for any assistance!
ADDED CODE:
Button source:
<asp:Button ID="ShowRates" runat="server" OnClick="ShowRates_Click" CommandArgument="0" Text="View Rates" ></asp:Button>
Button code behind:
protected void ShowRates_Click(object sender, EventArgs e)
{
var ID = ((Button)sender).CommandArgument;
if (int.TryParse(ID, out int assetID) == false) return;
assetCard_ShowRate(sender, e, assetID);
}
private void assetCard_ShowRate(object sender, EventArgs e, int assetID)
{
Controllers.AssetController ctlr = new Controllers.AssetController();
var rates = ctlr.GetAssetRateCardsByAssetID(assetID);
UserControls.RatesTable2 ratesTable = (UserControls.RatesTable2)LoadControl("~/UserControls/RatesTable2.ascx");
ratesTable.BuildRateCard(rates, "");
//Add the rate card control to the placeholder
phRateCard.Controls.Add(ratesTable);
//Call the javascrip function to show the popup
Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
}
Page code behind: Bootstrap popup class block:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal-label">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<asp:PlaceHolder ID="phRateCard" runat="server">
<%--Place Rate Card Here--%>
</asp:PlaceHolder>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Javascript:
<script type="text/javascript">
function ShowPopup() {
$("#myModal").modal("show");
}
</script>
It seems that the page reload is occurring right after the javascript is called, and before the javascript starts to run.
This is how I was able to accomplish what I needed using the following code:
Button source:
<button id="ShowRates2" runat="server" type="button" class="btn btn-link treUnderline" style="color:black" onclick="ShowRates_Click(this)">View Rates</button>
Button code behind:
[System.Web.Services.WebMethod]
public static string ShowRates(string AssetID)
{
int assetID = int.Parse(AssetID);
ListLayoutByCategory5 method = new ListLayoutByCategory5();
string html = method.BuildRateCard(assetID);
return html;
}
private string BuildRateCard(int assetID)
{
Controllers.AssetController ctlr = new Controllers.AssetController();
var rates = ctlr.GetAssetRateCardsByAssetID(assetID);
UserControl uc = new UserControl();
UserControls.RatesTable2 ratesTable = (UserControls.RatesTable2)uc.LoadControl("~/UserControls/RatesTable2.ascx");
ratesTable.BuildRateCard(rates, "", false);
//Get the HTML code of the ratesTable control (uses RenderControl(HtmlTextWriter(StringWriter(StringBuilder))) )
string html = ratesTable.HTML;
return html;
}
Page source:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal-label">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
</div>
<div id="popupBody" class="modal-body">
<asp:PlaceHolder ID="phRateCard" runat="server"></asp:PlaceHolder>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Javascript:
function ShowRates_Click(asset) {
var selectedAssetID = asset.getAttribute("assetid");
PageMethods.ShowRates(selectedAssetID, ShowRatesPopup);
}
function ShowRatesPopup(popupHTML) {
document.getElementById('popupBody').innerHTML = popupHTML;
$("#myModal").modal("show");
}
</script>
This is basically what I had to do. On the button’s ‘onclick’ event, I called the JavaScript function ‘ShowRates(this)’. This function extracted the assetid from the attributes, and then called the server-side method ‘ShowRates’ passing the assetid to it. This method created the rate card user control and return a string containing the raw html code of that user control. (This used C#’s control.RenderControl method to get the html.)
Once the JavaScript function received the html code from the server, it then called JavaScript function ‘ShowRatesPopup’ and passed the html code to it. This function inserted the html code into the ‘popupBody’ and then called the modal popup ‘#myModal’.
I am trying to retrieve text from a .txt file using jQuery (I am also using Bootstrap). I am very new to web design but I am familiar somewhat with coding. I have the following button in my HTML:
<button type="button" class="btn btn-primary-outline-btn text-btn" data-toggle="modal" data-src="test.txt" data-target="#textModal"><img class="video_icon" src="assets/icons/parchment_icon.png" alt="text"</button>
As you can see, the target of the button is a modal which loads up text like so:
<!-- Text Modal -->
<div class="modal fade" id="textModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" 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>
</div>
<div class="modal-body">
<p id="outputText">File not found.</p>
</div>
</div>
</div>
</div>
My JS file looks like this (changed following one of the answers):
$(".text-btn").on("click", textFunction);
function textFunction() {
var el = document.getElementById('test');
console.log(el.getAttribute('data-src'));
jQuery.get(el.getAttribute('data-src'), function(data) {
$( '#outputText' ).html(data.replace('n',''));
});
}
Whilst the filepath outputs to the console correctly, I am unsure how to use jQuery to utilise this so that it will input the file contents into the modal-body. Additionally, my issue is now how to make the variable assigned through getElementById correctly correspond to the button pressed. Moreover, I am not sure how to use getAttribute or attr in jQuery to obtain the data source in javascript.
This is an issue as I will have multiple buttons with multiple file sources so I would like the jQuery to retrieve from each button's respective data source. Is there a way in which I can do this...?
You have to set the full file url in data-src then use:
$('.text-btn').on('click', function() {
$.get($(this).data('src'), function(data) {
$('#outputText').html(data);
});
});
For the case of multiple buttons, you can use an onclick event on each, which will fire textFunction. Then, inside the text function, you can retrieve the correct button's data-src using jQuery's data() function:
//assuming all your relevant buttons have class `text-btn`
//call textFunction on button click
$(".text-btn").on("click", textFunction);
function textFunction() {
//inside event handler, `this` points to the button that triggered the event
jQuery.get($(this).data('src'), function(data) {
alert(data);
$( '#outputText' ).html(data.replace('n',''));
});
}
I am using Materialize framework in my rails app. I have this element that launch a modal on click:
<div data-target="modal1" class="modal-trigger" data-code="<%=code%>">lalala</div>
I want to catch the data-code in js and save it to variable. I've done something like this following the official documentation:
$('.modal-trigger').leanModal({
ready: function() {
var a = $(this).attr("data-code");
},
}
The variable "a" is undefined. How I can pass data-attr in Materialize modal? What is the best way? Thanks.
Update: I'd like to then display the value of data-code in the modal. This is the code:
<div id="modal1" class="modal bottom-sheet">
<div class="modal-content">
<p>The Code</p>
</div>
</div>
Update1: I eventually solved it with clickOn method and append the data attr to a particular div but wondering if it is possible to pass it also through modal.
Im busy making my ASP.NET web-app.
I will start with explaining the flow of my application.
User submits form
Form data gets posted to controller
Controller generates table with numbers in it using tagbuilder, returning it as mvcHtmlString.
Every number in this table is surrounded by an anchor tag (a).
When this number is clicked i want to open a modal window that shows data relevant to the number being clicked.
Clicking this number currently has an url.action as href so it jumps into my controller, passing the number to the controller.
Showing the modal is not a problem since i can just pass a data-toggle and a data-target into my anchor tag, but i want to show data that the controller returns in it's body.
What i am currently doing is in my view which contains the form i do
#{Html.RenderPartial("_Details");}
_Details contains the whole modal code:
<div class="modal fade" id="competenceModal" tabindex="-1" role="dialog" aria-labelledby="competenceModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<p>Competence details</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
My anchor tag being returned to the view containg the form:
UrlHelper url = new UrlHelper(HttpContext.Request.RequestContext);
var url2 = url.Action("LevelDetails", "Knowledge", new { level = level.Value });
var anchor = new TagBuilder("a");
anchor.Attributes.Add("href", url2);
anchor.Attributes.Add("data-target", "#competenceModal");
anchor.Attributes.Add("data-toggle", "modal");
This is correctly acessing my controller, but my big question is:
Is it possible to make the controller return data, such as a mvcHtmlString or any other content and put it in the body of my modal window? If so, what would be the best way to do so?
I would like to suggest you following things,
1. Use data-id field while building your modal link in controller. Like data-id="1".
2. In your partial view use this id to call an ajax method like "getData"
3. Return your data in json format from "getData".
4. Now bind that returned data to your form controls using jquery.
Hope this helps you !
I'm passing variables using jQuery to Bootstraps modal through span tags but having issue when running PHP within the modal. The variables all pull through normally but when I try to run mySQL statements, the span tag I store in a variable appears as nothing even though it echos fine. I have given an example of the code below:
HTML:
<a role='button' data-topicid='$number' data-toggle='modal' data-target='#modaluserinfo' class='modalsend'>
JS:
<script>
$(document).ready(function () {
$('.modalsend').click(function () {
$('span.user-topicid').text($(this).data('topicid'));
});
});
</script>
Modal:
<div class="modal fade" id="modaluserinfo" tabindex="-1" role="dialog" aria-labelledby="modaluserinfo" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Details...</h4>
</div>
<div class="modal-body" style="text-align:center; margin-top:10px;">
<?php
$numberid = "<span class='user-topicid'></span>";
echo $numberid;// THE VALUE ECHOS FINE IN THE MODAL, BUT FAILS TO LOAD IN THE MYSQL QUERY BELOW
$sqlcomment = mysql_query("SELECT * FROM comments WHERE comments.topic_id='$numberid' AND comments.emotions_id='1'");
$commentnumber = mysql_num_rows($sqlcomment);
echo $commentnumber;
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My guess is that the PHP statement is running on page load rather than when the modal is opened and the variable is sent to the span tag. Not too sure how to fix this though.
Issue has been resolved for passing multiple variables using the following method:
HTML:
$page = mysql_real_escape_string($_GET['page']);
<a role='button' data-topicid='$number' data-page='$page' data-toggle='modal' data-target='#modaluserinfo' class='modalsend'>
jQuery:
$(document).ready(function () {
$('.modalsend').click(function () {
$('span.user-topicid').load('get_number_comments.php?topicid=' + $(this).data('topicid') + '&page=' + $(this).data('page'));
});
});
Refer to #bloodyKnuckles post for any further details
PHP only runs on the server. For the Javascript or jQuery to execute a PHP script a call to the server needs to be made. There's two ways to do that GET (like a link) and POST (like a form). And there's two ways you GET and POST, one way is to reload the page, the other is an XHR object, AKA Ajax.
So, make a separate PHP file, such as...
get_number_comments.php:
<?php
// LOAD YOUR DATABASE CREDENTIALS HERE
$numberid = mysql_real_escape_string($_GET['topicid']);
$page = mysql_real_escape_string($_GET['page']);
$sqlcomment = mysql_query("SELECT * FROM comments WHERE comments.topic_id='$numberid' AND comments.emotions_id='1'");
$commentnumber = mysql_num_rows($sqlcomment);
echo $commentnumber;
?>
And change your document ready function to:
$(document).ready(function () {
$('.modalsend').click(function () {
$('span.user-topicid').load('get_number_comments.php?topicid=' + $(this).data('topicid') + '&page=' + encodeURIComponent('<?php echo page; ?>'));
});
});
The inner DIV of your modal now looks like:
<div class="modal-body" style="text-align:center; margin-top:10px;">
<span class='user-topicid'></span>
</div>
jQuery's load function makes an XHR call to the server, executing the file you enter in the first argument, get_number_comments.php in this case. So then get_number_comments.php takes the GET variable, safely escapes it, interpolates it in the query, and sends the result back to the page through the XHR object.
(By the way, since PHP mysql_* functions are apparently SOON to be null and void I urge you to convert to the PHP mysqli_* functions. Then you can also use rigorous database security measures.)