user2896120 user2896120 - 3 months ago 8
Javascript Question

Displaying image URL after submission

I have a form where the user submits an image and after submission the image URL will be shown in an input text field. The form data is relayed to PHP through Ajax. The image is then uploaded to the server. I have implemented the submission system, but I do not know how I can display the uploaded URL in the input text field so the user can see it. I do not want the page to refresh, this all happens dynamically.

Here's my code:

HTML

<form class="image_upload" method="post" action="">
<input name="server_upload" type="file">
<input type="text" name="image_url" readonly>
<input type="submit" value="UPLOAD TO SERVER">
</form>


jQuery/Ajax

$('.image_upload').on('submit', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if ($('.image_upload').valid())
{

$.ajax({
type: 'POST',
url: '',
data: new FormData(this),
processData: false,
contentType: false,
success: function(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);
}


I want $target_file to be shown in the input text form field after the user submits an image. How do I accomplish this?

Ekn Ekn
Answer

One option you have is to echo $target_file after the line

move_uploaded_file($tempName, $target_file);
echo $target_file;

Then in your ajax success, you can use this like:

$.ajax({
    type: 'POST',
    url: '',                      // (*)
    data: new FormData(this),
    processData: false,
    contentType: false,
    success: function(data) {
        $('input[name=image_url]').val(data);
    }
});

As long as the form submission doesn't take you to another page, the data will be what you echoed.

(*) Notes:

  • Since the url is empty, which by default is the current page, the above code would return the entire page. If you put the PHP into another file and call that like url: 'file.php', it will function correctly.
Comments