Pass two variables together with the form through the ajax

Asked

Viewed 77 times

2

I need to pass two more variables through ajax, I tried to do it this way:

JS:

var usuario_cod = document.getElementById("usuario_cod");
var line_cod = document.getElementById("line_cod");
...
$.ajax({

 url: "envio_anexo_processo.php",
 type: "POST",
 data: {'usuario_cod':usuario_cod,'line_cod':line_cod,formdata,},
...

HTML:

<fieldset>

    <div id="container" style="margin-top:50px;">

        <div class="col-sm-offset-2 col-sm-8">

            <div class="panel panel-default">

                <div class="panel-heading">

                    <h3 class="panel-title">Enviar arquivos em PDF</h3>

                </div>

                <div class="panel-body">

                    <form method="post" enctype="multipart/form-data"  action="/process_files.php">

                        <input type="file" name="files[]" id="input_files" multiple />

                        <input type="hidden" id="usuario_cod" name="usuario_cod" value="<?php echo mb_strtoupper ($usuario_cod);?>">

                        <input type="hidden" id="line_cod" name="line_cod" value="<?php echo mb_strtoupper ($line_cod);?>">
    
                        <button type="submit" id="btn_submit" class="form-control">Enviar Arquivos!</button>

                    </form>

                    <br />

                    <div id="loading_spinner"><i class="fa fa-spinner fa-pulse"></i> Enviando</div>

                    <div id="result"></div>

                </div>

            </div>

        </div>

    </div>

</fieldset>

<script type="text/javascript">

    function TransferCompleteCallback(content){
        // we might want to use the transferred content directly
        // for example to render an uploaded image
    }

    $( document ).ready(function(){

        var input = document.getElementById("input_files");
        var formdata = false;

        if(window.FormData){

            formdata = new FormData();
            $("#btn_submit").hide();
            $("#loading_spinner").hide();

        }

        $('#input_files').on('change',function(event){

            var i = 0, len = this.files.length, img, reader, file;
            //console.log('Number of files to upload: '+len);
            $('#result').html('');
            $('#input_files').prop('disabled',true);
            $("#loading_spinner").show();

            for( ; i < len; i++ ){

                file = this.files[i];
                //console.log(file);
                if(!!file.name.match(/.*\.pdf$/)){

                    if ( window.FileReader ){

                        reader = new FileReader();
                        reader.onloadend = function(e){ 

                            TransferCompleteCallback(e.target.result);

                        };

                        reader.readAsDataURL(file);

                    }

                    if (formdata){

                        formdata.append("files[]", file);

                    }

                } else{

                    $("#loading_spinner").hide();
                    $('#input_files').val('').prop('disabled',false);
                    alert(file.name+' Não é um PDF');

                }

            }

            var usuario_cod = $('#usuario_cod').val();

            if (formdata){

                $.ajax({
                    
                    url: "envio_anexo_processo.php",
                    type: "POST",
                    data: formdata,
                    processData: false,
                    contentType: false, // this is important!!!

                    success: function (res){

                        //alert(data);

                        var result = JSON.parse(res);
                        $("#loading_spinner").hide();
                        $('#input_files').val('').prop('disabled',false);

                        if(result.res === true){

                            var buf = '<ul class="list-group">';

                            for(var x=0; x<result.data.length; x++){

                                buf+='<li class="list-group-item">'+result.data[x]+'</li>';

                            }

                            buf += '</ul>';
                            $('#result').html('<strong>Arquivos enviados:</strong>'+buf);

                        } else{

                            $('#result').html(result.data);

                        }

                        // reset formdata
                        formdata = false;
                        formdata = new FormData();

                    }

                });

            }

            return false;

        });

    });

</script>

It didn’t work, as I do to send two variables?

  • If you are a beginner, it would be a good alternative to see a library called "Axios" https://github.com/axios/axios : )

3 answers

1


Since you are sending a formData, to upload the file, you need to add these two variables inside it. You can do it this way:

var usuario_cod = document.getElementById("usuario_cod");
var line_cod = document.getElementById("line_cod");
...

formdata.append('usuario_cod', usuario_cod)
formdata.append('line_cod', line_cod)

$.ajax({

 url: "envio_anexo_processo.php",
 type: "POST",
 data: formdata,
...

This way it would be as if your form had two other inputs inside it.

0

So come on, I’ll split the answer into two parts

First:

To send the ajax we will use a format called JSON, for it to be valid we need some things

He must be among { }

{

}

Properties should be separated by ,

{
   propriedade: "Valor1",
   propriedade2: "Valor2"
}

And the last element can’t have a comma

{
   propriedade: "Valor1",
   propriedade2: "Valor2"
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

Second:

With that in mind, we’d have to change a few things

var usuario_cod = document.getElementById("usuario_cod");
var line_cod = document.getElementById("line_cod");
...

let AjaxRequest = { 
   usuario_cod: usuario_cod,
   line_cod   : line_cod
}
$.ajax({

 url: "envio_anexo_processo.php",
 type: "POST",
 data: AjaxRequest,
...

References: https://www.w3schools.com/jquery/jquery_ajax_get_post.asp

0

Alternatively, you can use Método serialize() - this method eliminates the need to store data, one by one in variables, doing this process automatically and simply.

This method is intended to collect the values entered by the user in form fields and turn them into string format.

Data serialization is done in order to structure the data in an appropriate way, to be sent to the server. The serialization format is supported and accepted by most server-side programming languages as well as frameworks.

For the method to serialize() to work, it is necessary that the input fields of the data to be serialized are marked with the attribute name.

JS

var serializeDados = $('#idForm').serialize();

$.ajax({

 url: "envio_anexo_processo.php",
 type: "POST",
 data: serializeDados,
...

HTML

<form id="idForm" .....

PHP something like that

$usuario_cod = strip_tags($_POST['usuario_cod']); 
$line_cod = strip_tags($_POST['line_cod]); 


See an example with the serialize method()

$(document).ready(function(){
  $("button").click(function(){
    $("div").text($("#idForm").serialize());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="idForm" action="">
<input type="hidden" id="usuario_cod" name="usuario_cod" value="Codigo_123">

<input type="hidden" id="line_cod" name="line_cod" value="Linha_456">
    
</form>

<button>Serialize values do formulário</button>

<div></div>

  • I tried it this way but it’s not working when you put the pdf file to go with it. I need to send the pdf + both variables. <input type="file" name="files[]" id="input_files" Multiple />

  • @gabrielb3rn, I get it, I just saw you asking "how do I send two variables?" and JS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.