Send value from a radio input to php

Asked

Viewed 1,090 times

1

Good afternoon, I have a form that will send me the user data via email, and I have 3 input type="radio" that each tells me what the user wants, how do I send his values to php?

var frm = $("#form-carro");
    frm.submit(function (e) {
        $.ajax({
            type: "POST",
            url: "./form-carro.php",
            data: frm.serialize(),
            success: function () {
                $("#cform").append("<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button><i class='fa fa-thumbs-o-up'></i><strong>Obrigado!</strong> Sua mensagem foi enviada!</div>")
            }
        }), e.preventDefault()
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="form-carro">
  <label class="margem-direita" style="margin-right: 5%" for='seguro'>
    <input id='seguro-novo' type="radio" name="seguro" value="Seguro Novo">Seguro Novo</label>
  <label class="margem-direita" style="margin-right: 5%" for='seguro'>
    <input id='renovacao' type="radio" name="seguro" value="Renovação">Renovação</label>
  <label class="margem-direita" for='seguro'>
    <input id='sinistrado' type="radio" name="seguro" value="Sinistrado">Sinistrado</label>
</form>

  • Missing define the action which is the php file to be executed, the sending method and a Submit button.

  • @rray the action ta defined by ajax, I will add it to the code

  • That, keep adding the details there, before I didn’t have this information hehe.

  • @Mauroalexandre Somebody put this on $_POST['seguro']; in php that sends the selected value of name="seguro"?

  • That’s about it, when ajax sends the request PHP will respond by showing the input value

  • What problem you have, the request does not arrive (404)? the value is not sent, check with print_r($_POST) in php?

Show 1 more comment

2 answers

2


Start by having some errors and faults in your html, the error is that it does not close the tags <label> and I assume you want to send the information with the http method POST, which is defined in the tag <form> and the action that is the script php which will process server-side information.

<form id="form-carro" method="POST" action="script.php"> <!-- AJUSTAR AQUI O NOME DO FICHEIRO PHP -->
  <label class="margem-direita" style="margin-right: 5%" for='seguro-novo'>
    <input id='seguro-novo' type="radio" name="seguro" value="Seguro Novo">Seguro Novo</label>
  </label>
  <label class="margem-direita" style="margin-right: 5%" for='renovacao'>
    <input id='renovacao' type="radio" name="seguro" value="Renovação">Renovação</label>
  </label>
  <label class="margem-direita" for='sinistrado'>
    <input id='sinistrado' type="radio" name="seguro" value="Sinistrado">Sinistrado</label>
  </label>
  <input type="submit" value="enviar">
</form>

In the.php script (this can have any name you want):

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(isset($_POST['seguro'])) {
        echo $_POST['seguro'];
    }
}

Note that if you want the data to be processed on the same page/form file simply do not set the action on <form>:

<form id="form-carro" method="POST">

And include php that’s on top of the same page.

EDITING (I noticed by the comments on the question you are asking with ajax):

I made a small but complete example, you can test it by putting it all in the same.php file (as is) on the server, or you can put the php part in another file and set the correct url in the ajax request:

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(isset($_POST['seguro'])) {
        echo $_POST['seguro'];
    }
    die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="form-carro" method="POST">
  <label class="margem-direita" style="margin-right: 5%" for='seguro-novo'>
    <input id='seguro-novo' type="radio" name="seguro" value="Seguro Novo">Seguro Novo</label>
  </label>
  <label class="margem-direita" style="margin-right: 5%" for='renovacao'>
    <input id='renovacao' type="radio" name="seguro" value="Renovação">Renovação</label>
  </label>
  <label class="margem-direita" for='sinistrado'>
    <input id='sinistrado' type="radio" name="seguro" value="Sinistrado">Sinistrado</label>
  </label>
  <input type="submit" value="enviar">
</form>
<script>
$('input[type="submit"]').on('click', function(e) {
    e.preventDefault();
    var seg = $('input[name="seguro"]:checked').val();
    $.ajax({
        url: '',
        type: 'POST',
        data: {seguro: seg},
        success: function (response) {
            // aqui coloca tudo o que quer que aconteça caso a requisição seja bem sucedida
            // trabalha os dados que vieram do servidor como quiser
            alert('escolheu: ' +response);
        },
        error: function(xhr, status, error){
            console.log("Fail: " + xhr.responseText);
        }
    });
    return false;
});
</script>

2

To work with the frm.serialize() form, try this way:

<?php

if ($_POST) {
  echo $_POST['seguro'];
die();
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <script>
        $(function() {
            var frm = $("#form_carro");
            frm.submit(function (e) {
                e.preventDefault();
                $.ajax({
                    type: "POST",
                    url: frm.attr('action'),
                    data: frm.serialize(),
                    success: function (data) {
                        /* o alert irá imprimir o
                           retorno do que foi 
                           enviado para o PHP */
                        alert(data);
                        $("#cform").append("<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button><i class='fa fa-thumbs-o-up'></i><strong>Obrigado!</strong> Sua mensagem foi enviada!</div>")
                    },
                    error:function(error) {
                        console.log(error);
                    }
                });
            })
        });
    </script>
</head>
<body>

<div id="cform"></div>
<form id="form_carro" method="post" action="./form-carro.php">
    <label class="margem-direita" style="margin-right: 5%" for='seguro'>
        <input id='seguro-novo' type="radio" name="seguro" value="Seguro Novo">Seguro Novo</label>
    <label class="margem-direita" style="margin-right: 5%" for='seguro'>
        <input id='renovacao' type="radio" name="seguro" value="Renovação">Renovação</label>
    <label class="margem-direita" for='seguro'>
        <input id='sinistrado' type="radio" name="seguro" value="Sinistrado">Sinistrado</label>
    <input type="submit" value="Enviar">
</form>
</body>
</html>

Browser other questions tagged

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