Search code examples
javascriptphpform-data

how to add a variable to formData and ajax procedure


<input type='file' name='inpfile' id='inpfile' accept='image/*' hidden>

js

var clicked;
$('#btnplusa').click(function(){
    clicked = 'a';
    $('#inpfile').click();
});

I want to add clicked variable and proccess it on php side, together with inpfile data.

$('#inpfile').change(function(){
    var file_data = $('#inpfile').prop('files')[0];
    var form_data = new FormData();
    form_data.append('inpfile', file_data, 'clicked', clicked);
    $.ajax({
        url: "banners-pro-btnplus.php",
        type: 'post',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        success: function(data) {
            console.log(data);
        }
    });
});

banners-pro-btnplus.php

$file = $_FILES['inpfile'];

$clicked =  $_POST['clicked'];
echo $clicked;
exit();

Console:

Undefined index: clicked in...

How can I get clicked variable on php side?


Solution

  •  <!DOCTYPE html>
        <html>
        <head>
            <title></title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <script type="text/javascript">
                let clicked
                $(document).ready(function(){
    
                    $('#inpfile').change( function ( ){
                        console.log(clicked)
    var file_data = $('#inpfile').prop('files')[0];
         var form_data = new FormData();
            form_data.set('inpfile', file_data , file_data.name );
         form_data.append( 'clicked', clicked);
            $.ajax({
                url: "banners-pro-btnplus.php",
                type: 'post',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                success: function(data) {
                    console.log(data);
                }
            });
                    })
                })
                function bttn_click(){
                    clicked = 'a';
    
                    document.getElementById('inpfile').click();
                }
            </script>
        </head>
        <body>
            <form>
                <input type="file" name="" id="inpfile">
                <button onclick="bttn_click()"  >Browse</button>
            </form>
        </body>
        </html>
    

    You can try this way