Function Calls for Dynamically Loaded Content - php

I have a PHP file that serves up some HTML populated from a MySQL database and is loaded into the DOM. This data is loaded via jQuery load() method into the #navContent divide of the HTML document. This functions as planed.
At the very-bottom of the HTML doc, I have a click function that targets the #navItem div (see the first echo line of the php file) that was dynamically loaded into the DOM but this does not fire. I know the #navItem tag ID is there because my CSS styles it correctly.
What do I have wrong? For now, I just want all the divides that were dynamically created into the #navContent div to click thru to a URL.
I am a newB and just learning jQuery so corrected code would be very helpful. Thnx
In the HTML:
<html>
<head>
<script type="text/javascript">
. . .
var ajaxLoader = '';
var dns = 'http://www.someURL';
var navContent = '/folder/my_list.php';
var bodyContent = '/folder/index.php/somestuff #content';
$(document).ready(
function() {
loadPage(dns + navContent, "navContent");
loadPage(dns + bodyContent, "bodyContent")
});
. . .
</script>
. . .
</head>
<body>
. . .
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">NAVIGATION CONTENT GETS DUMPED IN HERE</div>
</div>
</div>
. . .
</body>
<!-- ================ Functions ===================================== -->
<!-- **************************************************************** -->
<script type="text/javascript">
/* --------------- Handle Pg Loading ----------------- */
function loadPage(url, pageName) {
$("#" + pageName).load(url, function(response){
$('#navHeaderTitle').text($(response).attr('title'));
// transition("#" + pageName, "fade", false);
});
};
/* ------------- Click Handler for the Nav Items------ */
$("#navItem").click(function(e) {
e.preventDefault();
var url = 'http://www.google.com';
var pageName = 'navContent';
loadPage(url, pageName);
});
. . .
</script>
</html>
Served PHP File:
<?php
$con = mysql_connect("localhost","root","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("andaero", $con);
$result = mysql_query("SELECT * FROM some_list");
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='My Nav Title'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>

You need to initialize that click method AFTER the DOM has been appended with your custom markup. This is a perfect example of a case where OOP programming would do wonders.
You also didn't load the click method into the doc-ready...
<script type="text/javascript">
function MyConstructor()
{
this.ajaxLoader = '';
this.dns = 'http://www.someURL';
this.navContent = '/folder/my_list.php';
this.bodyContent = '/folder/index.php/somestuff #content';
this.loadPage = function( url, pageName )
{
$("#" + pageName).load(url, function(response){
$('#navHeaderTitle').text($(response).attr('title'));
});
this.toggles();
}
this.toggles = function()
{
var t = this;
$("#navItem").click(function(e) {
e.preventDefault();
var url = 'http://www.google.com';
var pageName = 'navContent';
t.loadPage(url, pageName);
});
}
/**************************************
*Init Doc-Ready/Doc-Load methods
**************************************/
this.initialize = function()
{
this.loadPage( this.dns + this.navContent, "navContent");
this.loadPage( this.dns + this.bodyContent, "bodyContent");
}
this.initialize();
}
$( document ).ready( function(){
var mc = new MyConstructor();
//now, you can go ahead and re-run any methods from the mc object :)
//mc.loadPage( arg, 'ye matey' );
});
</script>

Related

How do I write a JQuery function to populate a div from an html select?

Below is my simple Javascript function.
<html>
<head>
<script>
$(document).ready(function() {
$.get('getImage.php', function(data) {
$('#imageSelector').html("<select>" + data + "</select>");
});
});
</script>
</head>
<body>
<div id="imageSelector">
</div>
<div id="imageArea">
</div>
</body>
</html>
This is the PHP script used to get the data.
<?php
include 'connect.php';
$sql = "SELECT products_id, products_image FROM products";
$query = mysqli_query($dbc, $sql);
while ($Array = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$imageEcho .= '<option value=' . $Array['products_id'] . '>' . $Array['products_image'] . '</option>';
}
echo $imageEcho;
?>
Below is the function used to complete the URL path to the image.
function getImage(image) {
document.getElementById("imageArea").innerHTML="<img src=../eoas/images/"+image+" alt='' />";
}
Maybe I can't do it this way but I thought I would check to see if anyone knows.
You need smth like this :
$(document).ready( function(){
$.get("getImage.php",
function(data){
$( '#imageSelector' ).attr('src', data);
});
});
Use Chrome developer tools to understand what data is in ajax answer
Here is article about it
And it would be much better to use JSON answers
Example using the jsFiddle API.
$.get('getImage.php',function(data){
// data = '<option value=...>...</option><option ...>...</option>...';
$('<select>').html(data).appendTo('#imageSelector');
});

JavaScript won't show/hide div - working with PHP/MySQL

In my PHP/MySQL while loop when selecting data for an activity feed, I'm trying to show comments underneath each post so that when you click "show", it shows all of the comments.
I'm using the following code in the while loop (so this is dynamically displayed numerous times for each separate update):
<script language="javascript">
function toggle' . $act_item_id . '() {
var ele = document.getElementById("toggleText' . $act_item_id . '");
var text = document.getElementById("displayText' . $act_item_id . '");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
<a id="displayText' . $act_item_id . '" href="javascript:toggle' . $act_item_id . '();">show</a>
<div id="toggleText' . $act_item_id . '" style="display: none">' . $responseList . '</div>
' . $act_item_id . ' contains the ID of the update, making everything unique.
When you click show, the JavaScript doesn't show the div.
FYI: Content is loaded into another page via an AJAX call.
AJAX call is as follows:
function list_activity(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
document.getElementById("viewActivity").innerHTML = hr.responseText;
}
}
hr.open("GET", "listActivity.php?t=" + Math.random(), true);
hr.send();
}
I'm not entirely sure you can create and call JS functions like that. Besides, I don't see any reason to re-create the function for each section. Why don't you simply parameterize you function and change the parameter each time through?
Define function once
<script>
function toggle(act_item_id) {
var ele = document.getElementById("toggleText' . act_item_id . '");
var text = document.getElementById("displayText' . act_item_id . '");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
Then you can loop through
while (some condition) {
...
<a id="displayText' . $act_item_id . '" href="javascript:toggle('.$act_item_id.');">show</a>
<div id="toggleText' . $act_item_id . '" style="display: none">' . $responseList . '</div>
...
}

Different Jquery hover popup divs on different links

I've a php for loop which finds data from an Json object, and creates based on these information different divs and different links:
echo $remoteTownFB . " - " .
"<a href=\"#\" id=" . $remoteTownFB . "_trigger>" .$eventName . "</a></br>";
After that, I wrote a Java Script to create different divs (with different names) wich should pop up on mouseover (with a Jquery Script)
<script type="text/javascript">
var samplediv = document.createElement('div');
samplediv.id = '<?php echo $remoteTownFB . "_info" ?>';
var txt = document.createTextNode("Informationen über: <?php echo $eventName?>");
document.getElementById('pop-up').appendChild(samplediv);
document.getElementById('pop-up').appendChild(txt);
</script>
My problem is now the Jquery Script. I tried around with $.each on an Array where every Town name is in, but I couldn't figure it out.
This is my base:
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('a#trigger').hover(function(e) {
$('div#pop-up').show().;
}, function() {
$('div#pop-up').hide();
}
);
$('a#trigger').mousemove(function(e) {
$("div#pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
});
Any help or ideas?
First of you forgot to close the id-property:
echo $remoteTownFB . " - " .
"" .$eventName . "</br>";
Then, for the pop-up to work you could try:
<script type="text/javascript">
var samplediv = document.createElement('div');
samplediv.id = '<?php echo $remoteTownFB . "_info" ?>';
samplediv.style.display = 'none';
var txt = document.createTextNode("Informationen über: <?php echo $eventName?>");
samplediv.appendChild(txt);
document.getElementById('pop-up').appendChild(samplediv);
</script>
The jquery part would be:
<script type="text/javascript">
$(function() {
$('a[id$="_trigger"]').hover(
function() {
var targetSelector = '#' + this.getAttribute('id').replace('_trigger', '_info');
$('#pop-up, ' + targetSelector).show();
},
function() {
var targetSelector = '#' + this.getAttribute('id').replace('_trigger', '_info');
$('#pop-up, ' + targetSelector).hide();
}
);
});
</script>
I'm not really sure what you are trying to do with the mousemove call so I left that alone.

php with jquery html pop up

this is actually a part of huge project so i didnt include the css but im willing to post it here if actually necessary.
Ok i have this code
<html>
<head>
<script src="js/jquery.js"></script>
<script type="text/javascript">
var q = "0";
function rr()
{
var q = "1";
var ddxz = document.getElementById('inputbox').value;
if (ddxz === "")
{
alert ('Search box is empty, please fill before you hit the go button.');
}
else
{
$.post('search.php', { name : $('#inputbox').val()}, function(output) {
$('#searchpage').html(output).show();
});
var t=setTimeout("alertMsg()",500);
}
}
function alertMsg()
{
$('#de').hide();
$('#searchpage').show();
}
// searchbox functions ( clear & unclear )
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (q === "0"){
if (thisfield.value == "") {
thisfield.value = defaulttext;
}}
else
{
}
}
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var q = "0";
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#pxpxx').html(output).show();
});
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="images/close_pop.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
</script>
</head>
<body>
<input name="searchinput" value="search item here..." type="text" id="inputbox" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><button id="submit" onclick="rr()"></button>
<div id="searchpage"></div>
<div id="backgroundPopup"></div>
<div id="popup" class="popup_block">
<div id="pxpxx"></div>
</div>
</body>
</html>
Ok here is the php file(search.php) where the jquery function"function rr()" will pass the data from the input field(#inputbox) once the user click the button(#submit) and then the php file(search.php) will process the data and check if theres a record on the mysql that was match on the data that the jquery has pass and so if there is then the search.php will pass data back to the jquery function and then that jquery function will output the data into the specified div(#searchpage).
<?
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='http://".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
}
else
{
echo "Yay! There's an error occured upon checking your request";
}
?>
and here is the php file(tt.php) where the jquery a.poplight click function will pass the data and then as like the function of the first php file(search.php) it will look for data's match on the mysql and then pass it back to the jquery and then the jquery will output the file to the specified div(#popup) and once it was outputted to the specified div(#popup), then the div(#popup) will show like a popup box (this is absolutely a popup box actually).
<?
//session_start(); start up your PHP session!//
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE id='$name'");
while($row = mysql_fetch_array($result))
{
$ss = "<table border='0' align='left' cellpadding='3' cellspacing='1'><tr><td>";
$ss .= '<img class="ddx" src="Images/media/'.$row['name'].'" />'."</td>";
$ss .= "<td>"."<table><tr><td style='color:#666; padding-right:15px;'>Name</td><td style='color:#0068AE'>".$row['title']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Description</td> <td>".$row['description']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Link</td><td><a href='".$row['link']."'>".$row['link']."</a></td></tr>";
$ss .= "</td></tr></table>";
}
echo $ss;
mysql_close($con);
}
?>
here is the problem, the popup box(.popup_block) is not showing and so the data from the php file(tt.php) that the jquery has been outputted to that div(.popup_block) (will if ever it was successfully pass from the php file into the jquery and outputted by the jquery).
Some of my codes that rely on this is actually working and that pop up box is actually showing, just this part, its not showing and theres no data from the php file which was the jquery function should output it to that div(.popup_block)
hope someone could help, thanks in advance, anyway im open for any suggestions and recommendation.
JULIVER
First thought, the script is being called before the page is loaded. To solve this, use:
$(document).ready(function()
{
$(window).load(function()
{
//type here your jQuery
});
});
This will cause the script to wait for the whole page to load, including all content and images
if you're using ajax to exchange data into a php file. then check your ajax function if its actually receive the return data from your php file.

Correct syntax to get my Ajax function to work

The following code will not do what I hoped, that is run the Ajax function when the div ="dist" li
created by the PHP code's is clicked.
Guidance please.
<?php
// ...
$result = mysql_query($sql);
echo "<div class=\"dist\">";
echo "<ul>";
while ($row = mysql_fetch_array($result)) {
echo "<li><a href=\"devplan.php?search-n=" . $row['NAME'] .
"&" . rawurlencode($row['PLAN']) . "\"" . ">" .
$row['PLAN'] . "</a></li>";
};
echo "</ul>";
echo "</div>";
?>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
});
});
</script>
Here is a starter for ten - I've corrected some additional braces and added error handling. If you still get an error, at least you#ll be able to tell us what it is.
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I'd add a console.log(urlplan) right after the click event handler. make sure that returned value works if you manually enter
php/dpdetails.php?q=test&anotherVar=5
into the address bar.
What does console.log(urlplan) return?
Here is a sample piece of code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What</title>
</head>
<body>
<?php
$anchorList = "";
$rows = array(
array(
'NAME' => 'me1'
, 'PLAN' => 'thePlan1'
)
, array(
'NAME' => 'me2'
, 'PLAN' => 'thePlan2'
)
);
$anchorList .= "<div class=\"dist\">";
$anchorList .= "<ul>";
foreach ($rows as $row) {
$anchorList .= "<li>";
$anchorList .= createAnchorTag($row['NAME'], $row['PLAN']);
$anchorList .= "</li>";
}
$anchorList .= "</ul>";
$anchorList .= "</div>";
echo $anchorList;
function createAnchorTag($name, $plan) {
return "" . $plan . "";
}
?>
</body>
</html>
<script type="text/javascript" src="../scripts/jquery-1.4.2.modified.js"></script>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>
In your click function you need to return false in order to override the anchor tags wanting to redirect.
[EDIT]
I believe your actually looking to parse the href attribute of the anchor tag and pass it to the Ajax, right? If so use this script:
<script type="text/javascript">
$(document).ready(function() {
$('.dist a').click(function() {
var urlquery = $(this).attr('href').val();
// regex would be better than split, could create a more generic function
var urlparts = urlquery.split('&');
var urlplan = urlparts[1];
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>

Categories