I have 3 PHP files named as,
index page
books
user
Index Page
<link href="colorbox.css" type="text/css" rel="stylesheet" media="all" />
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="jquery.colorbox.js"></script>
<script type="text/javascript">
function bookRetr(str)
{
if (str=="") {
document.getElementById("more-info").innerHTML="";
return;
}
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("more-info").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showbook.php?id="+str,true);
xmlhttp.send();
}
</script>
<script>
$(document).ready(function() {
//Examples of how to assign the ColorBox event to elements
$(".popup").colorbox({iframe:true, innerWidth:750, innerHeight:520});
});
</script>
<div id='$bookid' onClick="bookRetr(this.id)></div>
<div id='more-info'></div>
bookshow.php
$bookid = $_GET['id'];
$query = mysql_query("SELECT * FROM bookdatabase WHERE ID='{$bookid}'");
$fetch = mysql_fetch_array($query);
$user = $fetch['userID'];
echo "<a href='showuser?id=$user' class='popup'>My name is X</a>";
The book show echo part is shown in my index page when i click on the div, but when click on My name is X, it open a new page but its actually supposed to open a popup. I got the popup named as colorbox plugin.
I'm unable to figure out where exactly i'm going wrong that the popup never opens.
Instead of:
$(".popup").colorbox({iframe:true, innerWidth:750, innerHeight:520});
Try:
$('.popup').live('click', function() {
$.colorbox({href:$(this).attr('href'), open:true, iframe:true, innerWidth:750, innerHeight:520});
return false;
});
OR if it won't work:
$("body").on("click", ".popup", function() {
$.fn.colorbox({href:$(this).attr('href'), open:true, iframe:true, innerWidth:750, innerHeight:520});
return false;
});
Hope it helps a little
your problem is that you are dynamically generating the link, You will have to use jquery live to make it work. Here is the code
$(function(){
//Examples of how to assign the ColorBox event to elements
$(".popup").live("click",function(){
$.colorbox({iframe:true, innerWidth:750, innerHeight:520});
return false;
});
});
Dins
Because you need to hijack the natural execution of clicking a href link...you need to add return false , which will essentially tell the browser to not treat your href like a link
If you change your popup function like this it should work, course readd your colorbox opts after the href opt by comma separation like so
$('.popup').click(function(){
$.colorbox({href:$(this).attr('href'), iframe:true, innerWidth:750, innerHeight:520});
return false;
});
Added your opts and code cleanup
Related
I am doing a blog with PHP, AJAX, MySQL, etc. As usual, each post has its ID and inside the posts you can see the comments.
What I am trying to do is refresh the comment's div by calling the comments.php document with AJAX and putting it in the div with $('#comments').html(data);.
Doing this every 5 seconds for maintaining the comments like in real time, but the problem is that when the div does the first refreshing, the div loses the ID of the post and say that is undefined.
How can I refresh any div without losing the ID of the post?
If I call the comments.php file with the typical include(file.php) inside of the post file, I have no problem, but using this way I just can't refresh the content.
Here's the code:
post.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'support/comments.php',
success: function(data) {
$('#comments').html(data);
}
});
});
</script>
div where the result is going to be showed:
<div id="comments">
</div>
Script for refreshing the div:
<script language="Javascript" type="text/javascript">
function refreshDivs(divid, secs, url) {
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// The XMLHttpRequest object
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("your browser doesn't support ajax.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function () {
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
window.onload = function startrefresh () {
//update content on real time
refreshDivs('comments',10,'support/comments.php');
}
</script>
You can pass the post id in the URL, like so:
url: 'support/comments.php?id=<?= $post_id ?>'
Then wrap the call with a setTimeout, like so:
window.setInterval(function(){
$.ajax({
url: 'support/comments.php?id=<?= $post_id ?>',
success: function(data) {
$('#comments').html(data);
}
});
}, 5000);
And discard refreshDiv.
This is assuming that comments.php retrieves the comments, and some other code posts them.
ok guys I solved it... I am gonna leave the code here in case of somebody could has the same problem... what I did was build a hidden input and put this input to use its value like the id of the post, then I sent the value of this input to the script with #('div').val and finally I sent that value to the comments.php file, once there.... I used the value in the query sentence for doing the comparative and finally can get the comments in the right post
Here's the code
<script>
$(document).ready(function() {
window.setInterval(function(){
//Comentarios
var id = $("#idcomment").val();
$.get("support/comments.php", { idpost: id }, function(LoadPage){
$("#comment").html(LoadPage);
});
}, 5000);
});
</script>
My problems is how can I make my java script run on the elements that returned by AJAX. The javascript does not work on the that returned by AJAX. In my script it suppose to pop out a dialog box with "Hello" but its not. How can I make it works or there are another ways for this? Thanks for the advice.
The below is my code...
index.html
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#box_1").on("click", function() {
alert("Hello!");
});
changeDisplay();
});
function changeDisplay() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("text").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","ajaxHandling.php",true);
xmlhttp.send();
};
</script>
</head>
<body>
<h1>Ajax Test</h1>
<div id="text">
</div>
</body>
</html>
ajaxHandling.php
<?php
echo '<div id="box_1" class="box">Click me</div>';
?>
A common problem, you need to use the correct on() syntax for future elements by binding it to a parent of the future element that exists at the time the script runs.
$(document).on("click", "#box_1", function() {
alert("Hello!");
});
I've used document, but using the closest existing parent is better. Example:
$("#wrapper").on("click", "#box_1", function() {
alert("Hello!");
});
My short answer is that you need to bind the click event slightly differently, using jQuery.on:
$('#text').on('click', '#box_1', function() {
alert('Hello!');
});
This binds the click event dynamically to any item within the #text element (or that is added later to the #text element) that matches your #box_1 selector.
My long answer is that if you are using jQuery, you should also take advantage of its AJAX library rather than roll your own.
$.ajax({
url: '/ajaxHandling.php',
}).done(function ( data ) {
$('#text').html(data);
});
I have a simple form that that when changed includes a php file in a div. For some reason jquery will not load when placed in that included file? Can someone tell me why this doesnt work.
<select name='make' onChange='show(this.value)'>
<option value='some-file.php'>the file</option>
</select>
<div id="make">Where the file is loaded and where jquery wont work</div>
<script type="text/javascript">
function show(str)
{
if (str=="")
{
document.getElementById("make").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("make").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","include/some-file.php?q="+str,true);
xmlhttp.send();
}
</script>
Then some-file.php
$models = mysql_query("SELECT model, id FROM model where make like '%".$q."%' order by model asc") or die(mysql_error());
//Puts it into an array
$count = 1;
$max = 3;
while($model = mysql_fetch_array( $models ))
{
if($count%20==1)
echo '</ul><ul style="float:left; padding:0; margin-right:10px;" class="makesModels">';
echo "<li style='padding-right:5px; display:block;'><font color='#fe9000'>".$count.".</font> ".$model['model']." <a class='delete-model".$model['id']."'>x</a></li>";
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.1.min.js'></script>
<script type='text/javascript'>
$(docuument).ready(function() {
$(".delete-model<? echo $model['id'];?>").click(function() {
alert("delete");
});
});
</script>
$count++;
}
?>
i've had the same exact problem ...
to solve this all you need to do is edit the ajax from using normal JavaScript to $.ajax so use jQuery to handle it .. and it will work ..
$.ajax({
url: "include/some-file.php?q="+str,
type: "GET",
datatype: 'html',
success: function(e){
$('#make').html(e);
}
});
I'm not sure about it, because the code is not complete, my guess would be that on someotherphpfile that you are importing you use document.ready function which is not calling because you load the file using ajax.
scripts loaded with ajax or in general a script string injected in the DOM will not execute for security reasons
you can use eval to get it working although i must warn you that you could be opening a can of worms..
after document.getElementById("make").innerHTML=xmlhttp.responseText; add this..
var parent = document.getElementById('make');
var myScript = parent.getElementsByTagName('script');
for(var i=0,len=myScript.length; i<len; i++){
executeScrpt(myScript[i]);
}
then the execute function...
function executeScrpt(scrpt){
if(scrpt.innerHTML != ""){
eval("("+script.innerHTML+")");
} else {
if(scrpt.src != ""){
var myScrpt = document.createElement("script");
myScrpt.src = scrpt.src;
document.head.appendChild(myScrpt);
}
}
}
I am currently trying to build an Ajax / PHP grid based on a dropdown selection.
Firstly on the page I have a dropdown select box, on selection a variable is passed to a PHP page which executes a select statement, and I echo a table grid out to the page.
I have been using the library jquery / jquery.dataTables.js to make the table sortable and easy to navigate. The table / grid is outputted but sorting the columns and paging is not working can anyone help Ps. I have tried other grid libraries as well and the do not work????
Please see the code below thats being used:
<script type="text/javascript" src="/js/jquery-1.5.1.js"></script>
<script type="text/javascript" src="/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('table#example').dataTable( {
"sPaginationType": "full_numbers"
} );
} );
</script>
<script type="text/javascript">
function selMetal(str,str2){
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sql.php?m="+str+"&s="+str2,true);
xmlhttp.send();
}
</script>
Then the php script echos the table out inbetween
Thanks for you help in advance.
You need not use detect browser and make ajax call. Just use .ajax() method. You should use this code:
<script type="text/javascript">
function selMetal(str,str2){
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
$.ajax({
url: "sql.php",
data: {m:str, s:str2},
success: function(data) { $("#txtHint").html(data); },
dataType: "html"
});
}
</script>
Not sure this will solve your problem or not. Give a try :-)
I'm using Ajax in a HTML page to get a URL from a PHP file. I want to use the obtained URL to show with Colorbox.
Index.html
<html xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp=new XMLHttpRequest();
}
else // code for IE6, IE5
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) // 4- Peticion completada
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
<link media="screen" rel="stylesheet" href="colorbox.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="../colorbox/jquery.colorbox.js"></script>
<script>
$(document).ready(function(){
//Examples of how to assign the ColorBox event to elements
$("a[rel='example1']").colorbox();
$("a[rel='example2']").colorbox({transition:"fade"});
$("a[rel='example3']").colorbox({transition:"none", width:"75%", height:"75%"});
$("a[rel='example4']").colorbox({slideshow:true});
$(".example5").colorbox();
$(".example6").colorbox({iframe:true, innerWidth:425, innerHeight:344});
$(".example7").colorbox({width:"80%", height:"80%", iframe:true});
$(".example8").colorbox({width:"50%", inline:true, href:"#inline_example1"});
$(".example9").colorbox({
onOpen:function(){ alert('onOpen: colorbox is about to open'); },
onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); },
onComplete:function(){ alert('onComplete: colorbox has displayed the loaded content'); },
onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); },
onClosed:function(){ alert('onClosed: colorbox has completely closed'); }
});
//Example of preserving a JavaScript event for inline calls.
$("#click").click(function(){
$('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here.");
return false;
});
});
</script>
Livesearch.php
<?php
$variable = $_REQUEST['q'];
$response = "";
if(strcmp($variable,"taj")==0)
{
$response = "<p><a href='http://www.viajes-blog.com/wp-content/uploads/taj-mahal-agra-india.jpg' rel='example1' title=''>Taj Mahal</a></p>";
}
else
{
$response = "no picture found";
}
//output the response
echo $response;
?>
I'm able to get the URL but not able to open the image with Colorbox.
Perhaps is a CSS problem but I can't find the error.
Thanks in Advance
$.colorbox({href:Livesearch.php,innerWidth:560,innerHeight:400, open:true});
http://api.jquery.com/load/
It is more intuitive than native JS )