4

On my signup page people can sign up for my website by filling in some inputs ad checkboxes. It's basically a form that sends the data to a PHP page with ajax which then puts it in the database.

The javascript gets the values from the form like this for example

var w = _("website").value;
var bio = _("bio").value;

and then sends it like this ajax.send("w="+w+"&bio="+bio); This is working as it should, but I want to add something.

Now I have a number of checkboxes that I want to get in an array that gets posted in one variable via ajax. So in my form I have this piece of PHP:

$licensessql = mysqli_query($db_conx, "SELECT * FROM licenses");
while($licenserecord = mysqli_fetch_assoc($licensessql)) {
echo '<input type="checkbox" value="'.$licenserecord["license"].'" name="licenses[]" id="'.$licenserecord["license"].'"><label for="'.$licenserecord["license"].'">'.$licenserecord["license"].'</label><br>';
}

Using pure PHP this would work and put all the values from the checkboxes in an array licences[], but I have no idea how to achieve this using ajax. If I have 5 checkboxes, I want the javascript var to have for example the value 'value1,value2,value3' and have that posted to PHP.

Thanks!

4 Answers 4

1

First of all I recommend using form serialization as posted in other answers.

To answer your actual question: "If I have 5 checkboxes, I want the javascript var to have for example the value 'value1,value2,value3' and have that posted to PHP."

Here's a fully working example (using 3 checkboxes) which will produce a javascript variable which you can use to pass to your AJAX post method for PHP to process.

JSFiddle: https://jsfiddle.net/o5q04vf0/

Code Snippet:

$(document).ready(function() {
  $('#btnTest').click(function() {
    var checkBoxValues = $("[name=licenses\\[\\]]").map(function() {
      if ($(this).is(':checked')) {
        return this.value;
      }
    }).get().join();

    alert(checkBoxValues);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="0" name="licenses[]" />
<input type="checkbox" value="1" name="licenses[]" />
<input type="checkbox" value="2" name="licenses[]" />
<button id="btnTest">Submit</button>

This will help you guide in the right direction but do consider switching your approach in passing data through AJAX like other members suggested here.

Sign up to request clarification or add additional context in comments.

Comments

0

Use POST and serialize the array as data

  $data = $('form').serialize();
    $.post( "ajax/test.html", function($data) {
      $( ".result" ).html( data );
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="demo_form.asp">
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
  <input type="submit" value="Submit">
</form>

in PHP you use $_POST['attributeName'] to read the value

2 Comments

Thanks for your answer! I only want this value to be serialized so this is what I have now for the value of the array: var licenses = $('input[name="licenses"]').serializeArray();This is what gets posted to the database. Because I have other checkboxes as well outside the array, I needed to specify the name.But this is what gets posted to the database now instead of the real values: [object Object],[object Object],[object Object] ...
0

Here we go:

You need Serialize function! Here is an exaple how you may use it:

HTML:

<form id="yourOrderFormId" method="post">
<input type="checkbox"/><input type="text"/>
<input type="checkbox"/><input type="text"/>
<button id="yourButtonId">Send</button>
</form>

jQuery Ajax:

<script>
    $('#yourButtonId').click(function(e) {

       var yourData = $("#yourOrderFormId").serialize(); 

        $.ajax({
            method: 'POST',
            url: '/yourUrl',
            data: yourData,
            dataType: 'html',
           success:success: function (result) {
           alert("Your message sent!");
           }
    });

Or use with serializeArray();

console.log($('form').serializeArray());

Here :enter link description here

Hope it helps;)

10 Comments

I only want the values of my array to be serialized, the rest has to be send through javascript variables because of checking them for errors. How can I only serialize the array with checkboxes that have the name "Licenses"?
@SenneVandenputte try this method: if you want to serialize only checkboxes use this: var yourData = $("yourCheckboxId").val() ; insted of var yourData = $("#yourOrderFormId").serialize();
I think it is working now, but in my database I see now [object Object],[object Object] instead of the checkbox values..
@SenneVandenputte I think, if you send your data with this method it will be fine : var yourData = $("#yourOrderFormId").serialize(); ps. if it helps pls, check mark for my solution.Thanx ;)
I just used your method and when I use var licenses = $('input[name="licenses"]').val(); it sends it correctly, but only the first value. Not the array. I feel like it's almost working but nog completely yet
|
0

You can send all form data with serializeArray function.
Serialize use for GET, and serializeArray is useful for POST.

$('#btn-send').click(function(e) {
    $.ajax({
        url: 'url-to-data-send',
        method: 'post',
        data: $(this).closest('form').serializeArray(); <--- send form data
    }).done(function(response) {
        alert('form sent');
    })
});

or you can specify what you want to send definetely

var data = $(this).closest('form').serializeArray();
    console.log(data);

FIDDLE

** EDIT **

This does what you want I guess

var arr = [];
$.map( $(this).closest('form').find('input[name="chck[]"]:checked'), function( n, i ) {
     arr.push({ name: $(n).attr('name'), value: $(n).val()});
});
console.log(arr);

FIDDLE 2

2 Comments

Thanks for your answer! I only want this value to be serialized so this is what I have now for the value of the array: var licenses = $('input[name="licenses"]').serializeArray();This is what gets posted to the database. Because I have other checkboxes as well outside the array, I needed to specify the name.But this is what gets posted to the database now instead of the real values: [object Object],[object Object],[object Object] ...
@SenneVandenputte I updated my answer, check if help to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.