1

My current code gets all the data from a form then outputs it to the console as an Array (I'm testing a contact form). All the data it returns is correct but the value of the radio button is always the same.

html:

<form class="form1" action="form.php" method="post">
<div class="form-sect">
    <div class="formb-check">
        <input type="text" name="name" placeholder="Name" class="formb-small">
        <input type="text" name="id" placeholder="ID: 00000000" class="formb-small">
    </div>
</div>
<div class="form-sect">
    <div class="formb-srv">
        <div class="formb-check">
            <input type="radio" name="server" id="server-1" value="Srv 1"><label for="server-1">Server 1</label>
            <input type="radio" name="server" id="server-2" value="Srv 2"><label for="server-2">Server 2</label>
        </div>
    </div>
</div>
<div>
    <div>
        <textarea name="message" placeholder="Message....."></textarea>
        <button type="submit" name="submit">Submit Report</button>
    </div>
</div>

jQuery:

$('form.form1').on('submit', function() {
var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

that.find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();

    data[name] = value;
});

$.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response){
        console.log(response);
    }
});

return false; });

PHP:

<?php 
if(isset($_POST['name'], $_POST['id'], $_POST['server'], $_POST['message'])){
    print_r($_POST);
} ?>

In the array I'm using for testing the value of the radio button is always the second value used, in this code it is Srv 2. Like this: [server] => Srv 2

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • 1
    multiple radio buttons and inputs may have same name and you are looping on all elements (not checked elements) so you always get the value of last element in a family. I suggest using `serialize()` instead not inventing the wheel again. – Ali Sheikhpour Jul 24 '19 at 06:45
  • Possible duplicate of [jQuery get value of selected radio button](https://stackoverflow.com/questions/8622336/jquery-get-value-of-selected-radio-button) – freedomn-m Jul 24 '19 at 06:51
  • generally it is a bad idea to have dash separated names like the id's `server-1` – techie_28 Jul 24 '19 at 06:59
  • @techie_28 , I'm not aware of this, care to back that up with a source? – Jon P Jul 24 '19 at 07:21
  • @JonP https://stackoverflow.com/questions/1696864/naming-class-and-id-html-attributes-dashes-vs-underlines – techie_28 Jul 24 '19 at 08:39

3 Answers3

3

You should serialize the form like this:

$('form.form1').on('submit', function(event) {
    event.preventDefault();
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function (response) {
            console.log(response);
        }
    });
});
Bram Verstraten
  • 1,414
  • 11
  • 24
1

You need to check for "checked" on radio buttons (and check boxes)

that.find('[name]').each(function(index, value) {    
    var name = $(this).attr('name');
    var notCheckOrRadio = !$(this).is('[type=radio],[type=checkbox]') ;
    if( notCheckOrRadio || $(this).is(':checked')) {
       data[name] = $(this).val();
    }
});

Note, while this answers the question as asked, you should us Bram's updated approach.

Jon P
  • 19,442
  • 8
  • 49
  • 72
0

Every time you are getting server 2 because in jquery $.each will replace second value with first one.

N:B - Don't use $.each in this case and be specific because later if new fields will come then it will be problem example checkboxes and all.

N:B- Don't use return false always use e.preventDefault();

You need to check checked radio button. Remove the unnecessary lines of code. Please follow the below example

   $('form.form1').on('submit', function(e) {
            e.preventDefault();
            data = {'name':$('[name="name"]').val(),'id':$('[name="id"]').val(),'server':$('[name="server"]:checked').val(),'message':$('[name="message"]').val()};
            $.ajax({
                url: 'form.php',
                type: 'POST',
                dataType:'json',
                data: data,
                success: function(response){
                    console.log(response);
                }
            });
        });
Soubhagya Kumar Barik
  • 1,979
  • 20
  • 26
  • Actually this is not optimal, if you add a new form element, you have to then code it in. If you use serialize, as [Bram suggested](https://stackoverflow.com/a/57176747/4665) (the best option), or identify the check boxes and and radio buttons, [as in my answer](https://stackoverflow.com/a/57176804/4665), you don't have to change the javascript code. – Jon P Jul 24 '19 at 07:18
  • serialize is not the best option beacuse then you really need to unserialize data in case of json – Soubhagya Kumar Barik Jul 24 '19 at 08:08
  • the code you have mentioned that is not standard way – Soubhagya Kumar Barik Jul 24 '19 at 08:08