I have a group of Images in a webpage with each one has it's own ID, all of the ID's saved in a php array. I want to write a script where it take the ID from the php array and pass it to the client side and repeat a certain jquery function for each image. Here what I did:
<script>
<? php for ($i = 0; $i < $counterPostID; $i++) {
$str = "#post".$arrID[$i]; ?>
var myvar = <? php echo json_encode($str); ?> ;
var myvar2 = myvar + " " + "#textcaption";
//functions to be repeated for each image
jQuery(myvar).mouseover(function() {
jQuery(myvar2).slideDown("slow");
}).mouseout(function() {
jQuery(myvar2).slideUp("slow");
});
<? php } ?>
</script>
The code work fine but only for the last occurrence in the loop, I want the jQuery code to be repeated for all the images. How can I do that?
Assuming $counterPostID is an array with all the ID's, you can just implode it to a selector
var selector = '<?php echo "#post" . implode(", #post", $counterPostID); ?>';
// should output something like -> '#postid1, #postid2, #postid3' ... etc
$(selector).on('mouseenter mouseleave', function() {
$('.textcaption', this).slideToggle('slow'); // use a class, not the same ID
});
This isn't working because you're overwriting your vars with each loop. You could output the entire array to javascript and loop through it client-side, but you don't have to. I would recommend giving your posts a class, and giving your #textcaption elements a class, since ids must be unique, and targeting the classes:
jQuery('.post').mouseover(function () {
jQuery(this).find('.textcaption').slideDown("slow");
}).mouseout(function () {
jQuery(this).find('.textcaption').slideUp("slow");
});
You're using the SAME ID over and over:
#post1 #textcaption
#post2 #textcaption
^^^^^^^^^^^^--- here
etc..
IDs can occur only ONCE in a DOM document. Since an ID must be unique, document.getElementById() (which is what jquery is using internally, basically) will only ever return a single DOM element, never a list. That means the FIRST id found is what will be returned/processed.
Plus, your code will generate highly repetitive JS. Why not simply pass your IDs as an array to JS, then loop on that array? e.g.
<script>
var IDs = <?php echo json_encode($arrID); ?>;
$.each(IDs, function(idx, valu) {
... do your mouseover/mouseout stuff here ..
});
</script>
Related
I have 5 PHP variables, $menu1 to $menu5, that each evaluate to a keyword. I'm trying to populate these 5 PHP variables in JavaScript, and display them. The below code doesn't work. What is wrong with my processing of the PHP variables?
var menu_populator = "";
for (var x = 1; x <= count; x++) {
menu_populator += '<li><a class="myclass" href="#link">' + '<?php echo $menu' + x + '?>' + '</a></li>';
}
$('#nav_menu').html(menu_populator);
Depending on how you are getting the menu data server-side you can try both methods below. One is for set $menu variables but if you are getting data from a database or the $menu variable are created within a loop you might find the second method better.
Method one- PasteBin
Echo your php variables into a javascript array.
var myarray=["<?php echo $menu1;?>","<?php echo $menu2;?>","<?php echo $menu3;?>","<?php echo $menu4;?>","<?php echo $menu5;?>"];
Method Two- PasteBin
Create this array server-side, this will be better if you are creating the current $menu variable in a loop, with this you can just use array_push() to push the values into the array.
<?php
// PHP Array
$menu = array('Home', 'Gallery', 'About');
// How to push new item into array
array_push($menu, 'Contact');
?>
Then just simply echo this array into your javascript myarray variable.
var myarray=<?php echo json_encode($menu);?>;
I have used the following javascript to test both methods and both seem to function just fine. I prefer the second method but I have decided to offer both as I don't know what your PHP looks like or how your $menu variables are being defined so this should cover both.
window.onload=function(){
for(var i=0; i<myarray.length; i++){
var link= document.createElement('a');
link.href="#";
link.innerHTML=myarray[i];
document.body.appendChild(link);
document.body.appendChild(document.createElement('br'));
}
}
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!
Something like this would do the trick
<?php
$menu = "menu";
echo '
<script>
var count = 10;
var menu_populator="";
for(var x=1;x<=count;x++)
{
menu_populator += \'<li><a class="myclass" href="#link">'.$menu.' \'+x+\'</a></li>\';
}
$(\'#nav_menu\').html(menu_populator);
</script>
';
?>
If I pass an hard coded numeric value from php to javascript, all works perfectly. But if i pass the numeric value from a variable, i get an error:
javascript file (gallery.js)
function goto_anchor(id)
{
var anchor = $("#anchor_" + id);
$('html,body').animate({
scrollTop: anchor.offset().top - 20
}, 1200);
}
php file
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="js/gallery.js" type="text/javascript"></script><?php
$get_cat = 4;
if (isset($get_cat)) { ?>
<script>
$(document).ready(function() {
goto_anchor(4); // this will work PERFECTLY!!!
goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
});
</script><?php
} ?>
I need to pass the $get_cat variable in my php, not the harcoded numeric value. How ??
Thanks
I have such kind of problems before, can not fill
javascriptfunction(<?php echo $phpvirable ?>)
inside javascript function that causes error; Instead , according to your code, can echo it to javascript virable first before using it;
echo '<script> var get_cat = '.$get_cat.'</script>';
into your php
<?php $get_cat = 4; ?>
surely, Your php $get_cat can be captured from such as $_REQUEST['cat'] dynamic value from form submit event towards this page. then u convert it to javascript virable to use in function.
<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?>
// javascript function read predefined javascript virable that confirm work.
// u also avoid using mixed php and javascript statements which looks messy
<script>
$(document).ready(function() {
goto_anchor(get_cat); // this will work then.
});
</script>
So the problem is as follows:
I want to dynamically echo a javascript thing with PHP. This echo needs to be (or work with) another javascript file where the echo'd value is used to call a function when the ID is clicked.
However when the page is loaded and the document.getElementById things are added (and they are correct) when the element is clicked, the console tells me that fplaying is undefined
PHP File
<?php
mysql_connect ("localhost", "root", "") or die ("We couldn't connect!");
mysql_select_db ("dr");
mysql_query ("SELECT * FROM songs");
$result = mysql_query ("SELECT * FROM songs");
while ($row=mysql_fetch_array($result)) {
$source = $row ['audiosource'];
echo "
document.getElementById('$source').onclick = fplaying
";
}
?>
JS File
$(function() {
console.log( "ready!" );
function fplaying () {
alert ("test");
}
});
I am not sure if this can be done with php and this is probably not the answer you are looking for.But long comments are not recommended so I just posted as an answer.
It is possible to do, I have done when I was new to Web Developments (With ASP.Net), but still this indicates an improper architecture. JavaScript, that you are using, is a client side script and thus should be accompanied with proper AJAX structure to do such thing. Server should only be responsible to send proper response based on request, not dictate how a page should behave on client side.
Some thing like -
var play = function(){
...//code to play
};
$.ajax({
url: ..//url to php page
type: ...
...,
success: function(data){
...//data responded by php page
play();
},
error: function(){
}
});
I used syntax for jQuery. There are other libraries too.
This is very simple. Try this.
echo " <script> ";
echo "document.getElementById('$source').onclick = fplaying ";
echo "</script>";
I don't think
document.getElementById('$source').onclick = fplaying
will find the function as fplaying is undefined.
Try:
var fplaying = function() {
alert ("test");
}
instead of
function fplaying () {
alert ("test");
}
As in the JS you are printing through PHP only sets the onclick event for an element with that ID which exists somewhere else on the page I think. So, much better way of doing this would be define a class in that clickable item
<button id='<?php echo $source; ?>' class='click-me'>Click Me</button>
Then in JS use this:
$('.click-me').on('click',function(){
alert($(this).attr('id'));
});
Let's suppose you have a collection, coming from a db query: $collection and consists of associative arrays, with a unique id
Now, you are obviously going to display these objects and ask for a user to do something with them, your fplay function. What you must do, is echo whichever parts of the items you need and somehow pass in the html the item id.
So, the php part which will construct your html would be something like:
echo "<ul>";
$id = $item['id'];
foreach ($collection as $item){
echo '<li><a onclick="return fplaying(' + $id + ')" href="#" class="btn"></li>';
}
echo "</ul>";
Then, your js function would use the id as a parameter and do whatever you need:
function fplaying (id) {
alert ("your id is " + id);
}
$source = $row ['audiosource'];
echo '<div id="'.$source['id'].'" class="sourceDiv">'.$source['name'].'</div>';
then go to your js file and add this --you don't have to do that in php
$(document).ready(function(){
$('.sourceDiv').click(function(){alert($(this).attr('id'))});
});
Obviously your declaration of fplaying() is delayed and in addition its locally defined, only.
$(function() {
console.log( "ready!" );
function fplaying () {
alert ("test");
}
});
In that code fplaying is dropped as soon as the outer function has finished. Try binding that fplaying to your window instead.
$(function() {
console.log( "ready!" );
window.fplaying = function() {
alert ("test");
};
});
To illustrate this additionally:
function a() {
function fplaying() {
alert("Hi");
}
fplaying();
}
a();
will display alert box.
function a() {
function fplaying() {
alert("Hi");
}
}
a();
fplaying();
won't show alert box for fplaying() is visible in scope of a(), only, and thus it's undefined as in your case.
function a() {
window.fplaying = function() {
alert("Hi");
};
}
a();
fplaying();
will show alert box for now fplaying() is declared as method of object window more or less serving as global scope, too.
For it's delayed using $(function() { ... }); make sure invoking code as rendered by PHP isn't running before document has loaded. But that doesn't seem to be an issue according to your spare information on context.
Okay, from what I understand of your problem:
Your php creates a html file that has an element with id="the value of $source" and you want it to play a sound on click.
If you want to create a piece of javascript like you did, you could try:
echo ""
while ($row=mysql_fetch_array($result)) {
$source = $row ['audiosource'];
echo "
document.getElementById('$source').onclick = fplaying()
";
}
echo "</script>"
That should make the browser recognize the script as javascript and execute it. Make sure this is printed to the html after the part of the page with the elements you're referring to is printed to the html. Otherwise the script might run before the relevant part of the page is loaded in the browser.
<?php
include_once("database.php");
Header("content-type: application/x-javascript");
if(isset($_GET["files"])){
$src = explode("+",$src);
for($i = 0;$i<=count($src);$i++){
echo "console.log('$src');";
echo "console.log('$src[$i]');";
$file = preg_replace('#[^a-z0-9]#','',$src[$i]);
echo "console.log('You\'ve select $file');";
}
exit();
}else{
echo "console.error('No Files were found. Please try again, make sure your request is correct')";
}
?>
I'm trying to create a dynamic JavaScript file, and the consoles are working but my iteration of the $src is not working.
EX:
$_GET["files"] ===> file1+file2+file3+file4
url looks like myfile.php?files=file1+file2+file3+file4
So basically I want to split these up into an array by seperating the + in the $_GET I'm new to PHP and I'm trying to learn this on my own but there is not clear cut documentation that I can find quickly.
ALSO
Am I do my preg_replace correctly? I want to ensure there is no malicious injection going on
UPDATE
if(isset($_GET["files"])){
$src = explode("+",$_GET["files"]);
foreach($src as $files){
$file = preg_replace('#[^a-z0-9]#','',$files);
echo "console.log('$file');";
}
exit();
}
//Direct Output:
==>You've Selected aweelemtawe
//Output should be:
==>You've Selected awc
==>You've Selected elemt
==>You've Selected awe
For the incorrect usage of explode()
The following line contains your explode() call
$src = explode("+",$src);
At this stage (using the code example you've posted above) $src will not contain any data to be explode()ed. You want to use the $_GET['files'] value as the parameter
$src = explode("+", $_GET['files']);
See the php docs on explode for more info on how it works.
For your looping/iteration
For your loop you may also want to change your loop to check for $i < count($src). If you have file1+file2+file3+file4 the array will have 4 items at index 0, 1, 2 and 3. You want that statement to read $i < 4 not $i <= 4.
However... as #TML suggested, using foreach is preferred over for when directly iterating over an array.
foreach(explode('+', $_GET['files']) as $file)
{
// work with $file here (each one will be an element of the exploded array)
}
For the sake of simplifying the example, the above is essentially equivalent to
$src = explode('+', $_GET['files']);
foreach($src as $file)
{
// work with $file here (each one will be an element of the exploded array)
}
I have functions stored in SQL table that I need to use inside JS. The problem is, that I also need to use PHP variables in these functions.
The following:
<?php
$container='11';
$title='Header';
$function_text =
<<<EOT
$(function() {
$('#container$container').parent('div').find('h3').html('$title');
});
EOT;
echo $function_text;
?>
returns correctly:
$(function() {
$('#container11').parent('div').find('h3').html('Header');
});
but this one:
<?php
$ID=1;
$container='11';
$title='Header';
$article = $cls -> Query(sprintf('SELECT * from graphs WHERE ID="%s"', $ID));
$function_text = $article[0]['function'];
echo $function_text;
?>
prints exactly the contents of SQL field, without recognising variables:
$(function() {
$('#container$container').parent('div').find('h3').html('$title');
});
How could I get the variables to be injected to echoed text?
Change the data that is stored in your database, so that it uses format placeholders instead of references to variables:
$(function() {
$('#container%s').parent('div').find('h3').html('%s');
});
Use sprintf():
$function_text = sprintf($article[0]['function'], $container, $title);