1

I was requested to use only Javascript (Ajax/Jquery/JSON) only. Why doesn't this work?

Here's my code that I embedded in HTML script:

function uploadImage(){
    $.post("signup/upload.php", function(data)
    {
        if(data['status']!='ok'){
          $("#status").html(data['status']);
          console.log("!Failure");
        }else{
          $('#status').html("Your picture was uploaded!");
          console.log("Success");
        }
    });
}

$(document).ready(function () {
    $('#uploadImageButton').on('click', function()
    {
        uploadImage();
    });
});

Here is the HTML:

<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Submit" id = "uploadImageButton" name="submit">

Here is the PHP:

  $reply['status'] = 'ok';
    <?php
    if(isset($_POST['submit'])) {
            if (isset($_FILES['upload'])) {
                    $allowed = array ('image/pjpeg', 'image/jpeg','image/JPG');
                    if (in_array($_FILES['upload']['type'], $allowed)) {
                            if (move_uploaded_file
                                    ($_FILES['upload']['tmp_name'], "/fakepath/www/upload_files/{$_FILES['upload']['name']}"))
                            {
                                    $reply['status'] = 'ok';
                                    echo '<p><em>The file has been uploaded!</em></p>';
                            }

                    } else {
                            echo '<p class="error">Please upload a JPEG or PNG image.</p>';
                    }
        }
}
print json_encode($reply);
?>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Dil
  • 145
  • 1
  • 1
  • 9

2 Answers2

0

You should use $.ajax request, e.g below.

HTML :

<form enctype="multipart/form-data">
    <input type="file" name="upload" id="fileToUpload">
    <input type="submit" value="Submit" id = "uploadImageButton" name="submit">
<form>

JS :

$(function(){
    $('body').on('submit', 'form', function(e){
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "signup/upload.php",
            data: new FormData(this),
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                //your code
            }
        });

        return false;
    })  
})

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

First PHP instruction $reply['status'] = 'ok'; would not execute because it is placed before PHP open tag.

kshpolvind
  • 91
  • 4