Can't bind event to dynamically created element - php

I have following html structure in editstaff.php:
<div id="result" style="display:none">This is result div</div>
<form id="adres" onsubmit="return submitForm();">
<input type="hidden" name="type" value="adrs" />
<input type="submit" value="Address" /></form>
And in inline-style:
#result{
position: absolute;
border: 5px solid gray;
padding: 10px;
background: white;
width: 270px;
height: 190px;
}
What this html page do, clicking on "Address" button of "adres" form, some post data is send to another php page which shows information based on sent data on a pop-up like div (which style was display:none) fadeIn from display:none. The javascript/jquery codes for this purpose are as follows:
<script>
function submitForm(){
var data=$("#adres").serializeArray();
/* alert(data); */
data.push(
{
name:'sname',value:$("#title").val()
}
);
$.post("geteditdata.php",data,
function(data){
$("#result").html(data);
positionPopup();
$("#result").fadeIn(1000);
}
)
return false;
}
function positionPopup(){
$("#result").css({
left: ($(window).width() - $('#result').width()) / 2,
top: ($(window).width() - $('#result').width()) / 2,
position:'absolute'
});
}
$("#divclose").live('click',function(){
$("#result").fadeOut(500);
});
</script>
i.e the div in editstaff.php with fetched data will pop-up like following structure:
<div id="result">
some_value
Close
</div>
All things is going on okay upto this stage. But when I am clicking on "Close" link on pop-up div the div is not closing(fadeOut) with $("#divclose").click(function()
Why this is not happening in this case?
can anybody give a solution for me?
I am giving a demo page where you can see the problem in practical.
Please visit http://raddacentre.org/editstaff.php and
write 'Afsar' in "Search by name" field and
then press "show".
After page loads, please press "Address" button which will be at the bottom of the page.
Then a pop-up div will be shown where there will be a link named "Close".
Press that button and please check why this div is not fade in there?
As I used jquery version 1.3, I used $("#divclose").live method instead of $(selector).on method.
Any help will be appreciated.
in geteditdata.php there is only this code:
<?php
echo $_POST['sname'];
?>
<br /><br />Close Here

You are using really old jQuery 1.2.3 (it's not jq 1.3), I'm not sure if .live exist in that version. So two things:
Use new jQuery (I suggest 1.9)
Use .on instead of .live (read about it, syntax is a little bit different)
Code should look like that:
$("body").on('click', "#divclose", function(){
$("#result").fadeOut(500);
});
Instead of "body" you can use other container that exist when event is being binded.

Related

Show/Hide div onclick on its specific own anchor

I have the following HTML generated by PHP:
<input><label>anchor 139</label>
<div class="slidingDiv 139" style="display: none;">content 139</div>
anchor 140</label>
<div class="slidingDiv 140" style="display: none;">content 140</div>
<input><label>anchor 141</label>
<div class="slidingDiv 141" style="display: none;">content 141</div>
<input><label>anchor 142</label>
<div class="slidingDiv 142" style="display: none;">content 142</div>
As you can see it, the second class of anchor and div is the same for each iteration of the loop. I did like this because I am using a jquery snippet to hide/show div onclick on anchor.
<script type="text/javascript">
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
</script>
The problem of this jquery code: It doesn't take into consideration the second class I am adding (to anchor and div). In fact I want to hide the specific div related to his anchor, not all the divs.
Thank you for your time and help.
Try using .next which seems to do the trick for your markup.
$(this).next('.slidingDiv').slideToggle();
Full Code:
<style>
.slidingDiv { display: none; }
</style>
<script>
$(document).ready(function(){
$('.show_hide').click(function(e){
e.preventDefault(); //to prevent default action of link tag
$(this).parent().next('.slidingDiv').slideToggle();
});
});
</script>
Note: I added display:none style rule to .slidingDiv so that it is hidden when the page is rendering and not after page is rendered.
Try this using next:
$('.show_hide').click(function () {
$(this).next(".slidingDiv").slideToggle();
});
Your code:
$(".slidingDiv").slideToggle();
was sliding all the div with class slidingDiv. But we need to take into consideration the div next to the element being clicked in the current scope only using the next() method.

How to keep my text on the same line with AJAX call?

I'm trying to keep my ajax call on the same line, as detailed here: http://external.sidewaykill.com/versound/motd.php.
It won't, so what can I do?
$(document).ready(function() {
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='http://static.sidewaykill.com/img/ajax-loader2.gif' alt='loading...' />";
// load() functions
var loadUrl = "playercount.php?id=2";
$("#servercount").html(ajax_load).load(loadUrl);
});
This has nothing to do with PHP but everything to do with the absolutely awful markup of your HTML and the lack of CSS. You're going to want to wrap all of this "free-text" inside of a div or two, and then make sure you're putting the wrapper div inside of the infobar div
Sample CSS:
#infobar p{
float: left;
margin-left: 5px;
}
HTML:
<div id="infobar">
<div style="float: left;">
<p>Welcome! Our server count is:</p>
<p>1 / 10</p>
<p>We hope you enjoy your stay! We are currently playing on gm_construct.</p>
</div>
</div>
its because the ajax call returning a div element,
as this :
<div id="count"> 0 / 10</div>
Since div is a block element it will always render in a new line. there are two solutions for this
one would be to return a <span> element instead of the div
second will be if u are unable to change the return value you can fix it via css
#servercount #count { display : inline }
My suggestion is to go with the first solutions

how to show friendly message while task completes

I don't know if I've even asked the question properly, but I have a codeigniter application that some heaving lifting in the back end. While the app is busy executing commands(ajax commands), I'd like to show some sort of a status / message box / div. When the task is done, I'd like to clear the div / box.
What would I need to google to find a solution like this?
Thanks.
Edit:
This is what my jquery / ajax call looks like right now...
$('#availVLANS').click(function() {
$(this).attr("disabled","disabled");
$.ajax({
url:"<?php echo site_url('controller/methodABC/');?>",
type:'POST',
dataType:'json',
success: function(returnDataFromController) {
var htmlstring;
var submitFormHTML;
htmlstring = "<br><br><B>To reassign the port to a new vlan, click on a VlanId below and then click on the OK button</B><br><table class='table table-bordered table-striped'>";
htmlstring = htmlstring + "<th>VlanId</th><th>Name</th>";
for(i = 0; i < returnDataFromController.length; i++) {
//alert(returnDataFromController[i].VlanId);
htmlstring = htmlstring + "<tr><td><a href=>"+returnDataFromController[i].VlanId+"</a></td><td>"+ returnDataFromController[i].Name+"</td></tr>";
}
submitFormHTML = "<form method='post' accept-charset='utf-8' action='" + BASEPATH + "index.php/switches/changeportvlan/"+ $('#ip').val() +"/" + $('#hardwaremodel').val() +"/" + $('#port').val() + "'><input type='text' name='newVlanID' id='newVlanID' style='width:5em;height:1.5em'/> <button type='submit' class='btn' name='saveVlan' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button></form>";
//alert(submitFormHTML);
$('#clientajaxcontainer').html(htmlstring);
$('#newvlanform').html(submitFormHTML);
}
});
$(this).removeAttr("disabled");
});
Just use an animated GIF image in an absolutely positioned DIV overlayed on top of the whole page. Just make sure that you overlay an invisible DIV over top of the entire page to prevent clicks on interface elements behind the progress window. Something like this;
╔════════════════════╗
║ #progress-overlay ║
║ ╔════════════════╗ ║
║ ║ #progress-indicator
║ ╚════════════════╝ ║
╚════════════════════╝
The #progress-overlay is a background for the indicator and what you're going for is like a LightBox2 effect but using a progress indicator and small box in the middle of the screen.
You can get animated gif's from here;
http://preloaders.net/
Make sure that your progress/something-is-happening div sits at the top level of the document structure, so somewhere at the top of the body, before any of your other container DIV's. This is done so that the #progress-overlay is rendered at the same level in the DOM as the top level element of your website. When you absolutely position the #progress-overlay, it will appear overtop of everything else on the page.
<html>
<head>
....
</head>
<body>
<div id="progress-overlay">
<div id="progress-indicator">
<img src="images/myprogress.gif" /> Please Wait...
</div>
</div><!--progress-overlay-->
<div id="website-wrapper">
.... web site, layout, content, etc...
</div>
</body>
</html>
The #progress-overlay is hidden by default and then shown overtop when needed. Something like;
#progress-overlay{
position: absolute;
width: 100%;
height: 100%;
background: #000;
opacity: 0.2;
}
#progress-indicator{
position: relative;
margin: 0 auto;
top: 40%;
width: 200px;
height: 50px;
}
Using JQuery you could easily make this appear on demand using;
$(document).ready(function(){
$('#progress-overlay').hide();
});
function showProgressIndicator()
{
$('#progress-overlay').show();
}
You can make use of onreadystatechange event:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
If you're doing it through jquery, just show a div with a message and/or a spinner.
jQuery.ajaxSetup({
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
}
});
If you're using jQuery, I propose the following solution:
The jQuery:
$(document).ready(function(){
$("#the_button").click(function(){
var url = "the_controller/the_method"
var data = {the: "data"}
//before the POST takes place, fade-in the message
$("#the_message").fadeIn();
$.post(url, data, function(r){
if(r.success){
//when the post is finished, and it was successful, fade-out the message.
$("#the_message").fadeOut();
}
else console.log("something bad happened");
}, 'json');
});
});
The HTML:
<!-- HIDE IT BY DEFAULT -->
<div id='the_message' style='display:none;'>
Please wait.
</div>
The Controller:
class The_controller extends CI_Controller{
function the_method(){
$p = $this->input->post();
the_task($p);
if(the_task_success) return json_encode(array("success" => true));
else return json_encode(array("success" => false));
}
}

How to change the backgroundPosition of a div with a onClick event from another element

How do I put this together? I'm working on this website that requires that every time that a item from the menu is clicked the background-position of two specific DIVs change and keep the selection.
Here is my attempt:
First I create a variable "p" to save on the url/address the selected page, so for example, if you are in about us you will probably see something like this on the address bar:
website.com/index.php?p=aboutus
On the menu, on the button about us I did this with a call to the function changeBG onClick:
About Us
I figured I need javascript to do the trick and here is where I'm stock.
This is the script that goes in the header:
<script type="text/javascript">
<?
// Set "p" value to HOME if previously empty.
if ($_GET['p']=='') $_GET['p']='home';
?>
function changeBg(pvalue) {
if (pvalue == '') {pvalue = '<?=$_GET['p'];?>';
}
if (pvalue=='aboutus'){
document.getElementById('this_is_the_first_to_be_changed').style.backgroundPosition=0 20px;
document.getElementById('this_is_the_other_to_be_changed').style.backgroundPosition=0 80px;
if (pvalue=='contactus'){
document.getElementById('this_is_the_first_to_be_changed').style.backgroundPosition=0 10px;
document.getElementById('this_is_the_other_to_be_changed').style.backgroundPosition=0 100px;
}
}
</script>
This is what goes on the body:
<div id="left_menu">
About Us
Contact Us
</div>
<div id="this_is_the_first_to_be_changed">
</div>
<div id="this_is_the_other_to_be_changed">
</div>
Can anyone spot why this doesn't work?
Try it using quotes:
style.backgroundPosition="0 20px";
UPDATED
Also, what about this line:
pvalue = '';
you are setting pvalue='=aboutus'
UPDATED
The script element is incorrect:
<script type="java/text">
right is:
<script type="text/javascript">
In addition use firebug or chrome to see the JS generated in the page.

Dynamic Sliding Panel Using JQuery, based on values from a mySQL database

I am in the process of developing an academic toolkit for my university. The problem statement is, the user will be given a list of courses. When one clicks on that particular name of the course, he should get a dynamic slide panel showing the course objective and other details of that course. All these values will be present in a mySQL database. The slide panel is a must requirement here. So please help me how to get the data dynamically in the slide panel from the mySQL database. Thanks in advance... :)
http://api.jquery.com/jQuery.ajax/'>jQuery's $.ajax is your friend!
Something like the following should work (it is untested and not optimized). Hopefully it will lead you in the right direction. You should also add a loading message, error handling, and data caching.
<style>
.course{
border:solid 1px #000;
margin-bottom:10px;
}
.title{
display:block;
border-bottom:solid 1px #000;
background:#eee;
font-weight:bold;
}
.details{
display:none;
}
</style>
<div class='course'>
<a class='title' href='/classDetails.php?classID=54321'>Composition 101</a>
<div class='details'></div>
</div>
<div class='course'>
<a class='title' href='/classDetails.php?classID=54322'>Composition 201</a>
<div class='details'></div>
</div>
<div class='course'>
<a class='title' href='/classDetails.php?classID=54323'>Composition 301</a>
<div class='details'></div>
</div>
<script>
$(function(){
$(".course").each(function(){
var self = $(this);
$(".title",self).click(function(){
$.ajax({
"url":this.href,
"success":function(data){
// extract the content you need from the HTML page.
var content= $(data).find("#content").html()
// insert into the details div and then show it.
self.find(".details").html(content).slideDown(1000);
}
});
// prevent default action...
return false;
});
});
});
</script>
Also note that there are some abstractions of $.ajax to make calls like this easier (such as $("#myElement").load(url), $.post and $.get). You can find more information about these methods at http://api.jquery.com/category/ajax/

Categories