I have searched for almost similar questions but none of those gave me the right answer. I have a fully working file_exist code in if else statement he
onclick= is used to call javascript function or to run javascript code you can not call a php function using onclick="", but as you are saying you are getting desired output without function is just because when you clicked on image it just render the same page having your first code and when you moved this code to a function, and as functions does not run by its own you need to call them thats why in second case you did not get expected output.
If you want to call php function using javascript use AJAX
Calling a PHP function using javascript
Create a test folder ex. ajax (yourhost/ajax/)
view.php (yourhost/ajax/view.php)
Simple AJAX Example
controller.php
readexisting();
break;
}
?>
model.php