0

I am having problems submitting a form via ajax where without ajax it submits without any problems.

If I use this on it's own the image uploads correctly:

<form id="edit_image1_form" action="upload_file.php" method="post" enctype="multipart/form-data">
    <img id="edit_image1" src="<?php echo $venue_image_upload_one; ?>" alt="" />
    <input type="file" name="file" id="file" onchange="readURL1(this);" style="width:155px;"><br>
    <input type="submit" id="upload_image1_submit" name="upload_image1_submit" value="Update Image">
</form>

But when I add this it give me an error and not upload is done:

$("#upload_image1_submit").click(function() {

        var url = "upload_file.php"; 

        $.ajax({
               type: "POST",
               url: url,
               data: $("#edit_image1_form").serialize(), //form name here
               success: function(data)
               {
                  alert(data); 

               }
             });

            return false; 
        });

The error is Invalid File from here:

<?php
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 20000)
    && in_array($extension, $allowedExts))
      {

      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        }
      else
        {
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("upload/" . $_FILES["file"]["name"]))
          {
          echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
          }
        }
      }
    else
      {
      echo "Invalid file"; //HERE
      }
?>

BUT my problem is that if I submit the form without ajax I will not get this error and the image I'm uploading all the time for testing is the same one.

Any ideas on what this could be ?

Satch3000
  • 47,356
  • 86
  • 216
  • 346

2 Answers2

2

See simply sending the serialized form won't send the image in post params, you need to append the files. this is a sample code which i once used to upload image using ajax which works fine.

 var imageUploaded = '';    
    formdata = false;                      
    if (window.FormData) {
        formdata = new FormData();
    }            
    var reader, file;   
    if(jQuery('input[type=file]').get(0).files.length){
        file = jQuery('input[type=file]').get(0).files[0];  
        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("images[]", file);
            }
        }       
        if (formdata) {

            jQuery.ajax({
                url: "your url",
                type: "POST",
                data: formdata,
                dataType: 'json',
                processData: false,
                contentType: false,
                async: false,
                success: function (res) {   
                    //do something here
                }
            });
        }

in your controller, or ajax url page, get image using $_FILES["images"]["name"].. Hope this might help your need.

abhij89
  • 625
  • 3
  • 18
  • You should remove the async: false from your code. Synchronous Ajax requests are always a bad idea as they tie up the UI thread for the duration of the request. – Ray Nicholus Sep 20 '13 at 13:14
  • but sometimes they are most needed. – abhij89 Sep 20 '13 at 13:18
  • No, there is never a good reason to send a synchronous ajax request. If you think you need to do this, that is an indication that your code/application is improperly designed. – Ray Nicholus Sep 20 '13 at 14:06
0

With XHR2 you can upload through AJAX using FormData object, but this is not supported by older browsers as far as I know.

Otherwise you can do something like this:

var form = new FormData();
form.append('file', $('input[type=file]')[0].files[0]);

$.ajax({
       type: "POST",
       url: url,
       data: form,
       success: function(data)
       {
          console.log(data); 
       }
});
Clem
  • 11,334
  • 8
  • 34
  • 48