Form.serialize () does not work

1

I'm developing an application in which I have multiple tables and dialogs using form.serialize() , but that particular one is not working and I can not find the reason.

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 />
    
asked by anonymous 06.12.2014 / 12:22

3 answers

2

You should capture the submit event of your form instead of the button click

$("#formDialogOrdemServicoBuscaTopo").submit(function(e){
     e.preventDefault();
     var dataSerialize = $(this).serialize();
});
    
16.07.2015 / 13:10
1
  

Do not forget to load the JQuery lib on your page ok!?

JS

I changed $ ajax to $. post because this is most recommended in this case that you will only load a DOM object with new content. Later on 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 into the div

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

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

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

PHP

In the PHP code I changed the if's to just one switch, which is faster and makes the code somehow cleaner, thus:

<?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);
    
11.12.2014 / 10:27
1

Your code seems to be correct, if I'm going to kick something, I think maybe you have two forms with this id, or some other div, and that way you have no selected values or do not have those fields.

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

Also see what the serialize is returning, because if it is a javascript error you can at least stop investigating php for now.

    
11.12.2014 / 14:20