I have two XML sources to retrieve data from. I want to use them alternately per page load. So when someone visits the page the first source will be used, next time the visit the page the other source will be used. Here is the ajax request I am using to get one data source:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "source1.xml", //how do I alternately load two different xml data sources?
dataType: "xml",
success: function(xml) {
var counter = 0
var output = '<li>';
$(xml).find('person').each(function(){
counter++;
var image = $(this).find('image').text();
var name = $(this).find('name').text();
var title = $(this).find('title').text();
var company = $(this).find('company').text();
output = output + '<div><img src=img/' + image + '.jpg />' + '<br /><label><span>' + name + '</span><br />' + title + '<br />' + company + '</label><br /></div>';
if(counter % 3 === 0){
output = output + '</li><li>';
}
});
output = output + '</li>';
$('#update-target ul').html(output);
}
});
});
For extra info, here is how I am alternately loading 2 flash files using PHP:
if(isset($_SESSION['rotation'])){
$picker = $_SESSION['rotation'];
}else{
$picker = rand(0,1);
}
if($picker == 0){
echo '<script type="text/javascript">
var video1 = new SWFObject("somefile1.swf", "p1", "151", "590", "9", "#ffffff");
video1.addParam("wmode","transparent");
video1.write("meh");
</script>';
$_SESSION['rotation'] = ++$picker;
} else {
echo '<script type="text/javascript">
var video1 = new SWFObject("somefile2.swf", "p1", "151", "590", "9", "#ffffff");
video1.addParam("wmode","transparent");
video1.write("meh");
</script>';
$_SESSION['rotation'] = --$picker;
}
I realize I could just stick the jquery document ready code right in there where I have the js calling the flash but it does not seem like a very efficient way of handling this. What is a "best case" way to do this?
You can just use a variable to keep it short, like this:
echo '<script type="text/javascript">var xmlSource = "source1.xml";</script>';
Use that in an if caluse as well, then just reference that in your code:
url: xmlSource,
There are other ways of course, using a cookie (the cookie plugin), putting the text right in the document.ready handler, etc...whichever seems most elegant to you I suppose.
I recommend the variable from the PHP side or a cookie...both of these options allow the document.ready code to stay outside the page in an external script, and not downloaded by the user each time.
Related
I'm pulling data from a mysql db using php and echoing a json_encoded array.
Using ajax I pull in the results and set the values of various dom elements. I have a string which has some html tags eg <p></p>.
When I set the element $("#element").html(data['text']) it adds double quotes to the text and all of the html elements appear as text.
I can't seem to remove the quotes using replace. Oddly when I alert the value there are no quotes. They only appear in the html when I view the code.
What is the best way to include html with text? And how do I get jquery to render this has html and not text?
Many thanks!
PHP / MySQL
//Article by id
if(isset($_GET['do']) && $_GET['do']=='get_art') {
$content = array();
$id = clean_input($_GET['id']);
$q = "SELECT * FROM articles WHERE id = '$id'";
$r = $conn->query($q);
$row = $r->fetch_assoc();
$content['title'] = str_replace("€", '€', $row['title']);
$content['img'] = $row['img'];
$content['text'] = str_replace('€', '€', $row['text']);
$content['text'] = htmlentities($row['text']);
echo json_encode($content);
}
//end article by id
jQuery
//load article onclick
$('body').on('click', '.get_art', function (e) {
e.preventDefault();
var href = $(this).attr('href').replace('#', ' ');
$.ajax({
url: 'actions.inc.php?do=get_art&id=' + href,
dataType: 'json',
type: 'post',
success: function(data) {
var art_text = data['text'];
art_text = art_text.replace('€', '€');
$("#art_img").attr("src", "images/" + data['img']);
$("#art_title").html(data['title']);
$("#art_text").html($.parseHTML(art_text));
} //end success
});//end ajax
});
//end load
The htmlentities (php) was making a mess of things, got it working now after I console logged the output from the php file
I am writing an application in JQTouch, and am using a big red button
Red
I am using PHP to dynamically build the JQT page with multiple divs. The app is a server management console that gets data from MySQL. My idea is that I use a While loop to make a div for each server returned in the MySQL query, and each div will have a delete server button(the big red button). I have to call the dame bit of code because of the whole dynamic page generating thing. So I was wondering if there was a way I could have the onClick function that I call with the button
Red
know what div the button is in that is calling the function. There will be a button in multiple divs that call the same code, but i have to know WHAT server to delete. Any suggestions?
Here is the full source code.
<html>
<link rel="stylesheet" href="jq_touch/themes/css/jqtouch.css" title="jQTouch">
<script src="jq_touch/src/lib/zepto.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jq_touch/src/jqtouch.min.js" type="text/javascript" charset="utf-8"></script>
<!-- Uncomment the following two lines (and comment out the previous two) to use jQuery instead of Zepto. -->
<!-- <script src="../../src/lib/jquery-1.7.min.js" type="application/x-javascript" charset="utf-8"></script> -->
<!-- <script src="../../src/jqtouch-jquery.min.js" type="application/x-javascript" charset="utf-8"></script> -->
<script src="../../extensions/jqt.themeswitcher.min.js" type="application/x-javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var jQT = new $.jQTouch({
icon: 'jqtouch.png',
icon4: 'jqtouch4.png',
addGlossToIcon: false,
startupScreen: 'jqt_startup.png',
statusBar: 'black-translucent',
themeSelectionSelector: '#jqt #themes ul',
preloadImages: []
});
// Some sample Javascript functions:
$(function(){
// Show a swipe event on swipe test
$('#swipeme').swipe(function(evt, data) {
var details = !data ? '': '<strong>' + data.direction + '/' + data.deltaX +':' + data.deltaY + '</strong>!';
$(this).html('You swiped ' + details );
$(this).parent().after('<li>swiped!</li>')
});
$('#tapme').tap(function(){
$(this).parent().after('<li>tapped!</li>')
});
$('a[target="_blank"]').bind('click', function() {
if (confirm('This link opens in a new window.')) {
return true;
} else {
return false;
}
});
// Page animation callback events
$('#pageevents').
bind('pageAnimationStart', function(e, info){
$(this).find('.info').append('Started animating ' + info.direction + '… And the link ' +
'had this custom data: ' + $(this).data('referrer').data('custom') + '<br>');
}).
bind('pageAnimationEnd', function(e, info){
$(this).find('.info').append('Finished animating ' + info.direction + '.<br><br>');
});
// Page animations end with AJAX callback event, example 1 (load remote HTML only first time)
$('#callback').bind('pageAnimationEnd', function(e, info){
// Make sure the data hasn't already been loaded (we'll set 'loaded' to true a couple lines further down)
if (!$(this).data('loaded')) {
// Append a placeholder in case the remote HTML takes its sweet time making it back
// Then, overwrite the "Loading" placeholder text with the remote HTML
$(this).append($('<div>Loading</div>').load('ajax.html .info', function() {
// Set the 'loaded' var to true so we know not to reload
// the HTML next time the #callback div animation ends
$(this).parent().data('loaded', true);
}));
}
});
// Orientation callback event
$('#jqt').bind('turn', function(e, data){
$('#orient').html('Orientation: ' + data.orientation);
});
});
</script><?php
//Connect
mysql_connect("localhost", "root", "root") or die(mysql_error());
//Make and store queries
mysql_select_db("servermgr") or die(mysql_error());
$result = mysql_query("SELECT * FROM servers")
or die(mysql_error());
//Echo some constant HTML
echo'<div id="serverset">';
echo'<div class="toolbar">';
echo'<h1>Servers Home</h1> ';
echo'</div>';
echo'<ul class="rounded">';
//Begin printing out MYSQL rows (List Items)
while($row = mysql_fetch_array( $result )) {
//$row_friendlyName = $_row['friendly_name']
$friendlyName_noSpaces = str_replace(' ', '_', $row[friendly_name]);
echo'<li class="">'.$row["friendly_name"].'</li>';
}
//Close list
echo'</ul>';
echo '</div>';
//Redo all previous queries to print out the divs
mysql_select_db("servermgr") or die(mysql_error());
$result2 = mysql_query("SELECT * FROM servers")
or die(mysql_error());
while($row2 = mysql_fetch_array( $result2 )) {
$friendlyName_noSpaces2 = str_replace(' ', '_', $row2[friendly_name]);
echo '<div id="'.$friendlyName_noSpaces2.'">';
echo'<div class="toolbar">';
echo'<h1>'.$row2[friendly_name].'</h1> ';
echo 'Back';
echo'</div>';
echo'<ul class="rounded">';
echo '<li>Friendly Name: '.$row2[friendly_name].'</li>';
echo '<li>IP Address: '.$row2[ip].'</li>';
echo '<li>Server Hostname: '.$row2[hostname].'</li>';
echo '<li>MAC Address: '.$row2[MAC].'</li>';
echo'</ul>';
echo'<button href="#" class="redButton">Red</button>';
echo'</div>';
}
//END OF PHP
?>
</body>
</html>
add a data attribute to your "Big Red Button" as follows
Red
and from your handling code retrieve the data value as follows
var server = $(this).attr('data-server');
Then you can do your condition logic.
DevZer0's answer is probably what you want to go with but an alternative approach is to add a class to the containing div like
echo '<div id="'.$friendlyName_noSpaces2.'" class="server">';
Then you can do this in your callback
var server = $(this).closest(".server").attr("id");
to get the id of the containing div.
I have a comics website which loops through all images in a db and displays them as thumbnails.
The user can click on one of those images to see it in normal size on a viewComic.php template.
I'd like to allow users to press left and right arrows to navigate images.
So, my idea is:
pagination.php handles image display on correct pages (by offsetting) by looping through database result array. The user can click on a result (below) to go to that specific image on the viewcomic.php template.
'<br />IMG: <a href="./templates/viewcomic.php?id=' . $row['imgid'] . '&image=' . $imgpath.$row['imgname'] . '">
Now on viewcomic.php, I get the id and image, and display the image
$imgid = $_GET['id'];
$imgpath = $_GET['image'];
<center><img src=".<?php echo $imgpath ?>" /></center>
The user can press left and right arrows to navigate through images...
My goal was to somehow increment the image id to move to the next image, but that doesn't seem to be working...
<script type="text/javascript">
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) { //get next image
<?php
$count = 0;
$count++;
echo "<img src=" . $imageArray[$count] . "/>";
?>
}
});
});
</script>
Any ideas?
EDIT: I'm going to go through an image array passed in from pagination.php.
So, in my viewcomic.php file, I've updated my jquery script (see above).. but the jquery doesn't seem to like the embedded php, even though it's all in a php file.
Here's a picture of page source vs code:
Here is what i would do:
assuming that an imagepath is surrounded by quotes:
echo $imageArray[0]; // 'imagepath/image'
Script:
<script type="text/javascript">
var imgArray = [<?php echo implode(',',$imageArray) ?>];
// now the image array have the list of all your images.
$(document).ready(function() {
var img = document.getElementById("theImage");
imgIndex = 0;
$(document).keydown(function (e) {
if (e.which == 39) { //get next image
img.src = imgArray[imgIndex++]
}
... /* Logic to check if at the end of imageArray */ ...
});
});
</script>
The Html:
<center><img src="" id="theImage"/></center>
How about:
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) {
var nextId = $_GET['id'] + 1;
window.location = "./templates/viewcomic.php?id=" + nextId;
}
});
});
In this case your page is submit on every request, You can also handle this at client site.
Click link to see demo about rotate link using JavaScript. : Link Rotate using javascript
I think this is more down to timing than code, so really I am looking for best practice advice on how best to get a JSON response.
<script type="text/javascript">
$(window).load(function() {
$('#messages').append('<img src="images/loading.gif" alt="Currently Loading" id="loading" />');
var ideaid = <?php echo $_GET['ideaid']; ?>;
$.ajax({
url: 'sql/ajaxsql.php',
type: 'POST',
data: 'switch=commentList&ideaid=' + ideaid + '&filter=sortdate',
dataType: 'json',
success: function(result) {
var len = result.length;
var html;
console.log('length= ' + len);
$('#response').remove();
console.log(result);
for(var i = 0; i < len; i++) {
var pic = '<img src="https://graph.facebook.com/' + result[i].user_id + '/picture&type=small" align="middle" />';
var authname;
FB.api('/' + result[i].user_id + '?fields=name', function(AuthName) {
console.log(AuthName);
alert(AuthName.name);
authname = AuthName.name;
});
html = '<p>' + result[i].comment + '<br><hr>Date Added: ' + result[i].date + ' by ' + pic + ' ' + authname + '<br><hr><hr></p>';
$('#comms').append(html);
}
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
</script>
With this code, it fires off to get comments regarding a certain idea (idea_id). The comments only holds the Users ID (facebook). When all the data is back, the success then sorts the data ready to print to the screen in some order.
As part of the success, I have the date, time, FB image and name as part of the Author Info under each comment.
Date and Time, works. Image using the graph works, but the name is a bit late of the window loading, and so misses it's call, so comes back as undefined and then the Alert pops up with the name. I understand ajax is meant to do this.
Whats the best way to get round this.
Thank you in advance.
Andrew
EDIT
I have been unable to make this work, even with the suggestions below.
EDIT AGAIN Just seen bf new updated version as below. would also have worked. But I have spent a day on this one function and dare not to play.
As soon as the FB.api comes into play, I could not get the values from out side it. So I took a different approach.
Rather than ajax, I used the query from the PHP side that gets the data, including the uid and then json queried that, and bolted it onto the (mysql_fetch_array) array as follows:
$gc_result = mysql_query($gc_query);
while ($result = mysql_fetch_array($gc_result)) {
$jsonURL = "https://graph.facebook.com/" . $result['user_id'] . "/";
$json = json_decode(file_get_contents($jsonURL), true);
$result["name"] = $json['name'];
$data[] = $result;
}
echo json_encode($data);
Now I have that, I can then do the following and call it within the jQuery:
for(var i = 0; i < len; i++) {
var pic = '<img src="https://graph.facebook.com/' + result[i].user_id + '/picture?type=small" align="middle" />';
html = '<p>' + result[i].comment + '<br><hr>Date Added: ' + result[i].date + ' by ' + pic + ' ' + **result[i]['name']** + '<br><hr><hr></p>';
$('#comms').append(html);
}
This all works great, and I am a complete novice to programming jquery and using Facebook API and JSON, but even I sit back and am pretty impressed with this solution. Before I get carried away, are there any potential flaws in this, performance or security wise ???
Thanks again in Advance.
Andrew
The call to FB.api is probably asynchronous (another ajax request), so you have to move the code after it to inside the FB.api callback:
FB.api('/' + result[i].user_id + '?fields=name', function(AuthName) {
console.log(AuthName);
alert(AuthName.name);
authname = AuthName.name;
html = '<p>' + result[i].comment + '<br><hr>Date Added: ' + result[i].date + ' by ' + pic + ' ' + authname + '<br><hr><hr></p>';
$('#comms').append(html);
});
You also have a variable scope problem because of the for loop. One of the ways to fix this is to use a separate function to create the callback. Add this right after your $(window).load block, before </script>:
function createFbApiCallback(jsonResult) {
return function(AuthName) {
var authname = AuthName.name;
var pic = '<img src="https://graph.facebook.com/' + jsonResult.user_id + '/picture&type=small" align="middle" />';
var html = '<p>' + jsonResult.comment + '<br><hr>Date Added: ' + jsonResult.date + ' by ' + pic + ' ' + authname + '<br><hr><hr></p>';
$('#comms').append(html);
}
}
Then change your loop to this:
for(var i = 0; i < len; i++) {
FB.api('/' + result[i].user_id + '?fields=name', createFbApiCallback(result[i]));
}
If you have to execute code that relies on a callback function inside another callback function, execute your code inside the most inner callback function. In your case, move all that is out of the FB API callback to be inside it, so all your DOM manipulation is done only when both the AJAX response and the FB.api response has returned.
I am scraping sites, and I am doing this one at a time, and then trying to get the results to display AS I get them. I am trying to render one TR at a time, but instead, it does every single one, and then renders ALL the TRs.
Here is the call to javascript:
<body onload="getOffers(companies , {$scraped}, {$isbn13});">
Here is the JS/Jquery function:
function getOffers($company_ids, $scraped, $isbn)
{
if($scraped)
{
$.ajaxSetup({cache: false});
for(var $id in $company_ids)
{
$.ajax({
url: "../get_offer.php",
data: "id=" + $company_ids[$id] + "&isbn=" + $isbn + "&code=" + $id,
dataType: "html",
success: function(data) {
$("#results tbody:last").append(data);
}
});
}
}
else
{
return true;
}
}
And here is the PHP page:
<?php
require_once 'scrape.php';
require_once 'include.php';
$id = requestValue('id');
$isbn = requestValue('isbn');
$code = requestValue('code');
$page = curlMultiRequest(isbn10($isbn), $id);
$offer = getOffer($code, $page[$code], isbn10($isbn));
print "<tr><td>". $offer['company']."</td><td>". $offer['offer_new'] . "</td><td>" . $offer['offer_used']."</td></tr>";
?>
I tried returning the sting I am printing, but that didn't even work. How can I make it print each table row to the screen as the data is retrieved?
EDIT: so I tried adding this:
print "<tr><td>". $offer['company']."</td><td>". $offer['offer_new'] . "</td><td>" . $offer['offer_used']."</td></tr>";
ob_flush();
flush();
To the PHP and it didn't work. I don't understand, if I throw an alert, it happens on the fly for every ID, but the html rendering does not.
It may have magically fixed itself because your browser was caching some of the javascript. You should use some developer tools to manually flush the cache of resources for the host you are testing on to avoid old code being subtly used ....