3

Meanwhile I'm getting stuck on this issue. Normally, it's pretty simple but somehow it doesn't work for what I'm trying to do. I want to get all data from my form input fields by either Jquery or JS and then send them through AJAX to the server sided script (PHP). Even by using append or do it by serialize, I only obtain the object from input field with ID #file. I'm not using a submit button to confirm the uploaded image - only select the file and send it off.

I already tried too add

formdata.append("_token", document.getElementById('_token').val());

but whenever I try to append another element to the formdata the entire script stops working

By using $('#picUploadForm').serialize(); I do not get the any result from the input element with ID #file.

HTML:

<form enctype="multipart/form-data" id="picUploadForm">
   <input type="file" name="file" id="file" style="display:none;" >
   <input type="hidden" name="_token" id="_token" value="<?php echo $_SESSION['_token']; ?>" />
</form>
<!-- Default Avatar Image -->
   <div class="click-slide overlay">
<!-- Profile Image-->
   <img src="<?php if(isset($avatar['filelink']) && $avatar['filelink'] !='') { echo $avatar['filelink']; } else { echo "assets/images/avatars/default_avatar_large.png"; }?>" alt="" class="img-full-width-tight" id="imagePreview" />
<!-- Image update link -->
    <div id="editLink" >
      <span>
        <a href="javascript:void(0);" class="pop-inline ti ti-image" ></a>
       </span>
    </div>
</div><!--/ click-slide-->

JS:

//On select file to upload
 $('#file').on('change', function(e){

      e.preventDefault();
      var formdata = new FormData();
     // any other code here....

            } else {

            // Upload Image to backend

          formdata.append("file", document.getElementById('file').files[0]);

// formdata.append("_token", document.getElementById('_token').val()); // does not work!!!

// $('#picUploadForm').serialize(); // only returns data from input #_token


            $.ajax({
            url: "./serversided.php",
            type: "POST",
            data: formdata,
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,      
            beforeSend: function(){
                $("#statusav").removeClass().html('');
                $('.overlay').LoadingOverlay("show");
                HideLoadingOverlay();   
            },
            success: function(data){
                if(data.status === true){

                    // alert(data.imgURL);
                    setTimeout(function(){$("#statusav").removeClass('alert alert-danger').addClass('alert alert-success').html(data.reply)}, 2000);
                    $("#imagePreview").attr('src', data.imgURL);

              } else {

                    // alert(data.error);
                    setTimeout(function(){$("#statusav").removeClass('alert alert-success').addClass('alert alert-danger').html(data.error)}, 2000);

          }
        }
    });
   }
}); 
1
  • .val() is a jQuery method. And data from file select elements is not serialized. From MDN Commented Apr 15, 2018 at 5:06

1 Answer 1

2

.val() is a jQuery method - it is not a vanilla JS method, so it doesn't work when called on a plain element. document.getElementById will return an element (or null); $('selectors here') will return a jQuery object, on which you can use jQuery functions.

Try this instead, with vanilla JS:

formdata.append("_token", document.querySelector('#_token').value);

Or select the element with jQuery and use the jQuery method:

formdata.append("_token", $('#_token').val());
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that was helpful, indeed. thanks. I have to stick a little more to that Vanilla JS and all those methods. Little confusing sometimes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.