简体   繁体   中英

pause PHP untill event/function with javascript is complete

Here are my code:

<script type="text/javascript">
function SaveToDisk(fileUrl, fileName) {
    var hyperlink = document.createElement('a');
    hyperlink.href = fileUrl;
    hyperlink.target = '_blank';
    hyperlink.download = fileName || fileUrl;

    var mouseEvent = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true
    });

    hyperlink.dispatchEvent(mouseEvent);
    (window.URL || window.webkitURL).revokeObjectURL(hyperlink.href);
}
</script>

</head>

<body>
<?php
$newtarget = "0C004B290BF2D95F";
$filename = 'C:/Users/FOO/Downloads/'.$newtarget.'.txt';

if (file_exists($filename)) {
    unlink($filename);
} 

?>
<script type="text/javascript">
    SaveToDisk('http://www.ticketmaster.com/json/resale?command=get_resale_listings&event_id=<?php print $newtarget; ?>','<?php print $newtarget; ?>.txt')
</script>
<?php

$newlink = file_get_contents('C:\\Users\\FOO\\Downloads\\'.$newtarget.'.txt');

When the file is deleted the file_get_contents php function runs before the SavetoDisk rewrite the file on disk.

"failed to open stream: No such file or directory".

When I don't delete the file, it works. I tried to insert sleep(10) right after the call of the javascript function but still got the error, inexplicably the file is wrote after the 10 seconds... any tips on this?

PHP is processed by your server whereas Javascript is processed by the user's browser, therefore regardless of how you order functions within the same .php doc, the Javascript will always run after the PHP is processed.

If you need to run PHP after your Javascript has been executed, look at jQuery's post function to call a PHP file from your Javascript. I'd strongly recommend you take a look at some online learning tools like codecademy to get a better grasp of PHP / JS.

You can't do that. PHP is executed on the server and JavaScript is executed on the client (web browser).

Right click on your web browser and select View Source to check the content. You will not see your PHP there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM