i am using thie jquery code to poll my database:
jQuery(function($){
setInterval(function(){
$.get( 'getrows.php', function(newRowCount){
$('#rowcounter').html( newRowCount );
});
},5000); // 5000ms == 5 seconds
});
and display the results here:
<p>There are <span id='rowcounter'>xx</span> rows in the DB.</p>
but i am not sure what to put in the getrows.php file... does there need to be any html tags with an ID of rowcounter or newRowCount?
After getting the number of rows in your database, just do:
<?php echo $rowCount; //Or whatever value you want to show ?>
That's all
Looking at that code, all the PHP file needs to do is emit a number. You'd have normal data-access code like you would anywhere else, then just:
echo $someValue;
jQuery intelligently guesses the type of data returned by your php script (definable in your php request's script with ContentType).
A simple php script would return HTML/Text data, so you just have to "echo" your number in your PHP script. Then your newRowCount JS value will contain your PHP-echoed number.
You're simply requesting getrows.php and expecting a response from it.
You can do anything there, as long as you echo something. Like:
<?php
echo rand(1,10);
?>
When jQuery requests this page, PHP will generate a random number, and jQuery will append it to HTML.
Basically, you can respond anything there. jQuery doesn't care what you're responding.
Related
im curious, if the value of <p class="myclass"></p> assign by jquery using $('.myclass').text('txtvalue'); can be fetch using PHP script? example. like i want to fetch the assign value of jquery without using jquery post, ajax to pass value in PHP because im do this with only one page.
here my code:
<p class='myclass'></p>
<?php
$a = strip_tags("<p>","<p class='myclass'></p>");
echo $a;
// the result is 100; but its dismase like im printing "<p class='myclass'></p>"; i im trying to do is to get exactly the value of "<p class='myclass'></p>". because the value of that, i will use to query in mysql id.
//it is impossible to me to do this?...
?>
<script>
$('.myclass').text('100');
</script>
No, this cannot be done.
PHP runs server-side and generates your HTML, including any Javascripts with jquery in it. When it's done, Javascript gets to work, client-side. The only way to get something back into PHP is to send it to the server by posting it, ajax, or redirection.
I'm a bit of a newbie when it comes to Javascript and I am trying to find a way that I can pass a php value into a javascript/jquery function.
<script type="text/javascript">
$(document).ready(function() {
$('div#audit_admin_tabs').slideTabs({
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
tabsAnimTime: 300,
buttonsFunction:'click',
tabSaveState:true,
autoHeight:true,
urlLinking:false
});
});
</script>
I have a value call $audit_id, the value for which is from a $_GET from the previous page. I would like to add it to the audit_admin_tabs. I have tried...
div#audit_admin_tabs<? echo $audit_id; ?>
But I realise that won't work because php is server side and javascript isn't. I have also tried echoing the whole function so I can add the php value but that didn't work either.
Thanks
div#audit_admin_tabs<?php echo $_GET['audit_id']; ?>
When you want get a get parameter you make it with $_GET['yourparam']
Greetz
You have the wrong tags. It's <?php ?> ... Not <? ?> ... As Franco has mentioned, you need to use $_GET['audit_id'] (or just use $_REQUEST['audit_id'] because that will take care of getting the value from $_GET or $_POST).
To answer your doubt about javascript being client side but PHP being server side :: Yes your understanding is correct, however in this case first PHP will do its magic so the code inside will get replaced with whatever it should be and then the resulting javascript will be served to the browser. And after that browser will execute that resulting javascript.
So, in short, it should work.
Here is what I'm trying to do...
$("div").prepend("<div id='comment-number'><?php the_comment_number(); ?></div>");
Is there some way to get this to work?
<div class="gallery-item">
<div class="comment-number"><!--?php echo htmlspecialchars(the_comment_number()); ?--></div>
</span>
<span class="gallery-icon">
<img src="http://mysite.com/test/wp-content/uploads/2011/06/fff-150x150.gif">
</span>
</div>
PHP is executed on the server, but JavaScript code (jQuery) is executed later, in the web browser. For that reason, PHP can produce JavaScript code, but JavaScript can't produce PHP code.
The <!--? in your posted output shows that something is filtering our your PHP code. So the problem isn't your PHP code, it's that you're not actually executing PHP code. If it's a .js file, PHP almost certainly can't be included.
If PHP were being evaluated (ex. if this were in a <script> tag in a .php file), this should produce valid JavaScript code that will do what you want:
$("div").prepend("<div id='comment-number'><?php echo htmlspecialchars(the_comment_number()); ?></div>");
1) php is SERVER side scripting
2) javascript is CLIENT side scripting (generally)
so this is what happens:
1) User opens up your page http://example/
2) Your CLIENT sends GET request to http://example/ server
3) Apache (given you run on it) captures the request, based on the server config approaches index.php (index.html, etc). If php is installed, your index.php will be parsed by mod_php module
<<<< this is where SERVER side scripting is activated
4) outcome of the parsing of index.php will be then transferred back to CLIENT
5) CLIENT will digest the outcome received by SERVER
6) If there are javascript calls, those are executed either immediately OR when document is loaded (based on approach)
That's it. Here normal request life ends.
NOW if you want your page to dynamically update some parts of it, here is how you do that:
1) Usually to update your page dynamically, you would use AJAX approach. When AJAX request is created, 2-7 happens again, but this time the caller is your ajax process and information which is received is sent back to that process to decided what to do with it.
Okay, some coding:
1) index.php
<!-- include jquery, etc //-->
<div id="comments"></div>
<script>
function fetch_comments(){
$.get("ajax.php", null, function(data)){
// this is called, when response from SERVER is received
$("#comments").prepend(data);
setTimeout("fetch_comments", 5000); // fetch again in 5 seconds
}
}
$(document).ready({
fetch_comments();
});
</script>
2) ajax.php
<?php
//fetch comments, return them for CLIENT
echo "<p>Comment on " . date("Y-m-d H:i:s") . "<br />Lorem Ipsum</p>";
This should help you understand the whole process. Did not test the code, but should be quite ok.
do a .ajax() query to PHP script that will provide you value of the_comment_number(); and put result to comment-number by $("#comment-number").prepend(result); on success event in ajax query.
Remebmer that PHP script have to have connection to database and pass to it all variables you need (like entity id, article id, page etc.). You can do it by GET or POST.
Request is sended by browser so session/cookies will be the same unless you changed it in current request.
PHP is executed on the server side so you cannot call it from javascript
You can try something like this which will render once the page loads
$("div").prepend("<div id='comment-number'>"+ <?php the_comment_number(); ?> +"</div>");
Couldn't you just add the value directly to the template instead of using javascriot? eg:
<div class="gallery-item">
<div class="comment-number"><?php echo (the_comment_number());?></div>
...
</div>
Also you have a </span> tag with out matching <span> tag in your example.
As already told, you can't produce or call php code from javascript directly(you need to make an ajax call or form submit). You need to make ajax call using jquery to fetch the comment number and then update it into div.
However, you may want to look at this library - http://www.phplivex.com/ .It may help you in doing things your way. It allows you to call user defined php functions in javascript using AJAX internally.
Reading through this disccussion and from what i understand you want to acheive.. You gotta figure how your page is served. If it is an .php file that is serving the content, then you wont need Javascript at all and could get your function call to work by adding the function between the div as so..
<div class="comment-number"><?php echo htmlspecialchars(the_comment_number()); ?></div>
Assuming you don't have access to the .php or if its a .html/htm page that serves the content then your only bet would be to use ajax. That is make an ajax call to a php file(on the same domain) that makes your function call and echos the comment no. The Ajax will retrieve the echo'd comment no. which you can append/prepend to the desired
I got this prob. In a web page I have a DIV that display a counter ( a PHP variable, $count). I have also a JS function that change the INNERHTML property of the DIV. I'm not able to change the js var on the changing of the PHP one.
HTML
<DIV id="counter">0</DIV>
PHP
while (----) {
do_something;
$count++;
}
JS
function ChangeDiv() {
document.getElementById("counter").innerHTML = // here the value of $count;
}
setinterval("ChangeDiv()",3600);
I want to to refresh the DIV every sec inserting in it the value of $count... but doing
document.getElementById("counter").innerHTML = <?php echo($count); ?>;
is wrong 'cause it will output just the initial value of $count.
I tried to insert a parameter in the function ChangeDiv, but in that way I had to call the function every time $count changed, echoing a
echo("<script>ChangeDiv('".$count."');</script>");
...that's really not functional.
Someone knows a simpler way to do it??
You need to use some sort of AJAX implementation to get this to work.
It will allow Js to query your PHP script to get a new value for $count
It looks like you might be writing some sort of progress bar?
Note that PHP runs on the server side and generates HTML / Javascript. Javascript runs on the client side.
What you would have to do to show a progress bar like that is to output <script> snippets that update your DIV element. If you put the line
document.getElementById("counter").innerHTML = "<?php echo($count); ?>";
(notice the quotes)
into the loop, and output buffering is turned off, and the counter HTML element was output before, you will get some sort of progress bar.
However, depending on what you want kind of action you are running behind that progress bar, an Ajax driven progress indicator may be much, much more elegant.
I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.