0

I have a PHP page in which a user can insert data (with input text or files) in a DB. These data will be visualizated on a web site. I need a preview button. When the user click on preview button, it will be opened a popup window with the text and the image that he has inserted. So, i need to upload the image on server (to get the complete path of the image and display it) without a submit button and without a refresh of the page in wich the user is inserting data (because they don't have to be lost).

I was thinking of ajax and php

my code index.php:

<form action="filePHPForPublishing" method="Post">
    //other code...

    <input type="file" name="img" id="img" />
    <input type="button" id="Preview" name="Preview" value="Preview">

    //other code...

    <input type="submit" id="publish" name="publish" value="publish">
</form>

my cose ajax.js:

$(document).ready(function () {
$("#Preview").click(function() {
    var datiForm = new FormData();
    datiForm.append('image', $('#img')[0].files[0]);
                $.ajax({
                    type: 'post',
                    url: 'ajax.php',
                    data: datiForm,
                    dataType: 'text',
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        alert(data);
                        return false;
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        alert(xhr.status + ': ' + errorThrown);
                        alert("error");
                    }
                })
});

});

my code ajax.php:

$target_dir = "";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
$uploadOk = 1;
move_uploaded_file($_FILES["img"]["tmp_name"], $target_file);
$linkIMG =  basename( $_FILES["img"]["name"]);

But when i click the preview button, there is an error on the php file "undefinible variable img" in this point "$target_file = $target_dir . basename($_FILES["img"]["name"]);"

am I doing something wrong? i'm new with ajax

  • in JS you are appending "image", and in PHP you are looking for "img" – Dino Jan 20 '18 at 18:08
  • Did you try with `image` instead `img`? – Niklesh Raut Jan 20 '18 at 18:09
  • it doesn't work even with "image". In JS i'm appending '#img'. i think that the error is in ajax.php, because it doesn't recognize the file input. How ajax.php and index.php have to be connected? – Brododipollo Jan 20 '18 at 18:18
  • Try this for the preview: https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded?rq=1 –  Jan 20 '18 at 18:43
  • this is for the preview in the same page. i need to open preview (with image) in other window – Brododipollo Jan 20 '18 at 18:53

0 Answers0