I was wondering if someone would be able to help or point me in a direction. I am looking to make a web application like a quiz. What I need is to be able to load dynamic content off a dynamical created button or href in this case that will link to the other content. So far it doesnt seem to be functioning in that i get a page not found every time i click the button. doesnt seem to be passing the .php through the name. I have tested this outside of the dynmaic content div and it works fine but i really need it to work inside.
What I have so far:
index.php
<body>
<div class="container_12">
<div id="content">
<!--dynamic content loads here-->
</div>
</div>
</body>
Login.php
<h1> Login Page </h1>
<p> this is a test to c if works </p>
<a href='Suitable'>Hello</a> <!--button that doesnt work-->
general.js
$(document).ready(function() {
//initial
$('#content').load('Login.php');
//Handle widget Clicks
$('div#content a').click(function() {
var page = $(this).attr('href');
$('#content').load('pages/' + page +'.php');
return false;
});
});
Suitable.php
<h1> Working </h1>
<!-- content thats not loading off button-->
you should delegate the click event for dynamically loaded elements, try the following:
$('#content').on('click', 'a', function(e) {
e.preventDefault()
var page = $(this).attr('href');
$('#content').load('pages/' + page +'.php');
});
$(document).ready(function() {
//initial
$('#content').load('Login.php', function(){
//Handle widget Clicks
$('div#content a').click(function() {
var page = $(this).attr('href');
$('#content').load('pages/' + page +'.php');
return false;
});
});
});
Explanation:
load is asynchronous. JS engine does not wait for it to complete before it goes to the next line. The result is that when your click binding executes there is no a in div#content, so the selector returns an empty array and no binding happens.
Try Live instead of click
//Handle widget Clicks
$('div#content a').live('click',function() {
var page = $(this).attr('href');
$('#content').load('pages/' + page +'.php');
return false;
});
Related
im having small image gallery that uses fancybox. So on each image there is a hover and popup effect. Below is my code
<div class="one-third column hover">
<a href="large/28crowview_ld.jpg" class="image-box">
<div class="photo">
<span class="text"><span class="anchor"></span></span>
</div>
<img src="large/28crowview_ld.jpg" height="170px" width="260px"/>
</a>
</div>
the above code works perfectly.
but im using a ajax controller that returns the above code using an echo
echo '<div class="one-third column hover">
<a href="large/28crowview_ld.jpg" class="image-box">
<div class="photo">
<span class="text"><span class="anchor"></span></span>
</div>
<img src="large/28crowview_ld.jpg" height="170px" width="260px"/>
</a>
</div>';
but when i use the echo tag the images are displayed but non of the hover effects are visible. it was very odd. and i also noticed the same issue on my social bar.
It works perfectly when i use it in a html view. But when i echo, i see the code in the source but the icons are not visible
echo '<div class="supersocialshare" data-networks="facebook,google,twitter,linkedin,pinterest" data-url="'.$share.'" data-orientation="line"></div>';
all the images are placed correctly, no js conflicts.
Below is the java script im using
<script type="text/javascript">
$(document).ready(function() {
var track_click = 0; //track user click on "load more" button, righ now it is 0 click
var total_pages = <?php echo $total_pages; ?>;
$('#results').load("<?php echo base_url() ?>fetch_pages", {'page':track_click}, function() {track_click++;}); //initial data to load
$(".load_more").click(function (e) { //user clicks on button
$(this).hide(); //hide load more button on click
$('.animation_image').show(); //show loading image
if(track_click <= total_pages) //make sure user clicks are still less than total pages
{
//post page number and load returned data into result element
$.post('<?php echo base_url() ?>fetch_pages',{'page': track_click}, function(data) {
$(".load_more").show(); //bring back load more button
$("#results").append(data); //append data received from server
//scroll page to button element
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
track_click++; //user click increment on load button
}).fail(function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //alert any HTTP error
$(".load_more").show(); //bring back load more button
$('.animation_image').hide(); //hide loading image once data is received
});
if(track_click >= total_pages-1)
{
//reached end of the page yet? disable load button
$(".load_more").attr("disabled", "disabled");
}
}
});
});
</script>
inside fetch_pages
$page_number = filter_var($this->input->post('page'), FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
$item_per_page = 5;
//get current starting point of records
$position = ($page_number * $item_per_page);
$cottages = $this->properties->getstuff($sub_location,$position, $item_per_page);
foreach ($props as $cots):
echo'<div class="container section" id="'.$cots["id"].'">
<div class="one-third column hover">
<a href="'.$cots["image_url"].'" class="image-box">
<div class="photo">
<span class="text"><span class="anchor"></span></span>
</div>
<img src="'.$cots["image_url"].'" height="170px" width="260px"/>
</a>
</div>';
endforeach;
Im building this project using codeigniter, php and jquery. Any help will be appreciated.
You seem to have some serious problems understanding the overall architecture of a web application, what is happening on the browser of your client and what is happening on the server, what php does, and so on. You should read up on that.
However, your problem is most likely related to the fact that your hover and popup effects are being accomplished by something equivalent to this:
$(".hover").on("hover",function () {
// BLAH
});
If this is the case, then any elements with class hover loaded after the event handler has been attached (that is, through ajax) will not have that event handler attached to them, a simple fix would be to attach the event handler to the container and use a delegated event handler, something like this:
$(document).on("hover",".hover",function () {
// This handler is attached to the document but applies to any .hover elements inside it
});
Another fix would be to run whatever function attaches your "fancybox" functionality to an element after the element has been loaded through ajax. Hard to get it right without some reference code but i assume it would be something like:
$.get(url, function (data) {
var elem = $(data);
$("#container").append(elem);
elem.fancybox();
});
please provide you JavaScript code, I would like to throw my cent. I bet you are using hover method instead of live hover or on hover functions
just like the following :
jQuery('#div').click(...); // this will work fine if you place your code in page not posted back from ajax request or dynamically created
jQuery('#div').live('click',...); // this will work even if the element was created dynamically or from ajax request.
jQuery "live" link
jQuery "On" link
one more thing, be careful the live function is deprecated and removed from jQuery 1.9
According to anpsmn comment i had to re initialize the complete fancybox plugin within
$(window).load(function() {
it worked perfectly..
I have very limited knowledge with scripts so I hope you guys can help me with a simple solution to a small problem that I have...
I'm using the following jquery function to refresh a div with new content when a link is clicked
<script>
$(function() {
$("#myButton").click(function() {
$("#loaddiv").fadeOut('slow').load("reload.php").fadeIn("slow");
});
});
</script>
My problem is, I need to send 2 variables to the reload.php page to use in a mysql query (I have no idea how to accomplish that), also I need to make multiple links work with this function, at the moment I have multiples links with the same id and only the first link works so I guess I must associate different ids to the function in order for this to work, how can I do that?
here's the page where i'm using this: http://www.emulegion.info/teste/games/game.php
You may want to use document ready instead of function on your first line as this will make sure the code is not executed until the full page (and all elements) have loaded.
You can then use the callback functions of the fade and load to perform actions in a timely manner.
additional variables you can add after the .php, these can then be read in your reload.php file as $var1 = $_GET['var1'];
Do make sure to sanitize these though for security.
<script type="text/javascript">
// execute when document is ready
$(document).ready(function() {
// add click handler to your button
$("#myButton").click(function() {
// fade div out
$("#loaddiv").fadeOut('slow',function(){
// load new content
$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
}); // end load content
}); // end fade div out
}); // end add click to button
}); // end document ready
</script>
For different variables you could add a HTML5 style variable to your button.
<input type="button" id="myButton" data-var1="foo" data-var2="bar" />
You can retrieve this when the button is clicked:
// add click handler to your button
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
...
load("reload.php?var1="+var1+"&var2="+var2
if you have multiple buttons/links I would use class instead of id "myButton". that way you can apply the function to all buttons with the above script. Just replace "#myButton" for ".myButton"
First, you should use .on('click', function() or .live('click', function() to resolve your one click issue.
You'll want to do something like:
<script>
$(function() {
$("#myButton").on('click', function() {
var a = 'somthing';
var b = 'something_else';
$.post('url.php', {param1: a, param2: b}, function(data) {
//data = url.php response
if(data != '') {
$("#loaddiv").fadeOut('slow').html(data).fadeIn("slow");
}
});
});
});
</script>
Then you can just put var_dump($_POST); in url.php to find out what data is being sent.
Try creating a function that would accept parameters that you want.
Like:
$(document).ready(function(){
$('.link').click(function(){
reload(p1,p2);
});
});
function reload(param1, param2){
$("#loaddiv").fadeOut('slow').load("reload.php?param1="+param1+"¶m2="+param2).fadeIn("slow");
}
But by doing the above code your reload.php should be using $GET. Also you need to use class names for your links instead of id.
<script type="text/javascript">
// execute when document is ready
**$(document).ready(function() {**
**$("#myButton").click(function() {**
**$("#loaddiv").fadeOut('slow',function(){**
**$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){**
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
});
});
});
});
</script>
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
QUESTION: What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?
MOST RECENT EDIT:
solution
<script>
$(document).ready(function(){
$('.tree li a').one("click", function() {
var currentAnchor = $('.tree li a').attr('href');
if(!currentAnchor){
var query = "page=1";
}
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
alert ("page=" + page);
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
return false;
});
});
</script>
More Specifically:
I'm using Javascript and PHP to load some external PHP pages as sections in my main template.
I'm using a switch and append() so the included files keep appending. I need every file to be able to be appended ONLY ONCE. Here is the scenario as I'd like it to happen
1) downloads link is clicked
2) downloads.php appears
3) errors link is clicked
4) errors.php appears below downloads.php
5) downloads link is clicked again
6) page just scrolls up to top of downloads.php
I need the same functionality as the example on the documentation page of .one() where every div can be clicked only once.
I also looked at Using .one() with .live() jQuery and I especially liked the approach used in the accepted answer.
Iried using boolean flag as suggested below but all it did was limit my consecutive clicks on the same link to one. So if I click one link 1 multiple times it'll show page 1.php only once but if I click on link 1, then link 2, then link 1 again it will display page 1.php, then append page 2.php and append another page 1.php.
I'm starting to think that the setInterval is wrong and I may use .one() for the whole checkAnchor() function and bind it to the <a> tags. I tried this but it's not working either :(((
core.js - using .one()
var currentAnchor = null;
//$(document).ready(checkAnchor);
//Function which chek if there are anchor changes, if there are, sends the ajax petition checkAnchor
$("a").one("click", function (){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor){
query = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
}
});
The other thing I liked as an approach is adding the names of the pages to an array and then checking that array to make sure the page wasn't displayed yet. I managed to fill up an array with the page names using .push() but I hit a dead end when looking up for a value in it. If you have an idea how that's supposed to look like that'd be very helpful as well.
core.js
///On load page
var contentLoaded;
$().ready(function(){
contentLoaded = false;
setInterval("checkAnchor()", 300);
alert (contentLoaded);
});
var currentAnchor = null;
//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor(){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor){
query = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
alert (contentLoaded);
if (!contentLoaded){
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
alert (contentLoaded);
}
contentLoaded = true;
}
}
here is my
callbacks.php
<?php
//Captures the petition and load the suitable section
switch($_GET['page']){
case "4100errors" :
include 'template/4100errors.php';
break;
case "4100downloads" :
include 'template/4100downloads.php';
break;
}
?>
And my main file
4100.php
<?php
include 'template/header.php';
include 'template/4100menu.php';
include 'template/log.php';
include 'template/links.php';
include 'template/4100breadcrumbs.php';
?>
<div class="left-widget">
<div style="display:none; position:absolute; top:-9999; z-index:-100;">
</div>
<div id="side-nav-bar" class="Mwidget">
<h3>Contents</h3>
<ul class="tree">
<li><a href="#4100downloads" class="links" >Downloads</a> </li>
<li>Error Troubleshooting</li>
</ul>
</div>
</div>
<div id="content" style="margin-top:100px; margin-left:300px;">
<?
switch ($_GET['page'])
{
case "4100downloads": include 'template/4100downloads.php'; break;
case "4100errors": include 'template/4100errors.php'; break;
}
?>
</div>
</body>
</html>
4100dowloads.php
Downloads test page
4100error.php
Errors test page
Also you can look at the test page here http://period3designs.com/phptest/1/4100.php
"What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?"
.one() and live() really have little to do with $.get. They're only for event handling.
If you intend to run the code every 50ms as you are, but want to replace the current content, then use .html() instead of .append().
$("#content").html(data);
This will overwrite the old content.
I assume you're aware of this, but just to be sure, your code is running at an interval because of this...
$().ready(function(){
setInterval("checkAnchor()", 50); // better--> setInterval(checkAnchor, 50);
});
If you only want it once on document load, then do this...
$(document).ready(checkAnchor);
Just use a boolean flag to determine if you loaded the data yet or not. Set it to false on page load, and just after the call to $.get set it to true. Then, wrap your $.get with an if (!contentLoaded) { $.get ... }.
That way you will execute the $.get only once.
BTW: $.one is used to bind an event to an element, that will execute only once and then unbind it self from it.
i am trying to put a pagination page into jquery. example.html?id=foo&get=23
i would like to pass the get= into the jquery script so that i can change the page within the div instead of sending the link to the having the user see example.html?id=foo&get=23, they should only see example.html?id=foo. the rest is done in jquery.
<script >
$(document).ready(function()
{
$("#data").load("page.php?ht=<?php print $id; ?>&p=1" );
$("#next").click(function(){
var pageNum = this.id;
$("#content").load("page.php?ht=<?php print $id; ?>&p=" + pageNum, Hide_Load());
});
});
<div id="data">
page1
</div>
Why not modify the anchor
$('#next').attr("href","example.html?id=45");
After every click on the page?
you need something like this:
$(document).ready(function(){
$("#next").click(function(){
$.post('your_script_to_get_values.php',
{ page: "1" },
function(data) {
$('#content').html(data);
});
});
});
Make sure you use a live click handler, and not just a click handler, because you are creating the #next element after the page loads.
$("#next").live('click', function(){ //etc.
Documentation for .live()
It matches the current selector now and in the future (i.e. if the elements are created dynamically).
The simplest way would be with a session variable.
I have a main page with lots of content, one piece of content is a small calendar.
For the Calendar I have a Previous month and next month link. What I want to do is switch between months without having to refresh the page.
<div id='cal_wrapper'>
<a href='main.php?month=$m&year=$y' class='selector'>Previous month</a>
<a href='main.php?month=$m&year=$y' class='selector'>Next month</a>
<?PHP
echo $calendar;
?>
</div>
Javascript is as follows:
<script type="text/javascript">
$(document).ready(function() {
$('#cal_wrapper a.selector').click(function(e){
$('#cal_wrapper').load( $(this).attr('href') );
e.preventDefault();
});
});
</script>
What is happening is when I click on either prev/next link the entire page is reloaded into the cal_wrapper div..??? I'm stuck.
Maybe try putting e.preventDefault() first, i.e.:
$('#cal_wrapper a.selector').click(function(e){
e.preventDefault();
$('#cal_wrapper').load( $(this).attr('href') );
});
If I understand your question right, I think you want $(this).attr('href') to refer to the href attribute of $('#cal_wrapper a.selector'). Instead what is happening, is that $(this), at that point, actually is referring to the $('#cal_wrapper') element, not the $("#cal_wrapper a.selector') element.
If this is correct, what you may want to do is store $('#cal_wrapper') in a temporary variable, i.e,
$('#cal_wrapper a.selector').click(function(e) {
var o = $(this);
$('#cal_wrapper').load($(o).attr('href'));
e.preventDefault();
});