简体   繁体   中英

Uploading file through ajax and jquery

Good evening guys, I got a problem in the back-end of my system when I submit my form. It said Unidentified index: file1 . I can't fine the error here in my code. I'm not a newbie in javascript and seeking for help from you guys. Advance thank you.

So here is my HTML form

<form id="submit_form" action="<?php echo base_url()?>Homepage/add_blog" enctype="multipart/form-data" method="POST" >
    <input type="text" class="form-control" id="title" name="title" autocomplete="off">
    <input type="text" class="form-control" id="lead" name="lead" autocomplete="off">
    <input type="text" id="tags" name="tags"  data-role="tagsinput" placeholder="Add tags" class="form-control" >
    <input type="file" id="file1" name="file1"  >
    <textarea id="content" name="content" rows="10" cols="80">
      Put the content here!!!
    </textarea>
</form>

Here is my script

<script>
  function _(el)
  {
    return document.getElementById(el);
  }
  $(document).ready(function()
  {
    $('#submit').click(function(e)
    {
       e.preventDefault();
      var file = _("file1").files[0];
      var title = $('#title').val();
      var lead = $('#lead').val();
      var tags = $('#tags').val();
      var content = $('#content').val();

      if(title == '' || lead == '' || tags == '' || content =='')
      {
        $('#response').html('<br><div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div>');
        $('#response2').html('<div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div><br>');
      }
      else
      {
        $.ajax({
          url:"<?php echo base_url()?>Homepage/add_blog",
          method:"POST",
          data:$('#submit_form').serialize(),
          beforeSend:function()
          {
            $('response').html('<span class="text-danger">Loading...</span>');
            $('#submit').prop("disabled", true);
            var formdata = new FormData();
            formdata.append("file1",file);
            var ajax = new XMLHttpRequest();
            ajax.upload.addEventListener("progress",progressHandler,false);
            ajax.addEventListener("load",completeHandler,false);
            ajax.addEventListener("error",errorHandler,false);
            ajax.addEventListener("error",abortHandler,false);
            ajax.open("POST","<?php echo base_url()?>Homepage/add_blog");
            ajax.send(formdata);
          },
          success:function(data)
          {
            $('form').trigger("reset");
           $('#tags').tagsinput('removeAll');
           $('#tags').tagsinput('destroy');
            CKEDITOR.instances.content.setData('');
            $('#response').fadeIn().html(data);

          }
        });
      }
    });
    $('#title,#lead,#tags,#content').focus(function(){
      $('#submit').prop("disabled", false);
    });
  });
  function progressHandler(event)
  {
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded;
    var percent = (event.loaded/event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded.. please wait";
  }
  function completeHandler(event)
  {
    _("progressBar").value = 0;
  }
  function errorHandler(event)
  {
    _("status").innerHTML = "Upload Failed.";
  }
  function abortHandler(event)
  {
    _("status").innerHTML = "Upload Aborted.";
  }
</script>

And the problem relies here in the back-end Homepage/add_blog:

$filename = $_FILES["file1"]["name"];
echo $filename;

If you any more details needed to solve this. Just comment. Need to fix this as soon as possible. Thank you again.

Undefined index notice that the array $_FILES does not contain the "file1" key set. Probably the way you are trying to send the file via ajax is not working properly.

I'd recommend you try to use FormData. I believe the link below is a good reference to solve your problem.

How to use FormData for ajax file upload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM