Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax: add a variable to a formData

I got a jQuery script which sends info about a picture to a php file through a "formData" variable, like this:

    url: 'ajax.php',
    type: "POST",
    contentType:false,
    processData: false,
    cache: false,
    data: formData,
    success: function(data){}

As far as I know, here is the part of the script that generates the content of that formData before it is sent:

function handleFileUpload(files,obj)
{
    for (var i = 0; i < files.length; i++) 
    {
        var fd = new FormData();
        fd.append('file', files[i]);
        var status = new createStatusbar(obj);
        status.setFileNameSize(files[i].name,files[i].size);
        sendFileToServer(fd,status);
    }
}

To catch that data in the php file, I just use

$_FILES['file'][...];

What I would like to do is to simultaneously send an additional javascript variable to the php file, along with the formData, that I would be able to catch as

$_POST['picID'];

How would I do that?

Thank you.

PS the additional javascript variable "picID" is defined at the beginning of the root of the js file so, it should normally be accessible from within any function in that file.

like image 954
Bachir Messaouri Avatar asked Aug 31 '25 02:08

Bachir Messaouri


1 Answers

You can append as many key => value to the form data.

fd.append('key',  value); 

Applying to your scenario,

fd.append('picID', value); //where value is the value of picID

I would recommend that you declare the form data variable fd before the for loop begins. This is because only the file data requires the loop. For additional form data, append them outside the loop

Example

function handleUpload(){
var fd = new FormData();
//commence for loop {

  // }end for loop
   //append extra key => value 
  fd.append('key', value); 
   }
like image 183
Rotimi Avatar answered Sep 02 '25 15:09

Rotimi