I am trying to make a Content Slider for my site. I have multiple HTML files and the structure of these files is like this:
<div id="title"><h2>Title of the Slide</h2></div>
<div id="image"><img src="image.jpg" width="600" height="300" alt="image"</div>
<div id="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</div>
I have been trying to use the following script get content (but no success):
<?php
function render($position="") {
ob_start();
foreach(glob("/slides/*.html") as $fileName) {
$fname = basename( $fileName );
$curArr = file($fname);
$slides[$fname ]['title'] = $curArr[0];
$slides[$fname ]['image'] = $curArr[1];
$slides[$fname ]['content'] = $curArr[2];
foreach($slides as $key => $value){
?>
<div id="slide-title">
<?php echo $value['title'] ?>
</div>
<div id="slide-content">
<?php echo $value['content'] ?>
</div>
<div id="slide-image">
<?php echo $value['image'] ?>
</div>
<?php
}}
?>
<?php
return ob_get_clean();
}
But then I came to know about a jQuery function.... (again no success)
jQuery.noConflict();
(function($){
$(document).ready(function () {
$('#slide-title').load('slides/slide1.html #title');
$('#slide-content').load('slides/slide1.html #content');
$('#slide-image').load('slides/slide1.html #image');
});
})(jQuery);
Now My questions are.....
Am I using the right syntax.
How do I get the content from multiple files using jQuery.
Please Note : My knowledge on Programming is almost '0'. I have just started learning it.
$('#slide-title').load('slides/slide1.html #title');
$('#slide-content').load('slides/slide1.html #content');
$('#slide-title').load('slides/slide1.html #image');
This will work, but not very quickly. You are doing three separate requests to the same page. You can combine them all into one fairly easily using $.get and its callback argument:
$.get('slides/slide1.html', function(html) {
var $html = $(html);
$('#slide-title').html($html.find('#title'));
$('#slide-content').html($html.find('#content'));
$('#slide-image').html($html.find('#image'));
});
Note that I have corrected slide-title to slide-image in the last line, since I hink that's what you need.
Jquery has no intuitive knowledge of files on the remote file system. You could, however, do something like this:
$(document).ready(function () {
for(var i = 1; i < 5; i++) {
$('body').append('<div id="slide-content-'+i+'"></div>');
$('#slide-title-'+i).load('slides/slide'+i+'.html #title');
// ...and so on
}
});
This will do something akin to what you were trying to do with PHP. I don't know PHP very well but that could be a better way to go (depending on it's DOM processing abilities) since the above will create one request for each file.
Your jquery code seems to be correct. What is the output you are getting?
Here's a pointer to what you are trying to accomplish..
http://www.electrictoolbox.com/load-content-jquery-ajax-select-element/
Let me know whether this helps....
Related
I'm using code from this angular.js modal window tutorial by Jason Watmore: http://jasonwatmore.com/post/2016/07/13/angularjs-custom-modal-example-tutorial
I'm trying to implement an angular.js modal window within a php partial. Here is the code where I believe there's a problem:
<div id="screenings">
<?php
//MySQL database connection established
...
while ($row = mysqli_fetch_array($result)){
echo "<div class='img_div'>";
echo "<img class='modal_img img_screenings' ng-click=\"vm.openModal('custom-modal-1')\" src='images/".$row['image']."' >";
...
echo "</div>";
}
?>
</div>
<modal id="custom-modal-1">
<div class="modal">
<div class="modal-body">
<img id="popup_img" src="#">
</div>
</div>
<div class="modal-background"></div>
</modal>
<script>
$('.img_div').on("click", function() {
var source = ( $('.modal_img').attr("src") );
alert(source);
$('#popup_img').prop('src', this.src);
});
</script>
The First Problem
The while loop spits out a bunch of images. The script at the bottom should then grab the src of whichever image is clicked and then alert that src in a pop-up message. However, it only alerts the src of the first image in the while loop regardless of which image of the bunch is clicked. I've tested this script outside of the while loop on separate img elements with different src attributes, and it works fine outside of the echoed while loop.
The Second Problem
Within the while loop, there is an ng-click in the second echoed statement that just isn't working. In my app.js file, here is the controller code that ng-click=\"vm.openModal('custom-modal-1')\" should go to (the slashes are because of the echo statement):
app.controller('screeningsController', ['$scope', '$log', "ModalService", function($scope, $log, ModalService){
var vm = this;
vm.message = "Hello World!";
$log.log(vm.message);
vm.openModal = openModal;
vm.closeModal = closeModal;
function openModal(id){
ModalService.Open(id);
}
function closeModal(id){
ModalService.Close(id);
}
};
}]);
Right after the var vm = this; statement, I'm trying to output a message to the browser console as a test, but it's not working. Maybe my syntax is wrong?
here's a couple quick thoughts. In the first portion, I don't think you were actually capturing the correct click. I added a variable to pass into the on click function to select the one that was actually clicked.
As far as the php, sometimes its easier to toggle out of php and do a chunk of html. If you're passing a lot of html chunks you might want to consider doing output buffering.
<?php
while ($row = mysqli_fetch_array($result)){ ?>
<div class='img_div'>";
<img class="modal_img img_screenings" ng-click="vm.openModal('custom-modal-1')" src="images/<?php echo $row["image"]; ?>" />
</div>
As far as the jquery on the page:
you need to grab the actual node with the click event - the "e" is a common convention for that, but its really just a variable
$('.img_div').on("click", function(e) {
var source = $(e).attr("src"); // here you grab the actual attribute
alert(source);
$('#popup_img').attr('src', source);
});
i'm assuming you actually want to set the img src attribute in your target modal here.
My site parses a spanish dictionary and lets you search for more than one word at a time. If you look up "hola" you get the first div). Some words come up with suggestions, like "casa", instead of definitions like "hola":
And what i am looking for is this:
So, i would like to: when you click on the suggestions (like CASAR in the example I posted) to print the result in a div like HOLA. Here is the code used:
$words = array('word0','word-1');
function url_decode($string){
return urldecode(utf8_decode($string));
}
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
$cssReplace = <<<EOT
<style type="text/css">
// I changed the style
</style>
</head>
EOT;
$resultIndex = 0;
foreach($words as $word) {
if(!isset($_REQUEST[$word]))
continue;
$contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/search', $contents);
echo "<div style='
//style
", (++$resultIndex) ,"'>", $contents,
"</div>";
}
I have tried with: $contents .= '' . $word . '<br/>'; But it didn't work nor I know really where/how to use it.
Okay, I'll use jQuery for the example because it will be the easiest to get the job done specially if you are new to programming.
NOTE: I DO NOT RECOMMEND USING JQUERY -BEFORE- LEARNING JAVASCRIPT -- DO IT AT YOUR OWN RISK, BUT AT LEAST COME BACK AND LEARN JAVASCRIPT LATER
First, read up on how to download and install jquery here.
Secondly, you will want something a little like this, let's pretend this is your markup.
<div id="wrapper">
<!-- This output div will contain the output of whatever the MAIN
word being displayed is, this is where HOLA would be from your first example -->
<div id="output">
</div>
<!-- This is your suggestions box, assuming all anchor tags in here will result in
a new word being displayed in output -->
<div id="suggestions">
</div>
</div>
<!-- Le javascript -->
<script>
// Standard jQuery stuff, read about it on the jquery documentation
$(function() {
// The below line is a selector, it will select any anchor tag inside the div with 'suggestions' as identifier
$('#suggestions a').click(function(e) {
// First, stop the link going anywhere
e.preventDefault();
// Secondly, we want to replace the content from output with new content, we will use AJAX here
// which you should also read about, basically we set a php page, and send a request to it
// and display the result without refreshing your page
$.ajax({
url: 'phppage.php',
data: { word: 'casar' },
success: function(output) {
// This code here will replace the contents of the output div with the output we brought back from your php page
$('#output').html(output);
}
})
});
})
</script>
Hopefully the comments will shed some light, you need to then set up your php script which will be sent a GET request. (for example, http://some.address.com/phppage.php/?word=casar)
Then you just echo out the output from PHP
<?php
$word = $_GET['word'];
// Connect to some database, get the definitions, and store the results
$result = someDatabaseFunctionThatDoesSomething($word);
echo $result;
?>
Hope this helps, I expect you have a lot of reading to do!
I have been trying to create a random picture display animation, in the style of a slot machine wheel. The user clicks 'spin' and a gif image appears, giving the effect of a slot wheel spinning. When the wheel stops, the spinning effect gif image is replaced by a random member's picture. However, the random member's picture is not appearing. In firebug, I can see that the array is being populated correctly, and the member pictures (with correct url) are all present.
The issue seems to be that the jQuery script is not prepending the tag to the in which the image is to appear, and I cannot work out why.
The PHP to gather the information for the array is here:
$q = "SELECT id, username FROM members WHERE my_sex =:req_sex";
$stmt = $dbo->prepare($q);
$stmt->execute(array(":req_sex" => $req_sex));
while($r = $stmt->fetch()) {
$m_id = $r['id'];
$m_name = $r['username'];
$m_pic .= '"members/'.$m_id.'/minis/resized_image_'.$m_id.'_0.jpg", ';
}
$m_pic = rtrim($m_pic, ', ');
and the jQuery which I am sure is incorrect somewhere is here:
$(document).ready(function(){
images = new Array(<?php echo $m_pic; ?>);
var length = images.length;
var which = Math.round(Math.random()*(length-1));
$('<img src="'+images[which]+'" alt="" class="randomMember"/>').prependTo('div#wheel');
};
I have been playing around with this and tried various methods, and using firebug to investigate, the best I have managed to achieve is to get the following line showing in the html.
<img class="randomMember" alt="" src="" />
I cannot remember how I did this, but I think it was using document.write and not wrapping it in a function. I have only been using javascript and jQuery for a week or so, and despite a whole lot of Googling and reading up, I cannot see why this isn't working out. Thanks in advance!
EDIT: the html is as follows:
<div class="hidden_sidebox">
<div id="chat_view">
<div id="wheel">
<img src="members/0/default_pic.jpg" alt="" class="preSpin" />
<img src="images/randomChatWheel.gif" alt="" class="spinAnimation" style="top: -220px;" />
</div>
//here is where the problem jQuery script is...I think this is the correct place for it, as it will prependTo the previous div element (which I have explicitly specified anyway, just in case)
<div id="btnPanel">
<div id="chatButton">CHAT</div>
<div id="spinButton">SPIN</div>
</div>
<div id="chatSplash"></div>
</div>
</div>
and the function for the wheel spin (which works perfectly apart from the final image failing to display) is here:
$(document).ready(function() {
$("div#chatSplash").click(function () {
$("div#chatSplash").slideUp("fast");
$('img.randomMember').hide();
$('img.spinAnimation').hide();
$('div#spinButton').removeClass('ButtonDisabled');
$('div#chatButton').removeClass('ButtonDisabled');
});
$("div#spinButton").click(function () {
$("img.preSpin").hide();
$("img.spinAnimation").show();
$('div#spinButton').addClass('ButtonDisabled');
$('div#chatButton').addClass('ButtonDisabled');
setTimeout(function(){$("img.spinAnimation").hide();
$('img.randomMember').show();
$('div#spinButton').removeClass('ButtonDisabled');
$('div#chatButton').removeClass('ButtonDisabled');
}, 2500);
});
});
There is a simple error here, you're not closing parentheses. You have:
$(document).ready(function(){ . . .};
Which should be
$(document).ready(function(){ . . .});
Try this in PHP:
$pictures = array();
while($r = $stmt->fetch()) {
$pictures[] = sprintf('members/%d/minis/resized_image_%d_0.jpg', $r['id'], $r['id']);
}
and then in JS:
images = <?php json_encode($pictures); ?>;
I have this code on my page, but the link has different names and ids:
<div class="myclass">
<a href="http://www.example.com/?vstid=00575000&veranstaltung=http://www.example.com/page.html">
Example Text</a>
</div>
how can I remove and Replace it to this:
<div class="myclass">Sorry no link</div>
With PHP or Javascript? I tried it with str.replace
Thank you!
I assume you mean dynamically? You won't be able to do this with php because it is server side, and doesn't have anything to do with the HTML once its been output to the screen.
See: http://www.tizag.com/javascriptT/javascript-innerHTML.php for the javascript.
Or you could use jquery which is just better and nicer than trying to do a cross browser compatible javascript script.
$('.myclass').html('Sorry...');
If the page is still on the server before you need to make the replacement, do this:
<?php if (allowed_to_see_link()) { ?>
<div class="myclass">
<a href="http://www.example.com/? vstid=00575000&veranstaltung=http://www.example.com/page.html">
Example Text</a>
</div>
<?php } else { ?>
non-link-text
<php } ?>
and also write the named functions...
You might want to clearify what you are up to. If that is your file, then you can simply open up in an editor and remove the portions. If you want to modify HTML with PHP, you can use native DOM
$dom = new DOMDocument;
$dom->loadHTML($htmlString);
$xPath = new DOMXPath($dom);
foreach( $xPath->query('//div[#class="myclass"]/a') as $link) {
$link->parentNode->replaceChild(new DOMText('Sorry no link'), $link);
}
echo $dom->saveHTML();
The above code would replace any direct <a> element children of any <div> elements that have a class attribute of myclass with the Textnode "Sorry no link".
I am using AJAX to load content into a placeholder, the PHP code uses file_get_contents to get the page I want, then gives it back to the AJAX response which puts it into my placeholder. The problem I am having is that the content that is being grabbed is actually being altered, like html tags are being put where they didn't exist.. Here is the code:
function getPreview() {
var indexe = ajax.length;
ajax[indexe] = new sack();
var form = document.getElementById('form');
ajax[indexe].setVar("prevsub", form.ebay_preview_submit.value);
ajax[indexe].method = 'POST';
ajax[indexe].requestFile = "../admin/model/catalog/getEbay.php";
ajax[indexe].onCompletion = function(){ createPreview(indexe) };
ajax[indexe].runAJAX();
}
function createPreview(indexe) {
var obj = document.getElementById('preview_ph');
obj.innerHTML = ajax[indexe].response;
}
so everything gets put inside of this placeholder:
<div id="preview_ph" ></div>
Here is the PHP that does the grabbing:
if(isset($_POST['prevsub'])){
$template_viewer = http://localhost:8888/admin/view/template/ebay/template_viewer.php';
$file_got = file_get_contents($template_viewer);
echo $file_got;
}
And here is a snippet of what It is supposed to be vs what it is adding in there...
Supposed to be:
Sign up for Newsletter</a> </div></td>
But instead it is altered:
Sign up for Newsletter</a></td></tr>
Another, supposed to be:
bidding! </span>
</div>
</td></tr>
But gets altered to:
bidding! </span>
</div>
</td></tbody>
It alters the content 7 total times from the page its grabbing... Any explanation for this?
The page, opens up in a browser perfectly, it is seriously getting altered by AJAX or file_get_contents in some way, and I am completely baffled...
Thanks for your help!
To me, this looks like the browser is sanitizing the HTML at the time of the .innerHTML operation. That is an act of self-defense, because the HTML you output is clearly not valid, is it?
The end result would look like
<div id="preview_ph" >
Sign up for Newsletter
</a> <--- broken
</div> <--- broken
</td> <--- broken
</div>
that code would break the DOM, so the browser has to try and fix it as best as it can.
Why are you outputting those closing tags through AJAX?