I have a form where the user uploads an image and the image is then relayed through Ajax to PHP. After the image is uploaded on the server, PHP will echo back the $target_file to Ajax. $target_file is essentially the URL of the image. Ajax will take that variable and then display it through the "readonly" input text box in the same form. After testing what I have, the image is being uploaded successfully. The only problem is that when the image is uploaded successfully, the entire code of the PHP script is being shown in the "readonly" input box instead of the $target_file variable that should display the URL of the image.
Here's what I have:
HTML
<form class="image_upload" method="post" action="ajax.php">
<input name="server_upload" type="file">
<input type="text" name="image_url" readonly>
<input type="submit" value="UPLOAD TO SERVER">
</form>
Ajax
$('.image_upload').on('submit', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if ($('.image_upload').valid())
{
$.ajax({
type: 'POST',
url: 'ajax.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
$('input[name=image_url]').val(data);
}
})
}
})
PHP
if (isset($_FILES["server_upload"]))
{
$name = $_FILES["server_upload"]["name"];
$tempName = $_FILES["server_upload"]["tmp_name"];
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
if (getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
move_uploaded_file($tempName, $target_file);
echo $target_file;
}
How can I fix this so the URL is shown? Why is it printing out all my PHP code?