If I put marquee in while loop it shows all the data at the same time, sliding right to left. I want this to behave one by one, when one finishes the second starts... and lastly the first comes again, how can I do this please help me out I would be very grateful to you, thanks in advance :)
$data=mysql_query("SELECT heading from moto_static_pages");
while($res = mysql_fetch_assoc($data)){
echo '<marquee behavior="scroll" direction="left" style="padding:0 0 10px 0;">';
echo $res['heading'];
echo '</marquee>';
}
PHP is server-side. Everything is computed on the server, and then all at the same time displayed on the browser in-front of you. So your loop is merely looping around what eventually will be displayed in the browser, and printing it all out at once, which is what it's supposed to do.
You will need to use JavaScript to accomplish this, as this is client-side. You cannot do this with PHP.
You will need to retrieve all the data from your database, convert it to json (json_encode()), and send this to your browser as one string. Then, in JavaScript, loop through the json and print out each one as a marquee with a timed event.
To reiterate, unless you are going to be doing something with asynchronous I/O with PHP, which you aren't, you will need to do this with JavaScript.
This is untested code and straight from the top of my head, but hopefully this will point you in the right direction.
<?php
// Server-side code, get your data, json encode it too!
$data = json_encode(mysql_query("SELECT heading from moto_static_pages"));
?>
<script type = "text/javascript">
// Client side code that happens in real time in the browser
// Get your data from your php variable
var data = JSON.parse(<?php echo $data; ?>);
// Loop your data
for (var i = 0; i < data.length; i++)
{
// Output your data in marquees
setTimeout(function() {
document.write("<marquee behaviour='scroll' direction='left'>");
document.write(data[i].heading);
document.write("</marquee>");
}, 4000); // Every 4 seconds
}
</script>
Don't expect this code to just work for you, so get debugging it and using var_dump() to see what you get from PHP, and console.log() to see what you have in JavaScript.
Final Note
mysql_query has been deprecated and should be used with caution. You should check out PDO / mysqli instead; they're not too hard to understand and they're interesting too!
Related
for($x=0;$x<100000;$x++) {
echo "hello $x";
}
So, normally, it will finish processing everything first and then print everything at once. Is there a way to just keep printing the message as the command is sent, so that I'll see a new hello $x appended one by one or do I have to use jQuery/JavaScript?
Update:
I ask because I'm trying to run a long test script and have it show all the results 1 by 1 on the browser so I don't have to go check the logs and could just visually see the color coded results. I'm trying to make a similar effect to this: http://tools.css3.info/selectors-test/test.html If anyone could provide a short sample of the jQuery (if it has to be done this way), I would appreciate it.
Although it's possible by controlling the output buffer, I wouldn't do that, mainly because it will delay the JavaScript DOMReady event.
If you're looking for a visual effect, you should use JavaScript (but I don't see any reason for Ajax based on what your question says). It can be accomplished with a simple setInterval. Considering an initially empty <div id="hello">:
var i = 0;
var timer = setInterval(function(){
if(i == 10000) {
clearInterval(timer);
return;
}
var div = document.getElementById('hello');
div.innerHTML += 'hello ' + i + '<br>';
i++;
}, 250);
I just saw your edit, and now I think you actually should use Ajax! The example you linked to does. Basically, you have to setup a test queue in JavaScript, where each test has an unique URL. Then it's just a matter of firing one request at a time with Ajax (jQuery and $.get would be the easiest way to go). The following assumes an <ul> instead of the div from my previous example, and that the server will respond with a success or failure message for each test:
var tests = [
'http://example.com/test1',
'http://example.com/test2',
'http://example.com/test3',
];
function processQueue() {
if(tests.length > 0) {
var test = tests.shift();
$.get(test, function(response) {
$('#some_ul').append('<li>' + response + '</li>');
processQueue();
});
}
}
processQueue();
Yes, if you disable output buffering: http://php.net/manual/en/book.outcontrol.php
But as #Blender suggests you'd probably be better off doing this with AJAX (commonly done using jQuery).
Ultimate Goal: I want to take data I keep in a MySQL Database and put it into an Array of Arrays in JavaScript, so it can be manipulated client side.
So far, I have been able to pull data from my database with this code:
<?php
...
$num=1;
$q = "SELECT blah1, blah2, blah3 WHERE blah4=$num";
$sth = mysqli_query ($database, $q);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
?>
(from: JSON encode MySQL results)
This is where I am stuck, because I am having trouble getting this data into JavaScript.
One solution I can find is Parsing a Separate PHP Array in Javascript:
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
But the problem with this implementation is that it would spit out all of the database content I query onto the source-code of the page. If I have to do this, I might as well skip the database and just keep all of the content in javascript.
I am thinking there must be a way with jQuery/AJAX to pass the value of $num to a PHP script, grab this data and put it into a JavaScript Array without having to output all of it to the page.
Any assistance would be appreciated.
Thank you!
This solution you posted:
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
Is actually a very good approach. Using AJAX is drastically slower (because of network latency).
Unless you really need AJAX for some reason, you should avoid using it. It will add a noticeable split second of load time to the page, often for no benefit at all.
Above all when structuring your page, you want to try and reduce the number of individual network requests between the browser and the server. The less requests the faster your page will be. This is especially true for javascript and ajax, because they are unpredictable and browsers find it very difficult to optimise any part of the page where it's being used.
We're talking about one quarter of a second compared to one millionth of a second, for exactly the same end result.
Making an AJAX call with jQuery is easy enough. Take a look at the documentation: http://api.jquery.com/jQuery.get/
You can also do this without AJAX
var jsonarray = eval(<?php echo json_encode($array); ?>);
I have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.
Here's my code:
(function() {
var data = [];
for(var i = 0; i < 25; i++) {
data[i] = {
data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
data2: ....
};
};
});
I think you are confused, you are trying to use a variable of javascript in php.
You cannot do this:
<?= $latest[?>i<?=]->file; ?>'
Which expands to:
<?php
$latest[
?>
i
<?php
]->file;
?>
how can you possibly know the value of i, if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.
You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.
The following links better explain this.
http://www.givegoodweb.com/post/71/javascript-php
http://www.dynamicdrive.com/forums/showthread.php?t=21617
1.Pass the javascript variable to the URL to another php page.
window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);
2.Then you can use this variable using $_GET in the php script.
$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;
3.Perform any server side operation in the Php and pass this result.
header("Location:<your starting page>?result=".$yourPhpResult);
4.Redirect back to the page you started from thus passing the result of PHP.
Php and Javascript have different roles in web development.
This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.
Hope this helps!!
I want to change the effects of a set variable that is at the beginning of a document for example:
if(isset($var)){
// Show Loading Message
}
// Whole bunch of code to load a report
unset($var); // To remove the loading message
I want the deceleration at the end of the code to remove the loading message that is above by removing the variable. Is there any way to do this with PHP?
Thanks!
Note: I understand how the program would usually work, the question is if there is a way around this typical model output being definite, using PHP.
You are not able to remove something that has already been outputted to the browser using PHP - once you output the loading message, from PHP's perspective it is gone and out the door.
You'd have to have some javascript on the page to manipulate the DOM and remove the text node that way.
For example:
print '<div id="loading_message">Loading, please wait</div>';
... bunch of code ...
print '<script type="text/javascript">var e = document.getElementById("loading_message"); e.parentNode.removeChild(e); </script>';
You will have to do it client side; all HTML generated by a PHP script is sent to the browser and can't be retrieved again. To do it client side, give the loading div an ID of, say, #loading. Then, at the end of the PHP script, stick some JavaScript in that will hide the div. Here's a jQuery example:
Loading div:
<div id="loading">Loading...</div>
jQuery (echo this from the bottom of your PHP file):
<script>
$("#loading").hide();
</script>
EDIT
For a vanilla JavaScript solution, please see #Chris's answer
Hope this helps,
James
Well, there are actually ways to process PHP and send to the browser window BEFORE things are done processing.
It's a hokie, hokie, hokie way of doing things but I wanted to at least share.
You can use the flush() command at any point to output the current moment in processing out to the browser while the page is still rendering.
You can also do your processing and store the output of the processing in the output buffer before it goes out.
ob_start();
//Do a bunch of PHP stuff
$results = ob_get_contents();
ob_end_clean();
echo $results
Like I said...HOKIE for general web page processing. Use jQuery or your own JS, but maybe this will some in handy somewhere else.
I have the following jquery code:
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
But I need $day_1 in the php echo statement to reflect the variable "count", so in theory it should be something like "echo $day_count". Is it possible to pass the var to php?
php & jquery coding:
$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}
?>
<script type="text/javascript">
var chart1;
var count=1;
var formfig=17;
var formfig2=2;
function chartdraw(){
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
The short answer here is no.
To understand what's possible, you need a deep understanding of what's going on. Your PHP code is building an HTML document (with embedded JavaScript) and sending it on to the web browser. Once the web browser (which is, of course, running on the user's machine, not your server) renders that page, it will execute the javascript. This is when the javascript variables begin to actually mean something. Until then, they are just text getting sent across the network. This point is long after the PHP code has finished running. Your server has already closed down that php instance as it sent the code to the user.
Keeping that in mind, you can send the value of a javascript variable (or any number of other things) back to your server with something called an ajax request. Essentially, this will send some information (the variable's value, and the name of the page you want) back to your server, which will in turn cause your server to build a new web page, which can have PHP code in it. That web page's content will get returned to another bit of javascript you can provide -- called a 'callback' -- which can take the page created by the second php script and make use of it. This is, of course, fairly resource intensive.
Unless you plan to do something that ONLY PHP can do, I would recommend finding a way to do as much of your logic as possible in javascript. This alleviates all these complex problems and keeps all the hard work on the user's machine.
If you can structure your code so your php code provides all the data the javascript code needs before the php finishes running, you can get away without doing anything fancy with ajax. Here's an example:
<script type="text/javascript">
var days = {};
<? for($day = 0; $day < 30; $day++) { ?>
days.<? echo $day ?> = "<? echo get_day_info($day) ?>";
<? } ?>
</script>
What this will do is create a javascript object called days. Then it will fill in days.i for i from 0 to 30. It assumes you have a function called get_day_info($day) which takes a day and returns the info for that day. I'm assuming here that you're dealing with strings -- if not, you will need to remove the quotes, and possibly do other things to wrap the data depending on what format it takes.
I belive the only way is using ajax. http://api.jquery.com/jQuery.ajax/
Not without changing your approach significantly.
The problem is that PHP exists entirely on your server, where javascript exists in the browser. PHP does really know anything about javascript. PHP will completely render your page before any javascript has been run at all. So there is no way to get this value back in easily.
You can use ajax in order to run javascript which can load data or hit URLs on your server, but you cant simply substitute javascript variables in PHP. The reason you can do it with PHP variables is because the PHP actually is generating the javascript.
Have javascript store the value in a hidden field and pick up the value with PHP that way?