Variable does not go to PHP with Ajax

0

I have this code that requests with Ajax for a PHP file. The problem is that you are only getting the input type="file" value, the other fields are not being passed to PHP.

I'm doing this to get the input value

var valor = $("input[name=nome]").val();
//mostra o valor com alert()
alert(valor);

How can I get all the form fields?

My js

$(document).ready(function() {

            $('.contato_form').validate({ // initialize the plugin
                rules: {
                    email: {
                        required: true,
                        email: true
                    },
                    nome: {
                        required: true,
                        minlength: 5
                    }
                },


                messages: {
                    required: "Campo obrigatório",
                    remote: "Please fix this field.",
                    email: "Por favor insira um email válido",
                    url: "Please enter a valid URL.",
                    date: "Please enter a valid date.",
                    dateISO: "Please enter a valid date (ISO).",
                    number: "Please enter a valid number.",
                    digits: "Please enter only digits.",
                    equalTo: "Please enter the same value again.",
                    maxlength: $.validator.format("Não insira mais do que {0} caracteres."),
                    minlength: $.validator.format("Digite pelo menos {0} caracteres."),
                    rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
                    range: $.validator.format("Please enter a value between {0} and {1}."),
                    max: $.validator.format("Please enter a value less than or equal to {0}."),
                    min: $.validator.format("Please enter a value greater than or equal to {0}."),
                    step: $.validator.format("Please enter a multiple of {0}.")
                },



                submitHandler: function(form) { // for demo
                    $(".resultado_contato_fom").html('<div class="spinner"></div>');
                    var form = $('.contato_form');

                    var valor = $("input[name=nome]").val();
                    //mostramos o valor com alert()
                    alert(valor);


                    var file_data = $('#file-upload').prop('files')[0];
                    var form_data = new FormData();


                    form_data.append('file-upload', file_data);
                    //alert(form_data);                             
                    $.ajax({
                            url: 'http://xxx.com.br/email_contato.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
                                // pegando os dados

                            }

                        })




                        .done(function(data) {
                            $('.resultado_contato_fom').fadeOut('slow', function() {
                                $('.resultado_contato_fom').fadeIn('slow').html(data);


                            });
                        })
                        .fail(function() {
                            alert('Ajax Submit Failed ...');
                        });
                    return false; // for demo
                }
            });

});

My Html form

    <form action="" id="contato_formulario" method="post" name="contato_form" class="contato_form" novalidate="novalidate" enctype="multipart/form-data">

<div cla="row">
<div class="col-md-6 formulario" >
<input type="text" name="nome" id="nome" value="" size="40" class="" aria-required="true" aria-invalid="false" placeholder="Nome" style="
    width: 96%;
">
</div>
<div class="col-md-6 formulario">
<input type="text" name="telefone" id="telefone" value="" size="40" class="" aria-required="true" aria-invalid="false" placeholder="Telefone">
</div>
</div>


<div cla="row">
<div class="col-md-12 formulario">
<input type="text" name="email" value="" id="email" size="40" class="" aria-required="true" aria-invalid="false" placeholder="Email">
</div>
</div>



<div cla="row">
<div class="col-md-12 formulario">
<textarea name="mensagem" cols="40" rows="10" id="mensagem" class="" id="" aria-invalid="false" placeholder="Mensagem"></textarea>
</div>
</div>

<div cla="row">
<div class="col-md-6 center"> 
<label for="file-upload" class="custom-file-upload"><p></p><div class="botao_anexar_form botao_form vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-square vc_btn3-style-modern vc_btn3-color-grey"><i style="color: #4a0743 !important;    font-weight: lighter;font-size: 19px;" class="fa fa-paperclip"></i> Anexar Arquivo</div><p><br> <span class="wpcf7-form-control-wrap file-612"><input type="file" name="file-upload" size="40" class="wpcf7-form-control wpcf7-file" id="file-upload" aria-invalid="false"></span></p></label></div>

<div class="col-md-6 center">
<button type="submit" class="botao_enviar_form vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-square vc_btn3-style-modern vc_btn3-color-grey">enviar</button>
</div>
</div>

<div cla="row">
<div class="col-md-12 center resultado_contato_fom">
</div>
</div>

</form>

My PHP

if(isset($_FILES['file-upload']))
   {
      date_default_timezone_set("Brazil/East"); //Definindo timezone padrão

      $ext = strtolower(substr($_FILES['file-upload']['name'],-4)); //Pegando extensão do arquivo
      $new_name = date("Y.m.d-H.i.s") . $ext; //Definindo um novo nome para o arquivo
      $dir = $_SERVER['DOCUMENT_ROOT'].'wp-content/uploads/'; //Diretório para uploads

      move_uploaded_file($_FILES['file-upload']['tmp_name'], $dir.$new_name); //Fazer upload do arquivo
   }

I tried this way more did not work either

$(document).ready(function() {

            $('#contato_formulario').validate({ // initialize the plugin
                rules: {
                    email: {
                        required: true,
                        email: true
                    },
                    nome: {
                        required: true,
                        minlength: 5
                    }
                },


                messages: {
                    required: "Campo obrigatório",
                    remote: "Please fix this field.",
                    email: "Por favor insira um email válido",
                    url: "Please enter a valid URL.",
                    date: "Please enter a valid date.",
                    dateISO: "Please enter a valid date (ISO).",
                    number: "Please enter a valid number.",
                    digits: "Please enter only digits.",
                    equalTo: "Please enter the same value again.",
                    maxlength: $.validator.format("Não insira mais do que {0} caracteres."),
                    minlength: $.validator.format("Digite pelo menos {0} caracteres."),
                    rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
                    range: $.validator.format("Please enter a value between {0} and {1}."),
                    max: $.validator.format("Please enter a value less than or equal to {0}."),
                    min: $.validator.format("Please enter a value greater than or equal to {0}."),
                    step: $.validator.format("Please enter a multiple of {0}.")
                },



                submitHandler: function(form) { // for demo
                    $(".resultado_contato_fom").html('<div class="spinner"></div>');
                    var form = $('#contato_formulario');

                    var valor = $("input[name=nome]").val();
                    //mostramos o valor com alert()
                    alert(valor);


                    var file_data = $('#file-upload').prop('files')[0];
                    var form_data = new FormData();


                    form_data.append('file-upload', file_data);
                    //alert(form_data);                             
                    $.ajax({
                            url: 'http://xxx.com.br/email_contato.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
                                // pegando os dados

                            }

                        })




                        .done(function(data) {
                            $('.resultado_contato_fom').fadeOut('slow', function() {
                                $('.resultado_contato_fom').fadeIn('slow').html(data);


                            });
                        })
                        .fail(function() {
                            alert('Ajax Submit Failed ...');
                        });
                    return false; // for demo
                }
            });

});
    
asked by anonymous 01.03.2018 / 12:41

2 answers

0

The reason you're only getting the value of the input type="file", as you said, is because you're declaring a form, and putting only that variable in it:

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

What you can do:

1 - Assign an id to your form: Example:

<form id="formSave" action="" method="post" class="contato_form" novalidate="novalidate" enctype="multipart/form-data">

2 - Next, structure your request as follows:

$('#formSave').validate({
    submitHandler: function (form) {
        $(form).ajaxSubmit({
            url: 'http://xxx.com.br/email_contato.php',
            type: 'post',
            resetForm: true,
            beforeSerialize: function () {

            },
            success: function () {

            }
        });
        return false;
    },
    rules: {
            // ...
    },
    messages: {
            // ...
    }
    });
    
01.03.2018 / 14:05
0

Here is a generic routine of mine to give submit in all elements of the form

      var Elementos = {};
      function sendForm(){

        form = document.forms[0];
        for(var i=0; i<form.length; i++){
          Elementos[form.elements[i].name] = form.elements[i].value;
        }

        var xhr = new XMLHttpRequest();
        var url = 'http://localhost/DashboardMarketingPlace/produto/';
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Content-type", "application/json");

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
              // console.log('Resposta PHP: ' + xhr.responseText);
              document.getElementById('demo').innerHTML = xhr.responseText;
            }
        };

        var data = JSON.stringify('1');
        xhr.send(data);

      }
    
01.03.2018 / 15:34