JulianJ JulianJ - 1 month ago 10
jQuery Question

How to return a variable in an ajax response?

I am using a script to upload images to a server. It uses ajax to post the image to a php script where after validation the image is given a unique file name before saving it to a directory. I'm trying to understand how to get the new file name of the image back to my form page as a variable where I can then use that new variable, for example echo it in

<?php echo "new_file_name"?>
. Any help would be really appreciated.

my_form_page.php

<div id="preview"><img src="no-image.jpg" /></div>
<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
<div id="err"></div>

<h2>The new file name is: <?php echo "new_file_name"?></h2>


The jquery

$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#file_name").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});


ajaxupoad.php

<?php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory

if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];


// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

// can upload same image using rand function
$final_image = rand(1000,1000000).$img;

// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);

if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";


}
}
else
{
echo 'invalid';
}
}


?>

Answer

To get the file name back to the script, simply echo it out in php! I would use JSON as a wrapper for your response, so that you can send back multiple values at once, like this :)

$response = array(
    'status' => 'success',
    'name'   => $img,
    'path'   => $path
);

echo(json_encode($response));
exit();

Next, add "dataType" to your ajax request, like so

  $.ajax({
        url: "ajaxupload.php",
        type: "POST",
        data:  new FormData(this),
        contentType: false,
        cache: false,
        processData:false,
        dataType: 'json', <-- THIS RIGHT HERE

Now the servers response will automatically be parsed as JSON, so you can access your response like so

   success: function(data)
        {
            if(data['status']=='invalid')
            {
                // invalid file format.
                $("#err").html("Invalid File !").fadeIn();
            }
            else
            {
                var name = data['name'];
                // view uploaded file.
                $("#preview").html('<img src="' + data['path'] + '">').fadeIn();
                                    $("#file_name").html(data).fadeIn();
                $("#form")[0].reset();  
            }
        },

Just make sure that ANYTIME you echo in your php script, you json_encode the response FIRST, then EXIT!! Otherwise, the script will keep executing and you'll get multiple responses and everyone get's confused. LOL

Comments