update JS Var on chaging of a php var - php

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.

Related

why $(element) not works directly. but works in function

When i try to select any element which is the result of ajax call it don't get selected using $(element)
but when i try to select that element in any function it will selected
Example: if i select an element with id change.
hello.php is
<?php
echo '<span id="change"> hello </span>';
?>
html in main.php is
<div id="content">
</div>
and script in main.php
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
$("#change").css({"backgroundColor":"red"});
</script>
this script don't change the color of span , I know it will not work because at the time when 2nd statement is executed their was no element with id change,
and $("#element") can't find the element with id change
But when i try $("#change") in any function it will change the color of span.
for example if i use
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
setTimeout(function(){$("#change").css({"backgroundColor":"red"});},0);
</script>
Please note i set the delay time to 0 sec. But this works and change the color of span with id change. I mean now the $("#change") can find the element with id #change
and if i use $("#change") in ajax function then also it works.
<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
$.post("example.php",function(r,s){$("#change").css({"backgroundColor":"red"});});
</script>
Can someone explain why this happen , why in other two examples $("#change") selects the element. even their is no delay in executing the function
Is all about timing. When you get content from the server and you try to inject it in DOM, it will take a bit to render. When you use setTimeout with whatever value, you push the inner function in the event loop. The result is that it will be executed after minimum time that you specify - in your case 0, but only when the stack is empty. During this time, things are rendering in DOM and you get to have access to those elements. You should watch this video for a much better explanation of what is going on: https://www.youtube.com/watch?v=8aGhZQkoFbQ
This is due to the asynchronous nature of your post command. The rest of the script doesn't get halted till the post get finished. Rather than that, it get's executed even though the post command is already under progress. What you do with the timeout function is that you delay the execution of the jquery selection by a fraction of time, and this gives the time for the post to finish.

jquery php mysql html passing value on one page

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.

jquery ajax / php poll database for changes

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.

jQuery context menu filled with php content based on selection

When a user selects a word in a text on my website (PHP), and then right clicks, i want a jQuery context menu to come up, this can be done by using one of the already existing jQuery context menu plugins.
But besides the options like copy / paste / cut, etc. I also want something to be done with the selected word using PHP. Which, i think, is a little harder.
For example using this script:
$selection = //the selected word or text
$target = //fetch from MYSQL database
$output = array();
while ($row = //fetch $target) {
If ($selection == $row->input) { array_push($output,$row->output); }
}
echo '//menu '.print_r($output).''; // of course not print_r! Just for the example's sake.
Databse example:
(Sorry for the oversized image)
Ok so selecting the word 'lazy' in the example text, and then right clicking, the jQuery box should pop up showing the results from the database extracted by PHP.
Example:
Ok, so i know you can't just combine javascript with PHP and it can only be parsed, but i thought loading an iframe withing the menu, which does the database extraction would do the job by using javascript to set the iframe src containing the selected word in the url.
However, iFrames are not really a nice way to solve this.
The question: How can i do this effectively? Execute this script on right-click and show the database-related content in the menu?
I would need to know the plugin you're using to give you some code examples but, general, I would go about this like this:
There has to be a click handler on the items in the jQuery context menu. Use it to submit an AJAX request to the server when the "selection" term is clicked.
Make sure to give the user some feedback (a loader or spinner)
Put the results into an array server-side.
JSON encode the array and send it as the response (e.g. echo json_encode($output)
JSON.parse(response) on client-side and you now have a JS object with the results
Put those results in the context menu (again, how depends on the plugin you're using)
AJAX is a great way to do what you want.
Here is a simple AJAX example. Note that in the 2nd .PHP file, that is where you put your database lookup etc.
Whatever you echo from the 2nd script is received by the calling javascript (first script again) and can be inserted into your context menu on-the-fly. Here is another example with a very detailed, step-by-step explanation of the process at the bottom of the answer.
I think you have to use Ajax to get JSON from a PHP file, which you would process on the actual page.
I you create a PHP file called test.php, with the following in it:
<?php
echo json_encode(array('time' => time(), 'hour', date('H')));
?>
Then the Javascript:
<script>
$('#curr_menu_entry').click(function() {
$.getJSON('test.php', function(data) {
$.each(data, function(key, val) {
$('#curr_menu_entry').append('<li id="' + key + '">' + val + '</li>');
});
});
});
</script>
Would that work?

How to make browser not to refresh full page when it goes to URL?

I tried to understand - is it any method to ask browser not to refresh entire page when user clicks onto . Hash adding method is seen - I need another method, working with links without hashes.
May be any headers should be sent ? Or something another ?
I want to process GET queries returning only the part of HTML (or special js commands), not all page, and process it in AJAX-style.
You can ajaxify your links through jquery. Something like this:
$('a.ajax').click(function(ev){
ev.preventDefault();
var target=$(this).attr('data-target');
var url=$(this).attr('href');
$(target).load(url+' '+target);
}
This can be used in conduction with the following HTML:
<div id="output">
Hello World
<div>
and inside world.html you would need to have:
<div id="output">
Foo bar baz boo
</div>
In theory this should load content of the dif from "world" file into the div inside the first file, but I haven't tried it. I think it's what you need, because the regular link is still there, google will properly index this bypassing ajax and your users will be happy to see part of the page change.
you could make it 'fake' links doing something like this:
<span style="cursor:pointer;" onclick="loadPage('mypagename');">My Link</span>
The function then would be:
function loadPage(pageName){
// do ajax call here using pageName var
}
You cannot prevent navigation when a user clicks a hyperlink with a URL. Using a hash value to navigate or having your hyperlinks invoke JavaScript is generally the way to add navigation inside of a single page.
However, if you're trying to convert an existing page that's not designed this way, you would have to use JavaScript to modify hyperlinks so they invoke Ajax. For example:
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var oldUrl = links[i].getAttribute('href');
links[i].setAttribute('href', 'javascript:void(0)');
links[i].onclick = (function(url) {
return function() {
// Then you can do your AJAX code here
}
})(oldUrl);
}
I recommend that you don't do something like this, though, and rather create your page with an AJAX design in mind.
Changing the url without using hashes can be achieved with the Html5 History API: http://html5demos.com/history
Not supported by older browser though, so you must always have a fallback.

Categories