NickName:hugseirvak Ask DateTime:2009-06-22T07:56:40 Why won't this code work? Can anyone tell me why this code won't work? <?php $err=1; ?> <img src="334234234234234.gif" onError="<?php $err=0; ?>" /> <?php echo "<br />" . $err; ?> Even when the image exists, the onerror is still executed. Why? Copyright Notice:Content Author:「hugseirvak」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.Link to original article:https://stackoverflow.com/questions/1025065/why-wont-this-code-work Answers artlung 2009-06-22T00:18:39 Your code will always produce this output:\n\n<img src=\"334234234234234.gif\" onError=\"\" />\n<br />0\n\n\nThe onError JavaScript handler is empty because the php code inside it produces no output.\n\nIs the code you posted actual code or simplified code? It's not clear what you're trying to accomplish.", Sampson 2009-06-21T23:58:30 HTML cannot set PHP variables. Those can only be set while on the server. The onError method of the IMG tag has no access to PHP variables.\n\nThe page life-cycle:\n\n\n(SERVER) The server builds your page (handling variables, etc)\n(SERVER -> CLIENT) The server sends out the page to the client computer\n(CLIENT) The html is loaded, javascript is ran, and any errors are raised.\n\n\nNote, you're attempting to combine item 3 with item 1, which cannot be done semantically.\n\nThe only way to do what you're attempting would be to attach a javascript method to that event, and communicate to the server when and if the onError method is ran. But this is likely going to be a bit more complicated than you're use to.", DeadHead 2009-06-21T23:59:29 Since php is server side code, the <?php $err=0; ?> will get executed whether or not onError actually happens. You'll want to use someother method, or Javascript (or another client side code) to do that.\n\nIf all you are wanting to do is print out a variable to the screen if the image doesn't load, you can use onError=\"alert('ERROR: Image did not load');\" to create a popup box (or you can use javascript to modify the html on the page), but if you want to talk to the server, you'll have to either submit a form with javascript or use an AJAX method.",