Lucas Fusco
Lucas Fusco

Reputation: 75

Returning data from Ajax to PHP

Good Afternoon!

I'm trying to save in a Database the name of my picture... I have the following Ajax code.. It's saving perfectly the pic inside the foldes, but I can't return the name of my file into a PHP variable from upload_foto_webcam.php...

I have 2 pages... My first page is a form, and it's where I call the function Salvar_foto()... After saving the pic I'd like to return in the same page of my form the name of saved image.

        function salvar_foto()
    {

        var file =  document.getElementById("base64image").src;
        var formdata = new FormData();
        formdata.append("base64image", file);
        var ajax = new XMLHttpRequest();
        ajax.addEventListener("load", function(event) { upload_completo(event);}, false);
        ajax.open("POST", "upload_foto_webcam.php");
        ajax.send(formdata);

        document.getElementById('take_pic').style.display = 'none';
        document.getElementById('take_pic_again').style.display = 'none';
        document.getElementById('save_pic').style.display = 'none';         
    }

Here's my PHP file:

<?php
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['base64image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR .date("d-m-Y")."_".uniqid(). '.jpg';
$success = file_put_contents($file, $data);

$cliente_foto_webcam = $file;

print $success ? $file : 'Não é possível salvar o arquivo.';
?>

I want to get back the $cliente_foto_webcam variable... What should I do?

I'd really appreciate if you could help me!

tks

Upvotes: 0

Views: 126

Answers (2)

Szekelygobe
Szekelygobe

Reputation: 2695

What do you want to do with the name of the picture?

If to display the name of the saved image to the user, than you can use jQuery to get the filename from the php file where you saved the image.

So one way to do this is to print/echo the name of the file inside of a span or div or some object with a id tag like this:

$ajax_return = '<div class="hide_this">
                    <div id="ajax_response">'.$response.'</div>
                </div>';
echo $ajax_return;

Then in the file where you made the ajax call :

$.ajax({
    url: "upload_foto_webcam.php",
    method: 'POST',
    data: formdata,
    async: true,
    dataType: 'html',
    success: function(ajax_response) {
        // here you find the name of the saved image
        var saved_image_name = $(ajax_response).find("#ajax_response").text();
        // loading image name in container div/span
        $('#your_message_container').html(saved_image_name);
    }, // end success
    // handling error on ajax call
    error:  function(xhr, textStatus, errorThrown) {
        console.log(errorThrown ) ;
    } // end error handling
});

You can format the message in the php file where you save the image, and return the full message :

The image was saved as your_generated_image_name.jpg

and put this message in the container div.

Upvotes: 0

Tibbelit
Tibbelit

Reputation: 1335

I would suggest a JSON-answer from your PHP-backend, something like:

{
    "filename": "my_image.jpg",
    "message": "Image uploaded!",
    "success": true
}

Which would be something like:

<?php
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['base64image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR .date("d-m-Y")."_".uniqid(). '.jpg';
$success = file_put_contents($file, $data);

$cliente_foto_webcam = $file;

if ($success) {
    echo json_encode([
        "filename" => $cliente_foto_webcam,
        "message" => "Image uploaded!",
        "success" => true
    ]);
} else {
    echo json_encode([
        "filename" => null,
        "message" => "Couldn't upload image",
        "success" => false
    ]);
}
?>

Upvotes: 2

Related Questions