Form.serialize() does not work

Asked

Viewed 761 times

1

I am developing an application in which I have several tables and dialogs using the form.serialize(), but this particular one isn’t working and I can’t find the reason why.

Form:

<form id="formDialogOrdemServicoBuscaTopo">
        <span class="container">
            <span>
            <select id="selectOrdemServicoPesquisa" name="selectOrdemServicoPesquisa">
                <option value="numero">Número</option>
                <option value="cliente">Cliente</option>
                <option value="dataAbertura">Data Abertura</option>
                <option value="dataFechamento">Data Fechamento</option>
                <option value="equipamento">Equipamento</option>
                <option value="modelo">Modelo</option>
                <option value="nserie">Nº de Série</option>
            </select>
            </span>
            <span>&nbsp;</span>
            <span>
            <input type="text" id="inputOrdemServicoPesquisa" name="inputOrdemServicoPesquisa">
            </span>
            <span>&nbsp;</span>
            <span><button id="buttonOrdemServicoListaTipoPesquisa">Buscar</button></span>
        </span>
    </form>

Javascript code:

$("#buttonOrdemServicoListaTipoPesquisa").off("click").on("click", function(event){
    event.preventDefault();
    $.ajax({
        url : "ordemServicoCadastroBuscaTopo.php",
        type: "POST",
        dataType: "json",
        data : $("#formDialogOrdemServicoBuscaTopo").serialize(),
        success: function(data)
        {
            $("#divListaOrdemServico").html('');
            $.each(data, function(index, val) {
                $("#divListaOrdemServico").append("<tr><td>"+val.id+
                "</td><td>"+val.nome+"</td><td>"+val.equipamento+"</td><td>"+val.marca+"</td><td>"+val.modelo+"</td><td>"+val.nserie+"</td><td>"+val.dataAbertura+"</td><td>"+val.dataFechamento+"</td></tr>"
                );
            });
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert( jqXHR.responseText);
        }
    });
});

PHP code:

<?PHP
header('Content-Type: application/json');
include("dbConn.php");

$tipoPesquisa = $_POST['selectOrdemServicoPesquisa'];
$dadoPesquisa = $_POST['inputOrdemServicoPesquisa'];

if($tipoPesquisa == 'numero')
    $sqlSelect = "SELECT * FROM `ordemservico` WHERE id LIKE '%$dadoPesquisa%'";

if($tipoPesquisa == 'cliente')
    $sqlSelect = "SELECT * FROM `ordemservico` WHERE tipo LIKE '%$dadoPesquisa%'";  

if($tipoPesquisa == 'equipamento')
    $sqlSelect = "SELECT * FROM `ordemservico` WHERE equipamento LIKE '%$dadoPesquisa%'";

if($tipoPesquisa == 'modelo')
    $sqlSelect = "SELECT * FROM `ordemservico` WHERE modelo LIKE '%$dadoPesquisa%'";

if($tipoPesquisa == 'nserie')
    $sqlSelect = "SELECT * FROM `ordemservico` WHERE nserie LIKE '%$dadoPesquisa%'";        

if($tipoPesquisa == 'dataAbertura')
    $sqlSelect = "SELECT * FROM `ordemservico` WHERE dataAbertura LIKE '%$dadoPesquisa%'";  

if($tipoPesquisa == 'dataFechamento')
    $sqlSelect = "SELECT * FROM `ordemservico` WHERE dataFechamento LIKE '%$dadoPesquisa%'";

if($tipoPesquisa == '')
    $sqlSelect = "SELECT * FROM `ordemservico` ORDER BY nome ASC";

$result = mysqli_query($conn, $sqlSelect);

$rows = array();
while($row = mysqli_fetch_assoc($result)){
    $rows[] = $row;
}

echo json_encode($rows);

mysqli_close($conn);
?>

Error returned:

<br />
<b>Notice</b>:  Undefined index: selectOrdemServicoPesquisa in        <b>Z:\web\ManutencaoNET\ordemServicoCadastroBuscaTopo.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>:  Undefined index: inputOrdemServicoPesquisa in     <b>Z:\web\ManutencaoNET\ordemServicoCadastroBuscaTopo.php</b> on line <b>6</b><br />
<br />
<b>Warning</b>:  mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in <b>Z:\web\ManutencaoNET\ordemServicoCadastroBuscaTopo.php</b> on line     <b>35</b><br />
  • What you get if you do var_dump($tipoPesquisa); in PHP? how do you know it is .serialize() that doesn’t work?

  • Nothing happens with var_dump. PHP error tells me that the two form variables are not sent.

  • NOTE: All other dialogs and $.ajax are working correctly. And they are the same, just changing the variable names.

  • say that "$. ajax are working properly" and that var_dump($tipoPesquisa); "Nothing happens" is contradictory... How do you know that AJAX works? if it works var_dump should return something... if it does console.log(data); in the first line of the function success AJAX and put the var_dump I suggested, what do you get? (I’m assuming you know what the console is...)

  • At the risk of a guess, I would say that something more than mentioned, in this PHP file or another along the Request stream, is preventing the operation. I played your code by removing database interaction, of course, and a console.log(data) in the Success as @Sergio suggested, after submitting the form without filling anything, returns "SELECT * FROM ordemservic WHERE id LIKE '%%'" as expected. Yes, no, do your homework as a programmer and treat what comes from the user. Assume the user is smart and will not mess with the system is ask to fail.

  • this form is inside another form?

  • Go in parts, see what is the return of $("#formDialogOrdemServicoBuscaTopo"). serialize() in the console before submitting by ajax.

Show 2 more comments

3 answers

2

You should capture the Submit event from your form instead of clicking the button

$("#formDialogOrdemServicoBuscaTopo").submit(function(e){
     e.preventDefault();
     var dataSerialize = $(this).serialize();
});

1

Don’t forget to load the Jquery lib on your ok page!?

JS

I changed the $.ajax for $.post as this is most recommended in this case that you will only upload a DOM object with new content. Later you will notice that PHP will return the content ready because the loop is done in the backend (PHP) and brings the result ready to be inserted in div#divListaOrdemServico

$("#buttonOrdemServicoListaTipoPesquisa").off("click").on("click", function(event){
    event.preventDefault();

    var dataSerialize = $("#formDialogOrdemServicoBuscaTopo").serialize();

    $.post("ordemServicoCadastroBuscaTopo.php", dataSerialize, function(data) {
        $("#divListaOrdemServico").html(data);
    });
});

PHP

In PHP code I switched the if’s for just one switch, which is faster and makes the code somewhat cleaner, getting like this:

<?php
    include('dbConn.php');

    // Faz uma verificação se a variável foi passada, em caso negativo o valor fica vazio
    $tipoPesquisa = isset($_POST['selectOrdemServicoPesquisa']) ? $_POST['selectOrdemServicoPesquisa'] : '';
    $dadoPesquisa = isset($_POST['selectOrdemServicoPesquisa']) ? $_POST['inputOrdemServicoPesquisa'] : '';

    $sqlSelect = '';// inicia a variável $sqlSelect como vazia para gerar erros

    // switch com as opções da variável $tipoPesquisa
    switch($tipoPesquisa){
        case 'numero':
            $sqlSelect = 'SELECT * FROM `ordemservico` WHERE id LIKE "%' . $dadoPesquisa . '%"';
            break;
        case 'cliente':
            $sqlSelect = 'SELECT * FROM `ordemservico` WHERE tipo LIKE "%' . $dadoPesquisa . '%"';
            break;
        case 'equipamento':
            $sqlSelect = 'SELECT * FROM `ordemservico` WHERE equipamento LIKE "%' . $dadoPesquisa . '%"';
            break;
        case 'modelo':
            $sqlSelect = 'SELECT * FROM `ordemservico` WHERE modelo LIKE "%' . $dadoPesquisa . '%"';
            break;
        case 'nserie':
            $sqlSelect = 'SELECT * FROM `ordemservico` WHERE nserie LIKE "%' . $dadoPesquisa . '%"';
            break;
        case 'dataAbertura':
            $sqlSelect = 'SELECT * FROM `ordemservico` WHERE dataAbertura LIKE "%' . $dadoPesquisa . '%"'; 
            break;
        case 'dataFechamento':
            $sqlSelect = 'SELECT * FROM `ordemservico` WHERE dataFechamento LIKE "%' . $dadoPesquisa . '%"';
            break;
        default:
            $sqlSelect = 'SELECT * FROM `ordemservico` ORDER BY nome ASC';
    }

    $result = mysqli_query($conn, $sqlSelect);

    $rows = '';

    while($row = mysqli_fetch_assoc($result)){
        $rows .= '<tr>';
        $rows .= '<td>' . $row['id'] . '</td>';
        $rows .= '<td>' . $row['nome'] . '</td>';
        $rows .= '<td>' . $row['equipamento'] . '</td>';
        $rows .= '<td>' . $row['marca'] . '</td>';
        $rows .= '<td>' . $row['modelo'] . '</td>';
        $rows .= '<td>' . $row['nserie'] . '</td>';
        $rows .= '<td>' . $row['dataAbertura'] . '</td>';
        $rows .= '<td>' . $row['dataFechamento'] . '</td>';
        $rows .= '</tr>';
    }

    echo $rows;

    mysqli_close($conn);

1

Your code seems to be correct, if it is to kick something I believe that maybe you have two presses with this id, or any other div, and that in this way, has no value selected or does not have these fields.

Do a test, change the id of this form to some other name and try again.

See also what serialize is returning, because if it is error in javascript you can at least stop investigating php for now.

Browser other questions tagged

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