cola
cola

Reputation: 12466

I can upload files with jquery ajax and php, some explaination and modification required

I have read this.

https://developer.mozilla.org/en/docs/Web/API/FormData

Still can't understand why is formdata(frm) is empty in code. console.log(frm); returns "FormData{}" empty. Why?

file_form.php =>

<title>Upload File</title>
<div id="targetLayer">No Image</div>
<img id="my_image1" src="" />
<img id="my_image2" src="" />

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

<script type="text/javascript" src="jquery-1.11.3.js"></script>

<script type="text/javascript">

    $(document).ready(function (e) {
        $("#uploadForm1").on('submit', (function (e) {
            frm = new FormData($(this)[0]);
            console.log(frm);
            e.preventDefault();
            $.ajax({
                url: "upload_script1.php",
                type: "POST",
                data: frm,
                contentType: false,
                cache: false,
                processData: false,
                success: function (response) {
                    var JsonObject = JSON.parse(response);
                    $("#targetLayer").html(response);

                    var fl1 = "uploads/" + JsonObject.image1;
                    $("#my_image1").attr("src", fl1).height(100).width(100);
                }
            });
        }));

        $("#uploadForm2").on('submit', (function (e) {
            frm = new FormData($(this)[0]);
            e.preventDefault();
            $.ajax({
                url: "upload_script2.php",
                type: "POST",
                data: frm,
                contentType: false,
                cache: false,
                processData: false,
                success: function (response) {
                    var JsonObject = JSON.parse(response);
                    $("#targetLayer").html(response);

                    var fl2 = "uploads/" + JsonObject.image2;
                    $("#my_image2").attr("src", fl2).height(100).width(100);
                }
            });
        }));


    });
</script>

upload_script1.php =>

<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['image1']['name']);
    move_uploaded_file($_FILES['image1']['tmp_name'], $uploadfile);

    $image1 = $_FILES['image1']['name'];
    $images["image1"] = $image1;
    echo json_encode($images);
?>

upload_script2.php =>

<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['image2']['name']);
    move_uploaded_file($_FILES['image2']['tmp_name'], $uploadfile);
    $image2 = $_FILES['image2']['name'];
    $images["image2"] = $image2;
    echo json_encode($images);
?>
  1. Can anyone rewrite the two $.ajax() code to one $.ajax() code making the code shorter? Re-write the html and php code if necessary.

Any help will be highly appreciated. Thanks in advance.

Upvotes: 3

Views: 988

Answers (3)

Samir Karmacharya
Samir Karmacharya

Reputation: 890

I think it will minimize your code

<title>Upload File</title>
<div id="targetLayer">No Image</div>
<img id="my_image1" src="" />
<img id="my_image2" src="" />

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

<script type="text/javascript" src="jquery-1.11.3.js"></script>

<script type="text/javascript">

    $(document).ready(function (e) {
        $("#uploadForm1").on('submit', (function (e) {
            frm = new FormData($(this)[0]);
            console.log(frm);
            e.preventDefault();
            $.ajax({
                url: "upload_script1.php",
                type: "POST",
                data: frm,
                contentType: false,
                cache: false,
                processData: false,

                success: function (response) {
                    var JsonObject = JSON.parse(response);
                    $("#targetLayer").html(response);

                    var fl1 = "uploads/" + JsonObject.image1;
                    $("#my_image1").attr("src", fl1).height(100).width(100);
                     $("#my_image2").attr("src", fl2).height(100).width(100);
                }
            });
        }));



    });
</script>

upload_script1.php =>

<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';

    $uploadfile = $uploaddir . basename($_FILES['image1']['name']);
     $uploadfile2 = $uploaddir . basename($_FILES['image2']['name']);     
    move_uploaded_file($_FILES['image1']['tmp_name'], $uploadfile);
    move_uploaded_file($_FILES['image2']['tmp_name'], $uploadfile2);
    $image1 = $_FILES['image1']['name'];
    $image2 = $_FILES['image2']['name'];
    $images["image1"] = $image1;
     $images["image2"] = $image2;
    echo json_encode($images);
?>

Upvotes: 2

Dan Prince
Dan Prince

Reputation: 29999

Your FormData object is probably showing as empty because your browser doesn't support iterators.

Check out the methods compatibility table at MDN. Internally, the console will probably try to use the iterator exposed by the entries method to enumerate the properties.

I get the same result in Chromium 45.


As for simplifying the code, you can merge both functions and PHP scripts by parameterizing them.

function createFormHandler($form, url, $image) {
  $form.on('submit', function(e) {
    var frm = new FormData($form[0]);
    e.preventDefault();

    $.ajax({
      url: url,
      type: "POST",
      data: frm,
      contentType: false,
      cache: false,
      processData: false,
      success: function(response) {                
        var JsonObject = JSON.parse(response);              
        $("#targetLayer").html(response);
        var src = "uploads/" + JsonObject.image1;
        $image.attr("src", src).height(100).width(100);
      }           
    });
  });
}

createFormHandler($('#uploadForm1'), 'upload_script.php?id=1', $('#my_image1'));
createFormHandler($('#uploadForm2'), 'upload_script.php?id=2', $('#my_image2'));

Now the numeric id of each form is represented as a URL parameter, rather than having to be a separate script. You can merge both PHP files and use a single upload_script.php instead.

<?php
  $id = $_GET['id'];
  $uploaddir = '/var/www/html/file-upload/uploads/';
  $uploadfile = $uploaddir . basename($_FILES['image']['name']);
  move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile);

  $image = $_FILES['image']['name'];
  $images["image" . $id] = $image;
  echo json_encode($images);
?>

This lets you normalize the input names too.

<form id="uploadForm1" enctype="multipart/form-data">
  <input name="image" type="file" />
  <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
  <input name="image" type="file" />
  <input type="submit" value="Submit" />
</form>

Upvotes: 4

Alfred
Alfred

Reputation: 1296

I have modifid only the javascript part.

My example is...

<title>Upload File</title>
<div id="targetLayer">No Image</div>
<img id="my_image1" src=""/>
<img id="my_image2" src=""/>

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

<script type="text/javascript" src="jquery-1.11.3.js"></script>

<script type="text/javascript">

function fetch( type ) {

    var typeMap = {
        form1: { formId: 'uploadForm1', url: 'upload_script1.php', flKey: 'image1', imgId: 'my_image1' },
        form2: { formId: 'uploadForm2', url: 'upload_script2.php', flKey: 'image2', imgId: 'my_image2' }
    };

    var info = typeMap[ type ];
    if( ! info ) return console.error('no type: ' + type );

    $("#"+info.formId).on('submit',(function(e) {

        frm = new FormData($(this)[0]);
        console.log(frm);
        e.preventDefault();
        $.ajax({
            url: info.url,
            type: "POST",
            data:  frm,
            contentType: false,
            cache: false,
            processData:false,
            success: function(response){                
                var JsonObject = JSON.parse(response);              
                $("#targetLayer").html(response);

                var fl = "uploads/" + JsonObject[ info.flKey ];
                $("#"+info.imgId).attr("src",fl).height(100).width(100);
            }           
       });
    }));
}

$(document).ready(function (e) {    
    fetch( 'form1' );
    fetch( 'form2' );
});

</script>

Upvotes: 1

Related Questions