简体   繁体   中英

File upload using Jquery ajax without form

Here is mycode

function addPackage(elem)
{

    var dataimg = new FormData();
    dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
    var startdate=$("#from_date"+elem).val();
    var enddate=$("#to_date"+elem).val();
     $.ajax({
      url: "addpackage/",
      type:"post",
      contentType:false,
      data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
      success: function(data) {
      }
    });
}

I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object] . How to post image with input field without for in jquery ajax.

You can do it like following. Hope this will help you.

function addPackage(elem)
{
    var dataimg = new FormData();
    dataimg.append('startdate', $("#from_date"+elem).val());
    dataimg.append('enddate', $("#to_date"+elem).val());
    dataimg.append('packageid', elem);
    dataimg.append('img', $("#browseimg"+elem)[0].files[0]);

    $.ajax({
        url: "addpackage/",
        type:"post",
        cache : false,
        contentType : false,
        processType : false,
        data: dataimg,
        success: function(data) {
        }
    });
}

You can try this:

Your JS Code:

<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
    type: "POST",
    url: url,
    data:  data,
    enctype: 'multipart/form-data',
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    dataType: "json",
    success: function(response)
    {
        // some code after succes from php
    },
    beforeSend: function()
    {
        // some code before request send if required like LOADING....
    }
});
</script>

Dummy HTML:

<form method="post" action="addpackage/" id="yourFormID">
    <input type="text" name="firstvalue" value="some value">
    <input type="text" name="secondvalue" value="some value">
    <input type="file" name="imagevalue">
</form>

in addpackage php file:

print_r($_POST);
print_r($_FILES);

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