Issue running PHP code after Javascript
Basically, this i开发者_运维技巧s what I am doing: I have a flash/ajax file uploader where users can select x amount of photos and upload them and then they are inserted into a MYSQL database by an external php script.
After they are inserted in the database, I would like to display them on the page and allow the users to edit the tags, caption, etc.
However, I cannot figure out how to "Live update" the page to display the correct data
Take this for example: showFields() is ran once he upload is complete;
function showFields() {
var jsvar = '<?php echo getIDs(); ?>';
document.getElementById('picndata').innerHTML += jsvar;
}
which will work if I have getIDs just return a static value such as "test"
but if i were to have it do this:
function getIDs() {
$SQL = "SELECT * FROM `slides` ORDER BY `sid` DESC";
$results = mysql_query($SQL);
$row = mysql_fetch_assoc($results);
$slide = $row['sid'];
$SQL = "SELECT * FROM `slides` WHERE `sid` = $slide";
$results = mysql_query($SQL);
$str;
while ($row = mysql_fetch_array($results)) {
$str .= $row['size'] . "\r\n";
}
return $str;
}
(sloppy I know)
, then it will not work because the PHP is ran first and so it does not find any results because the images were not uploaded yet!
Any ideas?
This line:
$str .= $row['size'] . "\r\n";
will result in your JavaScript having an unterminated string literal.
Change:
var jsvar = '<?php echo getIDs(); ?>';
To:
var jsvar = '<?php echo str_replace("\r\n", "\\\r\n", trim(getIDs()) ?>';
This will place slashes in the appropriate places so the JavaScript is valid. Alternatively, instead of adding a backslash, you could replace the newlines entirely with a space or a comma or whatever works best for your code.
Use ajax and timestamp your images.
I personally have a 'refresh' function that get's called on a timed basis via setTimeout().
On initial load of current images, determine the newest image timestamp.
In you ajax, query for images with timestamp > previous 'newest' timestamp. Update the page if you get any results, and reset your new 'newest' var.
If you have some return from your upload function that you can use to trigger your ajax as well, that would eliminate any delay in seeing the new images.
I'd also suggest storing that timestamp in session variables so you are not relying on user input for your query.
Also handles concurrency where other users could be uploading to the same area.
精彩评论