Unable to call jquery automatically - javascript

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

Related

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");

Bootstrap $('#myModal').modal('show') is not working

I'm not sure why but all the modal functions are not working with me.
I checked the version and the load they are fine.
I keep getting this error message:
Uncaught TypeError: $(...).modal is not a function
for the hide I already found an alternative.
instead of:
$('#myModal').modal('hide');
I used this :
$('#myModal .close').click();
And it works perfectly.
The problem now is with the show
$('#myModal').modal("show");
I also tried both
$('#myModal').modal("toggle");
And:
$('#myModal').modal();
but unfortunately none of them is working.
Here html code -when the button is clicked I will do some verification and handle a json data from the web service if it succeed then I want show my modal- everything is working except the show.
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
if there's any alternative I would like to know it.
Most common reason for such problems are
1.If you have defined the jquery library more than once.
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
The bootstrap library gets applied to the first jquery library but when you reload the jquery library, the original bootstrap load is lost(Modal function is in bootstrap).
2.Please wrap your JavaScript code inside
$(document).ready(function(){});
3.Please check if the id of the modal is same
as the one you have defined for the component(Also check for duplication's of same id ).
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
Note: Remove fade class from the div and enjoy it should be worked
This can happen for a few reasons:
You forgot to include Jquery library in the document
You included the Jquery library more than once in the document
You forgot to include bootstrap.js library in the document
The versions of your Javascript and Bootstrap does not match. Refer bootstrap documentation to make sure the versions are matching
The modal <div> is missing the modal class
The id of the modal <div> is incorrect. (eg: you wrongly prepended # in the id of the <div>)
# sign is missing in the Jquery selector
I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'),
`
<button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
$('#btnPurchaseClose').trigger('click');// for close popup
$('#btnOpenPurchase').trigger('click');`// for open popup
My root cause was that I forgot to add the # before the id name. Lame but true.
From
$('scheduleModal').modal('show');
To
$('#scheduleModal').modal('show');
For your reference, the code sequence that works for me is
<script>
function scheduleRequest() {
$('#scheduleModal').modal('show');
}
</script>
<script src="<c:url value="/resources/bootstrap/js/bootstrap.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/fastclick/fastclick.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/slimScroll/jquery.slimscroll.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/jquery.dataTables.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/dataTables.bootstrap.min.js"/>">
</script>
<script src="<c:url value="/resources/dist/js/demo.js"/>">
</script>
Use .modal({show:true}) and .modal({show:false}) instead of ('show') and ('hide') ... it seems to be bootstrap / jquery version combination dependent. Hope it helps.
the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).
I wasted two days in finding this problem.
Please,
try and check if the triggering button has attribute type="button".
Working example:
<button type="button" id="trigger" style="visibility:visible;" onclick="modal_btn_click()">Trigger Modal Click</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script >
function modal_btn_click() {
$('#myModal').modal({ show: true });
}
</script>
Try This without paramater
$('#myModal').modal();
it should be worked
are you sure that the id of the modal is "myModal"? if not then the call will not trigger it.
also - just from reading your post - you are triggering a function / validation with this button
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
and then if all is well - you want to trigger the modal. - if this is hte case - then you should remove the toggle from this button click. I presume you have an event handler tied to this click? you need the .modal("show") as a part of that function. not toggled from this button. also - is this id correct "creatNewAcount" as opposed to this spelling "createNewAccount"
<button type="button" id="creatNewAcount" class="btn btn-default" >Sign up</button>
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
the first googleapis script is not working now a days use this second scripe given by jquery
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
Please also make sure that the modal div is nested inside your <body> element.
After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.
Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using
setTimeout(() => { $('#modalID').modal('show'); }, 500);
Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it
In my case, bootstrap.css and bootstrap.js versions are mismatched.
It is working if I remove the fade class. But the background is disappeared.
I added the same version of bootstrap files. Now it is working perfectly.
Thank you #Mohammed Shareef C.
Another use case that may be the cuplrit
My problem was that I had a jquery selector that was using a variable that was not assigned immediately.
My modal had a dynamic ID
<div class="modal fade" id="{{scope.modalId}}"... >
This is in angularJS, so the valud of scope.modalID wasn't being bound until $scope.onInit
vm.$onInit = function () {
$( `#${vm.modalId}` ).on('shown.bs.modal', function(){
console.log('WORKS')
});
zzz
Make sure your script tag is closed with another script tag like below
before
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"/>
After
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ajax calls doubles every time I click a link to open a window in modal

I have a table with action column and column has button(link) to show details of that row.
Following is the code that shows the button in every row :rowid will be actual ineger number.
<a data-path="http://example/rowdetails/:rowid" class="btn btn-info btn-xs load-ajax-modal" role="button" data-toggle="modal" data-target="#dynamic-modal">
<span data-toggle="tooltip" title="Show Details">
<span class="glyphicon glyphicon-eye-open"></span>
</span>
</a>
Following is the html for dynamic modal
<!-- Modal -->
<div id="dynamic-modal" class="modal modal-wide hide fade in" tabindex="-1" 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">Row Details</h4>
</div>
<div class="modal-body">
<!--Dynamic body content appears here-->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.Modal -->
Following is the Javascript that I am using.
$(document).ajaxComplete(function () {
// when .modal-wide opened, set content-body height based on browser height; 200 is appx height of modal padding, modal title and button bar
$(".modal-wide").on("show.bs.modal", function () {
var height = $(window).height() - 200;
$(this).find(".modal-body").css("max-height", height);
});
/*Dynamic Modal window to load row details usin ajax load*/
$('.load-ajax-modal').on('click',function () {
url = $(this).data('path');
//ajax call using load function
$('.modal-body').load(url, function (result) {
$('#dynamic-modal').removeClass('hide');
});
});
});
Problem
Everything works good here when I click the button in a row, one single ajax(xhr) call is made. second time I click this time for the same url there are two ajax requests. third time I click a button there are four, fourth time eight and so on, it doubles every-time the previous number.
I saw in other posts and tried .one() .live() .die() etc but I think I could figure out where exactly use these functions (I tried these functions with $('.load-ajax-modal') and it doesn't seems to work).
Thanks,
K
Your ajaxComplete handler fires everytime any Ajax request completes and each time it adds a new function as a handler when the button is clicked. So, not so surprising that the handler function gets executed once, then twice, then four times ...
What you should do is use event delegation.
$(function onDocumentReady() {
var $modal = $('#dynamic-modal');
var $modalBody = $('.modal-body');
var $window = $(window);
$modal.on("show.bs.modal", function () {
var height = $window.height() - 200;
$(this).find(".modal-body").css("max-height", height);
});
$(document).on('click', '.load-ajax-modal', function (e) {
url = $(this).data('path');
//ajax call using load function
$modalBody.load(url, function (result) {
$modal.modal('show');
});
});
});
Couple of points to remember:
Always cache the jQuery object ( e.g. $(window) ) in a variable if you use it multiple times. This makes sure that jQuery does not need to query the DOM everytime you look for a specific DOM element.
Read up on Event Delegation . It makes sure that your event handler gets executed even when the elements are added dynamically to your page. Similar to what jQuery.live() offered but that has long been deprecated.
That's because you are appending clicks to already existing element. Quickest fix will be to off all registered actions before attaching new one: $('.load-ajax-modal').off('click').on('click',function () {... Like I said that's is just a workaround, to get rid of that problem dispose dom elements when the dialog is closed.

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

Variable value not passing into mySQL statement in Bootstrap Modal

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

Categories

Resources