简体   繁体   中英

How can I pass extra variables with image over an AJAX call

I've looked around but I can't seem to find a solution to this. I'm a newbie when it comes to AJAX/PHP so please forgive me if this is a simple question.

I have this AJAX that is supposed to grab the image uploaded in a form and pass it to the handler to copy on server.

My indexing system is verified on the client side, so I need to be able to pass the Id variable to rename the file. Here's the AJAX code:

    var input = document.getElementById("imgBrw");
    file = input.files[0];
    if (file !== undefined) {
        formData = new FormData();
        if (!!file.type.match(/image.*/)) {
            formData.append("image", file);
            console.log(formData);
            $.ajax({
                url: "file_handler.php",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                success: function () {
                    console.log('img copied');
                }
            });
        } else {
            alert('Not a valid image!');
        }
    } else {
        console.log('No image change');
    }

And here is my PHP:

$name = $_POST["articleA"];
$dir = "img/content/$name";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir);

As you can see there is no articleA variable in the AJAX, but when I try to add it to data it doesn't write the image at all, like so:

 data:{formData:formData, articleA: articleA}

My question is how to pass the articleA variable alongside the image data in formData.

Got it! In the end I left:

formData.append("image", file);  

and added another:

formData.append("nameA", articleA);  

On the PHP side simply got it on POST:

$name = $_POST['nameA'];
$dir = "img/content/$name";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir);
$.ajax({
                type: "POST",
                url: "insert_record.php",
                 //dataType:'json',
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,
                success: function(data) {
                    alert("OK");
                }
            });

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