executing jquery code from php - 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");
}

Related

How can I make this div element dissapear

I have this code on my website and this div appears when u successfully post a comment.
Now I want the div element disappear after 3-5 seconds. Here's my code:
echo "<div class='granted'><p>Comment posted.</p></div>";
echo "<script type=\"text/javascript\">
setTimeout(function() {
$('.granted').fadeOut('fast');
}, 3000);
</script>";
Thanks!
Your code works perfectly. I think you have missed to link the script library.
Adding this line before the PHP script does the trick.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Your code should work perfectly. You can also use the delay() function:
$('.granted').delay(3000).fadeOut('fast');
$(document).ready(function(){
setTimeout(function(){
$('.granted').hide();}, 5000);
});
It's not good practice to include HTML tags inside php codes.
<div class='granted'><p>Comment posted.</p></div>
<script>
$(function(){
setInterval(function(){
$('.granted').fadeOut(1);
},5000);
});
</script>

js counter not displaying in php

I do not understand why I am not seeing each number diaplyed in the div.
My code...
<head>
<script>
function countit(i)
{
document.getElementById('counter').innerHTML = i;
}
</script>
</head>
<body>
<div id="counter"></div>
<script>countit(1)</script>
<?php sleep(1); ?>
<script>countit(2)</script>
<?php sleep(1); ?>
<script>countit(3)</script>
</body>
I have a php script which process several records from a database and I want to display a counter
of the current recod being processed. I thought JS was the way to do that. I saw something very similiar to the code above recommended on so.
Any insight would be greatly appreciated.
PHP buffers the output and doesn't send the page until it has finished running. The sleeps do not run between execution of script elements.
Rewrite your logic to use a JavaScript setInterval instead.
Alternatively, disable or avoid output buffering in your PHP script, but note that this is likely to have implications on the ability of browsers to cache your page.
PHP is a server side language, while Javascript is client side. I'm guessing you are simply seeing 3 in you counter div. The reason is because the PHP sleep(1) is happening before the page is even rendered. You need use a setInterval in Javascript to accomplish what you are trying to do.
The problem is your php code executes on your server, while you need code to execute on the client (JavaScript) for this to work:
<script>
var idx = 1;
var doCount= function(){
if(idx >= 3) return;
countit(idx);
setTimeout(doCount,1000);
};
doCount();
</script>
remove the following:
<?php sleep(1); ?>
<script>countit(2)</script>
<?php sleep(1); ?>
<script>countit(3)</script>
Your code waits 2 seconds and the browser receives:
<head>
<script>
function countit(i)
{
document.getElementById('counter').innerHTML = i;
}
</script>
</head>
<body>
<div id="counter"></div>
<script>countit(1)</script>
<script>countit(2)</script>
<script>countit(3)</script>
</body>
that's probably not what you want.
let's try something like this:
<script>
var i = 1;
function counter()
{
if (i < 4)
{
countit(i);
i++;
window.setTimeout(counter,1000);
}
}
counter();
</script>

Can the PHP $_GET be used to get a variable in the URL using Hashchange?

Click Me
<script src="https://raw.github.com/cowboy/jquery-hashchange/v1.3/jquery.ba- hashchange.js"></script>
<script type="text/javascript">
$(window).hashchange(function () {
//
});
</script>
When Click Me is clicked the URL looks like this "www.mydomain.com/#create=1".
What I am trying to do is us the $_GET in PHP to bring down the parameter. Ex:
<?php echo $_GET['create'];?>
Using the
Click Me
works, but it reloads the page and that is what I am trying to avoid. Any help would be greatly appreciated.
PHP runs on the server. A request has to be sent to the server for PHP to know what is in the query string. You don't need to reload the whole page but you will need to send something to the server, e.g. in an AJAX request and do something with the result.
//java script code
$("#clickme").click(function(event) {
var arr = $(this).attr('href').split('#');
var arr=(arr[1]);
event.preventDefault();
$("#content").load("data.php?"+ arr);
});
//html code
<a id="clickme" href="#create=1">Click Me</a>
<div id="content"></div>
// php code
data.php
There is a new future for that:
window.history.pushState("Remember me!", "Changing the get Parameter...", "?create=1");
You can apply this to all links by using this:
$("a").click(function() {
if ($(this).attr("href").substr(0, 1) != "#") {
$("body").load($(this).attr("href"));
window.history.pushState("Remember me!", "Nothing special", $(this).attr("href"));
return false;
}
});

PHP and jQuery function—only works once?

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.

How do I run a function only when a div gets loaded?

I want to run a function only when a div gets loaded.
When I load the page, a number of files are loaded. At the end of the list, PHP echoes a div. When this one is displayed, jQuery should run a function.
I can do this with a click-event, but I want it to work automatically, without pushing a button.
This is how it works with a click:
$("#PP_end_show").live("click",function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
This is the div echoed by PHP:
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
The output is generated after an AJAX call:
<form id="PP_search_input" method="post" name="search_ID" ONSubmit="xmlhttpPost('PP_search_stream_client.php', 'PP_search_input', 'PP_thumb_output', '<img src=\'images/wait.gif\'>');return false; ">
<input name="search_string" type="text" class="PP_input" id="search_string" value="<?php echo $_POST['search_string']; ?>"/>
<button type="submit" class="PP_submit" id="search_submit"> search </button>
at the end of the generated output the specific div will be printed and should trigger the new jQuery function.
This is how I would tackle this issue, assuming I've understood it correctly in which the submission of the form PP_search_input, returns the html needed, in which then a the javascript code should be executed.
$('#PP_search_input').submit(function() {
$.ajax({
url: 'PP_search_stream_client.php',
type: 'post',
data: $(this).serialize(),
success: function(html) {
$(html).insertAfter('#whereToInsert') //change to however you want to insert the html
.find("#PP_head_bar").slideToggle("slow").end()
.find("#PP_info_file_wrap").slideUp("slow");
}
});
});
Try putting your javascript code inside the generated ajax code.
For example if your ajax is generated from the php code
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
then try smth like this
<?php
echo "<div id=\"PP_end_show\"></div>";
echo '$(function(){$("#PP_head_bar").slideToggle("slow");';
echo '$("#PP_info_file_wrap").slideUp("slow");});';
?>
You could use the livequery plugin
You would then use it as follows :
$('#PP_end_show').livequery(function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
The code in the function would execute when the element in the selector (#PP_end_show) was added to the DOM
Why not echo your javascript along with the DIV code?
You can use PHP to echo Javascript like this:
After your code:
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
Write this:
echo "<script type='text/javascript'>
$('#PP_head_bar').slideToggle('slow');
$('#PP_info_file_wrap').slideUp('slow');
";
echo "</script>";
This should work.
In your JS, wrap the code you want to execute in a function. i.e.
function showInfoBlock() {
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}
In your PHP, write out the JS needed to call that function after writing out the PP_end_show div. i.e.
<?php echo "<div id=\"PP_end_show\"></div><script>$(function() { showInfoBlock(); })();</script>"; ?>
This does what you are asking:
(function($){
var checkForEndInterval = window.setInterval(function(){
if ($('#PP_end_show').length) {
// stop interval
window.clearInterval(checkForEndInvertal);
// call your code now
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}
},200);
})(jQuery);
However this is not a good idea because its silly and what you are asking for hints you not understanding but that is why you are here. Since you already know when your AJAX is called, call it explicitly and attach a success handler to it.
$.ajax({
/* your other setup code here */
success : function(data) {
// run your code
}
});
If you were not doing AJAX as you say, I would put a script tag at the end of your output and have it call your code as the simplest approach. Even still, you could use the jQuery.load method (not event) which by default executes JavaScript from your response.
Happy coding.
keep that jquery live-click-function as it is
& run the below code in php
<?php
echo "<div id=\"PP_end_show\"></div>";
echo "$(function(){ $(\"#PP_end_show\").click(); });";
?>
$.ready(function(){
$("#wrapper").add("div").attr('id','PP_end_show');
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
<div id='wrapper'>
</div>
Bind the live event to a custom event that is triggered by the document:
$(document).trigger('echo');
$("#PP_end_show").live("echo", function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
References
jQuery API: .trigger()
JQuery API: .live()
Jason Brumwell enter right answer, also you can use the $.when function of JQuery.
http://api.jquery.com/jQuery.when/
If the action you want to perform once the desired div loads is bound to a click event, simply trigger click at the end of the ajax request something like:
$.ajax({
url:'whatever.php',
type:'post', //guessing obviously
success: function(data){
$('#PP_end_show').click(); //etc
}
});
These guys are right though, you are doing this all backwards mate
Does it have to be that exact div? It seems to me that you should just execute the function on load of the document. That way you know all your elements are loaded.
$(function()
{
// This function is executed when the DOM is ready, including that last div.
// Could be that images are still loading, but your code usually won't depend on that.
}
Try this,
if(window.isBodyLoaded){
try{
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}catch(d){
alert(d)
}
}
Use a callback function.
Its a function that will be triggered as soon as your event is handled.
so for Jquery:
$("#PP_end_show").live("click",function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}, myCallback());
function myCallback(){
//Do what ever you want to happen after
//the div creationin this function
}
And I think that should do the trick

Categories