0

I am trying to pass values of selected checkboxes to a PHP file using jQuery's .getJSON method.

Problem: The values does not seem to be received by the PHP file. I am using print_f to see if the PHP file has received the form data. Looking at the return data, the error PHP throws [Undefined index:] tell me that the 2 arrays $bedroom and $bathroom are not defined. How do I get this to work?

HTML Code

<form action="form_ajax.php" method="post">
  <input type="checkbox" name="bedroom[]" value="1">
  <input type="checkbox" name="bedroom[]" value="2">
  <input type="checkbox" name="bedroom[]" value="3">

  <input type="checkbox" name="bathroom[]" value="1">
  <input type="checkbox" name="bathroom[]" value="2">
  <input type="checkbox" name="bathroom[]" value="3">

  <input type="submit" id="button" value="submit!!!">
</form>

jQuery Code

$(function() {

    $("#button").click(function(e) {
        e.preventDefault();
        var other_data = "hello";
        $.getJSON("form.php", {some-other-data: other_data, bedroom: bedroom[], bathroom: bathroom[]}, function(data) {
            console.log(data);
        });
    });

});

PHP Code

<?php

$bedroom = $_GET['bedroom'];
$bathroom = $_GET['bathroom'];

print_r($bedroom);
print_r($bathroom);

?>

3
  • I think getJSON is used to GET data from the server, not sending it Commented Nov 5, 2011 at 20:11
  • I want to send some data, and get the result in JSON format. Can I still use getJSON in this case? Commented Nov 5, 2011 at 20:12
  • Yes :) the data is send in the second parameter of the getJSON function and should be visible in the PHP $_GET object. If you still have a problem, check your JSON syntax. Commented Nov 5, 2011 at 20:16

1 Answer 1

3

According to the jQuery documentation of $.getJSON() the data is passed as querystring variables, so I would suggest you try to use $_GET instead:

$bedroom = $_GET['bedroom'];
$bathroom = $_GET['bathroom'];

Edit, how to send all form-data to the php-file:

If you add an id attribute to the form-tag, you can easily use jQuery to serialize the form, like this, and pass that as the data object in $.getJSON():

$.getJSON("form.php", $("#your-form-id").serialize());

Then all your selected checkboxes should be passed along to the PHP-file.

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

2 Comments

great, thanks. Now I dont know how to send the values of the selected checkboxes to the PHP file
See my edited answer on how to serialize the form with jQuery, to pass all data with the call.

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.