简体   繁体   中英

ajax send file and variable to php

I'm using an ajax call to upload a file, handled by PHP. The file should be placed in a specific directory based on a jquery variable. I can get the file to upload, but cannot pass the variable along with the file. PHP reports an undefined index error.

Ajax code:

var fd = new FormData();    
fd.append( 'file', document.getElementById('select').files[0]);
$.ajax({
    url: 'test.php',
    type: 'POST',
    data: fd,
    processData: false,
    contentType: false,
    success: function(e){
        // some code here
    }
});     

I tried changing the data property to "fd+'&myVar='+myVar, however PHP cannot parse the data correctly and returns undefined index error for both the $_FILES['file'] variable as well as the $_POST['myVar'] variable.

How can I send both the file and a variable?

If you need another form field, call fd.append a second time:

fd.append('file', document.getElementById('select').files[0]);
fd.append('myVar',myVar);

You can append values other than files to a formdata object.

var fd = new FormData();    
fd.append( 'file', document.getElementById('select').files[0]);
fd.append( 'myVar', myVar);
$.ajax({
    url: 'test.php',
    type: 'POST',
    data: fd,
    processData: false,
    contentType: false,
    success: function(e){
        // some code here
    }
});     

Refer to $.ajax jQuery API Documentation.

It is clearly stated that data should be an object with key-value pairs representing data accepted by server-side script. Whatever, not sure why jQuery seems to not accept your data. Maybe you should try this out manually.

Since your test.php accepts POST data as myVar your jQuery Ajax configuration should probably look like

$.ajax({
    url: 'test.php',
    type: 'POST',
    data: {
        myVar: document.getElementById('select').files[0]
    },
    success: function(e){
    // some code here
    }
});     

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