Error with serialize () + PHP function

0

I'm using the serialize function to send data from a form to a PHP page:

index.php

<form id="formfeira" method="post">

      <div class="form-group">
        <label for="horario">Horário de funcionamento:</label>
        <input type="text" class="form-control" id="horario" name="horario" placeholder="das 8h às 18h">
      </div>

      <div class="form-group">
        <label for="pagamento">Formas de pagamento:</label>
        <input type="text" class="form-control" id="pagamento" name="pagamento" placeholder="à vista ou nos cartões Visa e Mastercard">
      </div>

      <div class="form-group">
        <label for="quem">Quem somos:</label>
        <textarea class="form-control" id="quem" name="quem" rows="3" placeholder="descreva aqui..."></textarea>
      </div>

      <button type="submit" class="btn btn-primary" onclick="salvaFeira()">Enviar dados</button>
    </form>

funcoes.js

$(document).ready(function(){});
function salvaFeira(){
  alert($("#formfeira").serialize()); //aqui funciona
  $.ajax({
    type: "POST",
    url: "salvarFeira.php",
    data: $("#formfeira").serialize(),
    success: function(data) {
      alert(data); //não chega aqui
    }
  });
}

save.php

<?php

include 'conexao.php';

$mysqli = new mysqli("localhost", "root", "", "feira");
$res = $mysqli->query("insert into feira (horario, formapagamento, quemsomos) values ('123', '456', '789')");

echo 'teste'; 
?>

I gave up trying to retrieve the data and I'm just doing a common insert and returning the word test

However, you are not saving to the database. If I directly run the file saveFeed.php, it saves the data in the database correctly.

What am I doing wrong?

    
asked by anonymous 18.01.2018 / 22:52

1 answer

1

I copied your code and tested it, what is wrong is that you have set the type element as submit to perform an ajax , the property should actually be set to BUTTON as below:

<button type="button" class="btn btn-primary" onclick="salvaFeira()">Enviar 
dados</button>

While it was like submit, it did not work because the page reloaded and lost the request sent by ajax.

Inmytestnowitworksperfect,andforyou?

PS:Donotforgetthatjqueryshouldbeincludedonyourpageforthistowork:

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

Hugs ...

    
19.01.2018 / 01:05