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.
Related
First posting here. I know inline php is not preferred but I haven't converted all my scripts to echo json_encoded arrays to work in javascript on the client side...so for now, I have inline php.
I do not know the extension of the user uploaded media because it could be a jpg,mp4,etc and upon upload it goes into a media folder with the user id as an identifier.
When my user first loads the div (and html page), the php script cycles through an array and does a fetch_assoc from sql query to the database each time; It returns the (media_id #) and prints out an li with the respective media displayed next to some other values from the query.
I only know the (media_id) and the file path name without the extension. When the page first loads, everything works great and the file_exists function returns correctly.
THE PROBLEM
When I AJAX the div and do the query again, because the user added a row to the database, the new list prints out with all info, BUT the file_exists function doesn't recognize the exact same paths as before and I don't have an img or video on the page.
I copy/pasted the exact same code from the original div and put it in a file for ajax to re-query and print the new li's.
All variables are the same and when I hard code a test filepath, it prints fine. Maybe there's a caching issue?
THE CODE
<?php
$result=$conn->query($select);
$row=$result->fetch_assoc();
?>
<li>
<?php
if ($row['count']>0) {
echo "<div class='media-container'>";
$pathname = "uploads/".$row["id"]."media1";
$testjpg=$pathname.".jpg";
$testjpeg=$pathname.".jpeg";
$testpng=$pathname.".png";
$testmp4=$pathname.".mp4";
if (file_exists($testjpg)==TRUE || file_exists($testpng)==TRUE || file_exists($testjpeg)==TRUE) {
echo '<img src="'.$pathname.'">';
}if(file_exists($testmp4)==TRUE) {
echo "<video></video>";
}
echo "</div>";
}?>
</li>
I could use some advice on how to fix this and how to print appropriate media tags on unknown media types.
THE OUTPUT
<div class='media-container'>
</div>
DEBUGGING ATTEMPTS
echoing the exact file path of a known image in an <img> tag works fine. putting echo'test'; inside the file_exists case does nothing.
--
Solution (Kind of)
So I've used html's onerror before and I found a workaround, though I'd still like to know why I was getting an error. PSA this uses JQuery but javascript works too:
My Solution
<script>
function img2video(el, src) {
$( el ).replaceWith( '<video class="videoClass"><source src="'+src+'" type="video/mp4"></video>' );
}
</script>
<body>
<img style="width:100%" onerror="img2video(this,'<?php echo$pathname;?>')" src="<?php echo$pathname;?>">
</body>
Alright, so here's the final answer I made to best fit the problem using glob:
Javascript:
function img2video(el,src,place) {
if (place=='type') {
$( el ).replaceWith( '<video controls controlsList="nodownload" disablePictureInPicture style="width:100%;object-fit:contain;" preload="auto"><source src="'+src+'" type="video/mp4"></video>');
}
}
PHP:
<?php for ( $i=1; $i <= $limit; $i++) {
$path ="[DIRECTORY]/".$row["id"]."media".$i;
$path = (!empty(glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0])) ? glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0] : false;?>
<div>
<img onerror="img2video(this,'<?php echo$path;?>','type',<?php echo$row["id"];?>,<?php echo$i;?>)" src="<?php echo$path;?>">
</div>
<?php } ?>
I don't know how to mark as duplicate, if someone could help with that. My answer uses Glob_Brace from #Akif Hussain 's response on This Question.
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 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?
If you guys check out this webpage:
http://www2.scandvision.se/oresund10/
How have they done this background fade in fade out?
When i check the source this
<img id="wrapper-background" src="images/body-background-0.jpg" alt="Background" />
and i think theres some kind of script maybe php or js, or both, that every 5 sec changes the background:
images/body-background-1.jpg
images/body-background-2.jpg
images/body-background-3.jpg
and so on..
So how did they do this? an example would be great, as i want to learn how to do that. If i was going to do something like this i think i would only manage to do a script in php that randomize everytime you refresh.
Thank you, this will expand my knowledge
I did that one time on a website, I use "Prototype JS" and "Script Aculo US" but you can easily do the same thing without these library. You can see an example here: www.envolulm.fr
I extract below and translate some comment of my code:
/* In my HTML PAGE*/
<div id="slideshow">
<p id="text1"><img src="/url/of/your/image1"/></p>
<p id="text2"><img src="/url/of/your/image1"/></p>
<p id="text3"><img src="/url/of/your/image1"/></p>
<p id="text4"><img src="/url/of/your/image1"/></p>
</div>
CSS:
#text1, #text2, #text3, #text4 {
position:absolute;
height:402px; // you can put other value...here
width:850px; // you can put other value...here
}
Javascript function
function changeimg(){
var sec = 6000; // Change each 6 secondes
var paras = $$('#slideshow p'); // Grab element "<p>" of the div with slideshow for ID
// For each element "<p>"
paras.each(function(para){
if(para.visible()){
paraFade = para; // We stock the item which will disappear
paraAppear = para.next(); // We got the next element (The one who wants to appear)
//If it's the last "p" element we come back to the first one
if(paraAppear == undefined){
paraAppear = paras[0];
}
}
});
Effect.Appear(paraAppear); // Script Aculo US animation
Effect.Fade(paraFade); // Script Aculo US animation
timer = setTimeout("changeimg()",sec); // Timer
}
Event.observe(window, 'load', function() { changeimg(); }
Hope that can help you.
They are using mootools framework. Check this out:
http://mootools.net/forge/p/slideshow
The jquery cycle plugin is a simple script to do this effect.
I think you can have the same effect if you use a jquery plugin called "jquery innerfade"
Here is a website when you can get the .js file of it, of course you need jquery to use it
Inner Fade