Send Object and Variable at the same time using ajax in jQuery

Hi E's,
I try to get a solution for send via Jquery ajax a object and a variable at the same call.
This is the code I have when the data is one object:
var file_data = $('#imagem').prop('files')[0];    
                    var form_data = new FormData();                  
                    form_data.append('file', file_data);                            
                    $.ajax({
                        url: 'ajax_upload.php', 
                        dataType: 'text',  
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,                         
                        type: 'post',
                        success: function(php_script_response){
                            alert(php_script_response); //
                        }
                    });

Open in new window

In above code "form_data" contain the information of a upload file.
My problem is, I have a simple variable to send in the same call, and usually when I send variables I use "data" like this: data: {"var":value},.
But I don't know send both, object and variable.
I need some solution that send both things, like this: data: {"var":valor, "var":valor},+form_data;

Can you help me please?!

The best regards, JC
LVL 4
Pedro ChagasWebmasterAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ares KurkluSoftware EngineerCommented:
can you maybe use this?
form_data.append('abc', '123')
1
Pedro ChagasWebmasterAuthor Commented:
This is my entire code, index.php and ajax_upload.php:(index)
<!DOCTYPE html>
  <html>
    <head>
        <meta charset="UTF-8">
      <!--Import Google Icon Font-->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!--Import materialize.css-->
      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>

      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <div class="container">
        <div class="row" style="margin-top:80px;">
            <div class="col s12 center-align"><h4>Adaptação de Imagem</h4></div>
        </div>
        
        <div class="row">
            <form class="col s12" id="formulario">
                <div class="row">
                    <div class="file-field input-field">
                        <div class="btn">
                            <span>Imagem</span>
                            <input type="file" id="imagem" name="imagem">
                        </div>
                        <div class="file-path-wrapper">
                            <input class="file-path validate" type="text">
                        </div>
                    </div>
                </div>
                
                <div class="row">
                <div class="col s12 left-align blue-text"><h6>temas:</h6></div>
                </div>
                    <div class="row">
                        <p>
                            <input name="negocio" type="radio" id="vedacoes" value="vedacoes"/>
                            <label for="vedacoes">Vedações</label>
                        </p>
                        <p>
                            <input name="negocio" type="radio" id="automatismos" value="automatismos"/>
                            <label for="automatismos">Automatismos</label>
                        </p>
                        <p>
                            <input name="negocio" type="radio" id="drogaria"  value="drogaria"/>
                            <label for="drogaria">Drogaria</label>
                        </p>
                        <p>
                            <input name="negocio" type="radio" id="simples"  value="simples"/>
                            <label for="simples">Simples</label>
                        </p>
                    </div>
                <div class="row">
                    <div class="col s12 right-align"><a class="waves-effect waves-light btn blue" onclick="recebe();">Transformar</a></div>
                </div>
            </form>
        </div>
        </div>
    
    
    
      <!--Import jQuery before materialize.js-->
      <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
      <script type="text/javascript" src="js/materialize.min.js"></script>
      <script>
      function recebe(){
          var tema = $('input[name=negocio]:checked').val()
          var ficheiro = $("#imagem").val();
          if(ficheiro == ""){
              alert("Erro:\nSeleccione uma Imagem");
          }else if(tema == null){
              alert("Erro:\nSeleccione o Tema");
          }else{
              var hello = "sim";
                    var file_data = $('#imagem').prop('files')[0];   
                    var form_data = new FormData();                  
                    form_data.append('file', file_data);                            
                    $.ajax({
                        url: 'ajax_upload.php', // point to server-side PHP script 
                        dataType: 'text',  // what to expect back from the PHP script, if anything
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,                         
                        type: 'post',
                        success: function(php_script_response){
                            alert(php_script_response); // display response from the PHP script, if any
                        }
                    }); 
          }
      }
      
      </script>
    </body>
  </html>

Open in new window

(ajax_upload)
<?
    print_r($_POST[form_data]);
    exit;
    $extensao = pathinfo($_FILES['file']['name']);
    $extensao = $extensao[extension];
    $extensao = mb_strtolower($extensao, 'UTF-8');
    if($extensao == "jpg" || $extensao == "jpeg" || $extensao == "png"){
        $size = $_FILES['file']['size'];
        if($size < 3000000){
        move_uploaded_file($_FILES['file']['tmp_name'], 'upload/' . $_FILES['file']['name']);    
        }else{
            echo "Erro:\nImagem Superior a 3MB";
            exit;
        }   
    }else{
        echo "Erro:\nnão se trata de uma imagem jpg nem png. Verifique o ficheiro seleccionado.";
        exit;
    }
    
    //Se passou a primeira fase, onde foi checado se é uma imagem jpg ou png e também se é menor do que 3MB, falta fazer a checagem se estamos perante uma imagem landscape
    $nome = $_FILES['file']['name'];
    $caminho = "upload/" . $nome;
    $tamanho = getimagesize($caminho);
    if($tamanho[0] > $tamanho[1]){
        echo "ok";
    }else{
        echo "noK";
    }
?>

Open in new window

The goal is upload a picture via ajax, and at the same time I have to send the variable "tema" in the call.
It's possible, and how?
Thanks.

~JC
0
Chris StanyonWebDevCommented:
You've already been shown how to add the variable to the form_data:

var file_data = $('#imagem').prop('files')[0];   
var form_data = new FormData();                  
form_data.append('file', file_data);
form_data.append('tema', tema);

Open in new window

As for your AJAX Upload file, remove the first 2 lines. Change Line 5 to:

$extensao = $extensao["extension"];

And right at the start of your script add the following:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Open in new window

Now run your script and let us know if you get any errors
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Pedro ChagasWebmasterAuthor Commented:
Thank you!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Development

From novice to tech pro — start learning today.