Variable value not passing into mySQL statement in Bootstrap Modal - javascript

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.)

Related

I need to generate a modal popup dynamically that contains a user control when a button/link is clicked

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’.

Getting data from text file via data-src using jQuery

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',''));
});
}

How to echo id value as variable in bootstrap modal window?

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-defau­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­lt 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");

Unable to call jquery automatically

I use this javascript function to display popup passing url as arguments, but I want the form to display automatically without onclick, and its not working.
<!-- show_modal.php included in body -->
<script type="text/javascript">
function showModal(url)
{
// SHOWING AJAX PRELOADER IMAGE
jQuery('#modal_ajax .modal-body').html('<div style="text-align:center;margin-top:200px;"><img src="assets/images/preloader.gif" /></div>');
// LOADING THE AJAX MODAL
jQuery('#modal_ajax').modal('show', {backdrop: 'true'});
// SHOW AJAX RESPONSE ON REQUEST SUCCESS
$.ajax({
url: url,
success: function(response)
{
jQuery('#modal_ajax .modal-body').html(response);
}
});
}
</script>
<!-- (Ajax Modal)-->
<div class="modal fade" id="modal_ajax">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><?php echo $system_name;?></h4>
</div>
<div class="modal-body" style="height:500px; overflow:auto;">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- show_modal.php ends -->
PHP $url variable
<?php $url = "'".base_url() . "index.php?modal/popup/student_add/1'";?>
Call automatically
<script type="text/javascript">
$(document).ready(function(){
showModal(<?=$url?>);
});
</script>
When I call documentready : just displays dark background
it works with onclick
<a href="#" onclick="showModal(<?=$url?>);" > </a>
Console:
console1
console2
Where in the page is the ready call? If it was above the place where you load jQuery, ready would not be usable as $ doesn't exist yet.
If this is the case you will probably have an error message in the console along the lines of ReferenceError: $ is not defined. Moving the script tag that loads jQuery above the script block where you are trying to call it should fix it.
When the browser is parsing a page and it encounters a <script> block without a src attribute it runs the code in the block right away. If the script tag has a src attribute it downloads the code and then runs it before moving on to the next script tag. So if you call $() before you tell the browser to load jQuery, the browser doesn't know what you mean by $ because jQuery hasn't set $ to be a reference to itself yet. (There are ways to loading JavaScript in a non-synchronous manner, but you have to opt into them.)
The reason that it is working when you click a link is that the click handler does not run until you click it. This gives jQuery a moment to load so that $ is defined when it tries to call it.
Try this:
1) make sure $url is generated before its passing in showModal function, so declare $url in beginning of page
2) Remove extra single quote concatenation from $url
<?php $url = "aa"."index.php?modal/popup/student_add/1";?> //Remove extra single quote concatenation from $url
<script>
$( document ).ready(function() {
showModal('<?php echo $url; ?>'); // add single quotes here
});
function showModal(url)
{
// SHOWING AJAX PRELOADER IMAGE
jQuery('#modal_ajax .modal-body').html('<div style="text-align:center;margin-top:200px;"><img src="assets/images/preloader.gif" /></div>');
// LOADING THE AJAX MODAL
jQuery('#modal_ajax').modal('show', {backdrop: 'true'});
// SHOW AJAX RESPONSE ON REQUEST SUCCESS
$.ajax({
url: url,
success: function(response)
{
jQuery('#modal_ajax .modal-body').html(response);
}
});
}

how to load page in div onclick in yii?

I want to load a page in a certain div by using jquery function .load(), here is my code:
<a href="" onclick="return false;" id="generalinfo">
<div class="row alert alert-danger">
<h4 class="text-center">General Info</h4>
</div>
</a>
<div class="col-lg-6" id="userbody"></div>
<script>
$(document).ready(function(){
$('#generalinfo').click(function(){
$('#userbody').load('<?php echo Yii::app()->basePath."/views/users/_generalinfo.php"; ?>');
});
});
</script>
the page didn't load in the div and there are no errors appeared, so where is the problem here?
instead to execute:
$('#userbody').load('basePath."/views/users/_generalinfo.php"; ?>');
try to call:
$('#userbody').load('http://yousthost:portno/views/users/_generalinfo.php');
The jquery cannot evalutes on client side the PHP code echo Yii::app()->basePath
Try for instance to save the content of the PHP basepath server side in a javascript variable and the use it, like
$('#userbody').load(basePath + '/views/users/_generalinfo.php');
while on the server side, while building the html in the javascript section write:
var basePath = echo Yii::app()->basePath;
hope it's usefull

Categories

Resources