I would like to place some JavaScript into a PHP snippet and be able to load a function. I have been following this site: http://www.dynamicdrive.com/forums/showthread.php?41129-How-to-put-JS-in-PHP and have had no luck.
This is my code so far:
<input type="hidden" name="projectPhoto" value='<?php echo "<script type=\"text/javascript\" src=\"js\phpjs.js\"></script>";
?>'/>
Despite following instructions clearly, the result is exactly what is being echoed. The script has not been run. Is this even possible to do?
Also this is my function:
function uploadFile(){
var filename = document.getElementById("image").value;
filename = filename.replace("C:\\fakepath\\", "");
alert(filename);
filename = String(filename);
document.getElementById("projectPhoto").value = filename;
};
-
We discussed this before, this is unreliable some browser also return a fakepath ex.Tredged– Tredged2013年07月09日 07:48:52 +00:00Commented Jul 9, 2013 at 7:48
-
I think there are issues that are waaaaaaayyy more obvious with this snippet than file upload fake paths.zneak– zneak2013年07月09日 07:49:35 +00:00Commented Jul 9, 2013 at 7:49
-
1You can't echo a script tag inside an input tag and expect it to work. You shoul try to echo the script as it is and then set the value to something like: value=uploadFile()Gimmy– Gimmy2013年07月09日 07:49:50 +00:00Commented Jul 9, 2013 at 7:49
4 Answers 4
You have to load this JS file on its' own. You don't even need php for that, you can use the same script tag you've included:
<script type="text/javascript" src="js/phpjs.js">
Just place that tag, let's say bellow your input tag. Also, place another one bellow that:
<script>
uploadFile();
But I suspect this will not work. Your function wants to place a value of the "#image" element into this hidden field? Is this #image dynamically created? Ie. user enters something there?
Then you can simply do on that input tag something like this:
<input id="image" onchange="uploadFile()"/>
Comments
<?php
// PHP Single quotes and double quotes for JavaScript
echo '<script type="text/javascript">';
echo 'document.write("Like That!")';
echo '</script>';
?>
Comments
I'm not sure if it is possible. But it doesn't look right.
I'd take the javascript out of the value of your input field and instead set the value in your function:
function uploadFile(){
var fileName = document.getElementById('image').value;
document.getElementById('projectPhoto').value = fileName;
}
With your input field like this:
<input type="hidden" name="projectPhoto" id="projectPhoto" value='' />
Comments
You have two issues at least:
You are mixing javascript and php up, that cannot work as you can't use javascript in php:
$fileName = document.getElementById('image').value;I'm not sure the browser will execute
<script>tags within thevalueattribute of the input field. Place the script outside of it.