Problems and questions with sending Ajax and Php form data

Asked

Viewed 126 times

0

Hello. I need to save some html form information in php but without reloading the page. I searched several tutorials and video ajax class but I’m doing something very wrong or I don’t really understand anything about how ajax works. My html:

<form method='post' id="form">
Nome: <input name="nome" id="nome" type="text"/>
<input type="hidden" name="acao" />
<input type="submit" value="Enva" id="submit"/>
</form>

Javascript:

$(document).ready(function(){
$('#submit').click(function(event){
    event.preventDefault();
    $.ajax({
            type: 'POST',
            data: $("#form").serialize,
            url: 'teste.php',
            success:function(data) {
                // deu certo?
            }
    }); 
});
});

Php file:

<?php
if(isset($_POST["acao"])){
    $nome = $_POST["nome"];
    var_dump($nome);
}

Why don’t you send something in php? what am I doing wrong?

  • 1

    Any error appears in the browser console?

  • 5

    You must summon this serialize with ()... that is to say: $("#form").serialize()

  • Your Hidden input 'action' has no value set and I saw no place you seven some value, set one before sending

1 answer

0

Try this solution:

In the HTML part:

<input name="nome" id="campo_nome" type="text"/>
<input type="hidden" name="acao" id="campo_acao" />
<button id="btn_enviar" type="button"></button>

In the JAVASCRIPT/JQUERY part:

$('#btn_enviar').on('click', function(){
{
    var campo_acao = $('#campo_acao').val();
    var campo_nome = $('#campo_nome').val();

    // Caso seja via texto:
    //var dados = 'acao=' + campo_acao + '&nome=' + campo_nome;

   // Caso seja via JSON
    var dados = {
        acao : campo_acao,
        nome : campo_nome
    }

    $.ajax({
        url: 'nomeEnderecoArquivoAjax.php',
        type: 'POST',
        data: dados,
        dataType: 'html',
        success: function(data){  
            alert('dados enviados!');
        }
    });
}

PHP file:

// Veja o que está chegando no arquivo PHP
var_dump($_POST);
  • First, note the fact raised in the comments: the field hidden does not have a defined value. Second, what you mean by "if via JSON"?

  • if(isset($_POST["action"])) -> it seems to me that when the form is loaded, there may be a value set and this is the moment of the test it does, but what I understood the difficulty would be in passing data to the PHP page via Ajax. "if it is via JSON"? -> Optional way to pass the data to the PHP page, either via JSON or via normal text, what I meant.

Browser other questions tagged

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