PHP and jQuery function—only works once? - php

I have the following function. When I click the first time, it returns a random number, but all subsequent clicks always return the same number. How come it doesn't refresh?
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
$('#my-img').attr('src', '<?php echo $pics[array_rand($pics, 1)]; ?>');
});
});
</script>

It's because you're using PHP to generate the random number, and it can't possibly be refreshed across calls to the JS function -- it's embedded in the HTML by that point.

May be you can also use live like instead of click
$(document).ready(function(){
$('#btn-get-random-image').live("click", function () {
// your works here
}
});
also check out jquery live

As others have said, you are using PHP, which is executed once on the server and sent as raw output, so the image will not change. Try this!
Edit: modified code to make it suck less.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var myPics = <?php echo json_encode($pics); ?>;
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
var index;
do {
index = Math.floor(Math.random() * myPics.length);
} while ( typeof myPics[index] == 'undefined' );
$('#my-img')
.attr('src', myPics[index]);
});
});
</script>
This uses PHP's JSON encoder to dump your array to the javascript, then your function randomly selects an image from that array to display. The do/while loop might not be necessary, my testing shows a pretty good near-uniform distribution over thousands of iterations, but there it is nonetheless.

Your PHP is creating JS code, which gets sent to the browser once when the page is rendered. Each call to the JS function runs the function as it existed when the page was rendered.

Related

executing jquery code from php

$("#bt-potrdi").click( function(e) {
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
when i click on button this jquery code is executed and works fine. Can i execute this code without click event?
I want to execute this code from php when some data is executed successfully like for example
if ($ok) {
?>
//execude ajax code
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
<?php
}
is this possible? PHP is server side code so i didn't find any good example if this is possible
Similar to the other suggestions, but this doesn't rely on having 2 copies of the same code...
if ($ok) {
?>
<script type="text/javascript">
$(function() {
$("#bt-potrdi").trigger("click");
});
</script>
<?php
If you ever change the click event handler, this will still work. This means that you won't need to make any future changes in 2 places.
If I understand the question, you want to execute some javascript on page load if $ok is true. To do that, you should be able to do something like:
if ($ok) {
?>
<script type="text/javascript">
//execute ajax code
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
EDIT: Also, e.stopPropagation(); is not going to work because e is not defined anywhere.
What happens is when your PHP script is executed, if $ok evaluates to true, then your jquery code is included in the generated document, and is omitted if it doesn't. But at this point, there is no event, so the following line will not work.
e.stopPropagation();
However, as jdwire suggested, you can wrap your javascript in a script tag, and have it executed that way, without being triggered by an event. So... like this:
<?php
if ($ok) {
?>
<script type="text/javascript">
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
?>
I would design my code so that i could add classes and set z-indexes straight up when html is rendered, but if you want to do those with jquery, jsut wrap them in <script> and $(document).ready(function({}); so they will be executed when dom is ready.
eg.
if ($ok) {
?>
//execude ajax code
<script>
$(document).ready(function{
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
</Script>
<?php
}
edit
Okay i assumed e.stopPropagation(); is set somewhere before since it was in questions example aswell. removed it for now.
You can echo out the code in <script/> tags and it will be run as JavaScript, or with the code you have, just place it between tags and it should be fine :)
But you cannot do this "live". Only when the page is requested ONCE.
You can also do it this way to pass PHP variables over to javaScript. I think it's a lot cleaner.
$check = 1;
?>
...
<script type="text/javascript">
var check = <?= $check; ?>;
...
if (check)
{
$("#bt-potrdi").trigger("click");
}

escaping greater-than and less-than in php echo inside server-side html

I'm trying to simply echo a function back to the client browser from a server php page after a selection has been made in a jQuery autocomplete box so that the function can process as needed (client-side) with the value of the autocomplete box. The autocomplete is in the php page as follows:
mypage.php
<html>
<head>
<title>Autocomplete</title>
<link href="../../jqSuitePHP/themes/redmond/jquery-ui-1.8.2.custom.css" id="skin" rel="stylesheet" type="text/css" />
<script src="../../jqSuitePHP/js/jquery-1.6.min.js" type="text/javascript"></script>
<script src="../../jqSuitePHP/js/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script>
<script>
$(function ac_boxes() {
$("#dlr").autocomplete({
source: "dlrAutocompleteSearch.php",
minLength: 2,
search : function(){$(this).addClass('ui-autocomplete-loading');},
open : function(){$(this).removeClass('ui-autocomplete-loading');},
select: function( event, ui ) {
// Here's my attempt at calling the client side 'test' function
<?php echo '<script>window[test](ui.item.value)</script>;' ?>
}
});
});
</script>
</head>
<body>
---------
</body>
</html>
But the < and > are causing a problem. If I remove the < and >, the page processes completely (without the 'select' function of course. If I add the < and >, the page does not process.
I have tried assigning the string using the php htmlentities() as such:
<?php
$val = htmlentities('<script>window[test](ui.item.value)</script>;');
echo $val;
?>
But this doesn't seem to work either.
Is my problem stemming from the php being inside of the jQuery script? If so, what is another method of calling the php from the 'select' method of autocomplete?
Thanks in advance.
I don't think this code is doing what you think it is doing; when you load the page the PHP is executed and you end up with something like this in the source code:
<script>
...
select: function( event, ui ) {
<script>window[test](ui.item.value)</script>;
}
...
</script>
Which is not correct (you don't need script tags within script tags; as you've seen it doesn't do anything but cause problems).
If you want to execute some PHP when the selection changes, you have to make another call to the server, via AJAX, submitting a form, or whatever. Something like this might be more like what you want:
select: function(event, ui) {
// send the selected value to the server for processing
$.get("processChange.php", {value: ui.item.value});
}
See the JQuery docs on $.get() for more on that.
On the other hand, if all you're trying to do is call another client-side javascript function (test, for example) with the selected value, you don't need PHP to echo anything. This ought to do the trick:
<script>
function test(args) {
// ...
}
$("#dlr").autocomplete({
// ...
select: function(event, ui) {
test(ui.item.value);
}
}
</script>
You can use < and > just like in HTML. You can also use the replace() function to find all the < and > and replace them.

executing javascript: link + refreshing. JS + PHP

OK, so how can i make this link:
"javascript:elements.setPercentage('element1','".$value."')"
execute on my page, when the page is loaded?
you can either put it in the body tag like this:
<body onload="function(){elements.setPercentage('element1','".$value."')}"
or in your javascript file:
window.onload = function(){elements.setPercentage('element1','".$value."')};
Or in jQuery
$(document).ready(function(){elements.setPercentage('element1','".$value."')});
You need to wrap it in a function because you are sending arguments
This example binds the window.onload event handler to an anonymous function. However, with this example, you can only have one handler (but as much code within it as you want).
jQuery, for example, has a more effective method called onDOMReady that you should consider.
<head>
... other stuff
<script>
window.onload = function(){
if (typeof elements == 'object' and typeof elements.setPercentage == 'function') {
elements.setPercentage('element1','<?php echo $value; ?>');
}
}
</script>
... other stuff
</head>
If you're using native JS:
<body onload="/*whatever*/">...</body>
If you're using JQuery (better cross browser support for the following):
$(document).ready(function(){/*do whatever*/})

What is wrong with this simple jQuery slideUp and slideDown?

I want to display the image actual view when the mouse is over the thumb sized image. But when the mouse is placed over the first image it appears and then disappears, not the case with the second and following images.
It works perfectly fine in Internet Explorer, but not in Firefox or Chrome.
$file - runs displays all the files in a directory
$id_v - is a simple count on the number of files
$path1 - is the path
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#view').hide();
$('#ig<? echo $id_v; ?>').bind('mouseover', function(ev) {
$('#view').slideDown();
$("#view1").attr({ src: "<? echo $path1.'/'.$file?>" });
});
$('#ig<? echo $id_v; ?>').bind('mouseout', function(ev){
$('#view').slideUp();
});
});
</script>
Please note, my interpretation of your HTML may be completely wrong. Please post all relevant code with your questions. --help us, help you. :op
Please also note (in case you were unaware) that you can edit your question to update with relevant info.
Can't say for sure without seeing HTML, but consider the following:
$('#view').hide();
Here 'view' is an id. IDs must be unique. You can't have them assigned to more than one element.
I'm assuming each item that you want to animate is getting id='view' in your HTML, when you should be doing class='view' in HTML with the following in your javascript:
$('.view').hide()
etc...
Give that a try.
It's hard to tell (for me) without live example...
Did you try to :
preload you images (with css
technique or with preload jQuery
plugin) ?
change mouseover/mouseout by
mouseenter/mouseleave ?
Just for information, in jQuery 1.4, you could use multiple events.
So your code could be rewritten like this :
$('#ig<? echo $id_v; ?>').bind({
mouseover: function() {
$('#view').slideDown();
$("#view1").attr({ src: "<? echo $path1.'/'.$file?>" });
},
mouseout: function() {
$('#view').slideUp();
}
});
I would suggest using the hover method instead of the mouseover and mouseout:
<script language="javascript" type="text/javascript">
$(function() {
$('#view').hide();
$('#ig<? echo $id_v; ?>').bind('hover',
// over
function() {
$('#view').slideDown();
$("#view1").attr({ src: "<? echo $path1.'/'.$file?>" });
},
// out
function() {
$('#view').slideUp();
}
);
});
</script>
I would also suggest (to make your life a little easier), instead of binding new methods to each new id, just assign a class to each one of them and use
<script language="javascript" type="text/javascript">
$(function() {
$('#view').hide();
$('.some-class').hover(
// over
function() {
$('#view').slideDown();
$("#view1").attr({ src: "<? echo $path1.'/'.$file?>" });
},
// out
function() {
$('#view').slideUp();
}
);
});
</script>
There could be a lot of things.
If the image #view is fixed or is showed over the position of the thumbnail it will fire a mouseout in the thumbnail at the moment you show up.
Another thing that may cause that the #view hide instantaneously is that the element #view modifies the position of the whole document, if it is on the top or something like that.
Try to remove the mouseout bind and load the page with Internet Explorer and look how the document is modified.

javascript wont parse php html tags

php sends html strings to html via ajax wrapped in <p class="select"></p> tags, css reads class perfectly. javascript/jquery does not. javascript/jquery wont even parse <p onclick="function()"></p>. What am i doing wrong?
heres my php (sends data via ajax fine)
echo "<p class='select' onclick='populate();' >{$row['song_name']} </p>";
heres my css (works fine)
p.select{color:#fff;padding: 5px;margin:0}
p.select:hover{color:#fff;background:#f60;cursor:pointer;}
heres my javascript
method 1 jquery.
$("p .select").click(function(){
var str = $(this).val();
alert(str);
});
method 2 onclick function.
function populate()
{
alert('here')
}
neither of the two methods respond at all. Guru why is this?
$("p .select").live ( "click" , function(){
var str = $(this).text();
alert(str);
});
See
Events/live
Binds a handler to an event (like
click) for all current - and future -
matched element.
Two things:
p .select will choose <p> tags containing an element with class select. p.select selects <p class="select">.
Why not move the populate function to within the live? I suspect the jquery live (or click) removes any explicit handlers.
Try this:
$("p.select").live("click",function()
{
var str = $(this).text();
alert(str);
populate();
});
I posted a working(in Firefox) example below. I think you forgot to put the jquery method inside the onload event. Beside the other (small) bugs...
<html>
<head>
<style>
p.select{color:#fff;padding: 5px;margin:0}
p.select:hover{color:#fff;background:#f60;cursor:pointer;}
</style>
<script src="jquery-1.3.2.min(2).js" type="text/javascript"></script>
<script type="text/javascript">
function bodyOnLoad() {
//instead of "p .select" "p.select"
$("p.select").click(
function(){
//changed val() into text()
var str = $(this).text();
alert(str);
});
}
</script>
</head>
<body onload="bodyOnLoad()">
<p class='select'>Songname</p>
</body>
</html>

Categories