Using jQuery AJAX to pass checkbox data - php

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);
?>

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.

Related

Make checkbox return false when unchecked

I have a form looking like:
<form>
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
</form>
The number of checkboxes will variate from time to time so when processing this data with PHP I have to loop the _POST['checked'] array.
My problem is that I want to take actions both when a checkbox is checked and when it's not. But only the the checked checkboxes will be added to the _POST['checked'] array.
<form>
<input type="checkbox" key="1"/>
<input type="hidden" name="checked[1]" value="false">
<input type="checkbox" key="2"/>
<input type="hidden" name="checked[2]" value="false">
<input type="checkbox" key="3"/>
<input type="hidden" name="checked[3]" value="false">
<input type="checkbox" key="4"/>
<input type="hidden" name="checked[4]" value="false">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('[key]').change(function () {
var key = $(this).attr('key');
$($('[name="checked[' + key + ']"]')).val($(this).is(':checked') ? 'true' : 'false');
});
});
</script>
here is what i'm doing
i'm using two inputs one is checkbox without name so it won't be sent to php
, the other is hidden won't be shown to the user but it is what will be sent to php
then with jquery when the user check the box jquery change the value of the hidden input to true and when uncheck it change the value to false
so the value will always be send to the php with value true or false as string
you can change the value you want to send to php by changing this
.is(':checked')?'true':'false')
to something like that .is(':checked')?1:0) to send 1 and 0 instead of true and false
another solution is rybo111 solution
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
it will send the two options but if the checkbox is checked it will override the first option
but it is not reliable 100% and it will send more data to the server
read more about that in POSTing Form Fields with same Name Attribute
so if you want to use simple solution without js use the "html only"
if you want 100% reliable solution use the "js"
Here's a technique I've seen before:
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
The reason this works is because when values with the same name are sent more than once, only the last value is accepted.
In my opinion, a better way is to simply use isset($_POST['...']) or in_array($_POST['...']).
Add value="true" to each checkbox input element.
And change your PHP code to :
$checked_arr = [];
foreach($_POST["checked"] as $checked){
if($checked == "true"){
// do what you want to do
}
}
Another Solution is server-side solution that I think is too fast and easy.
client side:
Just use fresh HTML :
<input type="checkbox" name="checked1" value="value_checked" ... />
server side:
make global function like this:
function getVal(&$var, $default = '') {
if (!isset($var) || empty($var) || is_null($var))
$var = $default;
return $var;
}
then use where you want to read some value that you don't know is set or not.
like this:
$checked_value = getVal($_POST["checked1"],false);
or
$checked_value = getVal($_POST["checked1"],"value_not_checked");
I hope useful to another one.
This is best approach according to my experience
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">

jQuery $(this).serialize() does not send unchanged input

When I send a form using jQuery post and serialize, I only seem to send the items in the form that have been changed. I want to serialize the entire form. How do I do that?
I have some HTML.
<form name ="XXX" class="user_goal_form">
<input type="hidden" name ="goalID" value="1"/>
<input type="hidden" name ="userID" value="1"/>
Fullfilled: <input type="number" class="user_goal_input" name="achievedLevel" value="5"/.>
Finished: <input type="checkbox" class="user_goal_input" name="goalCompleted" value="false"/>
</form>
To that is attached some jQuery:
$(".user_goal_input").change(function(){
$.post("./handelform.php", {form: $(this).serialize()})
.done(function(data) {
$("#userList").html(data);
});
The content of the posted form I receive in handleform.php is only the things in the form that have changed. Never the hidden inputs or any input that has not been altered. How can I make this submit the entire form?
You're serializing the input instead of the form.
You can do this :
$(".user_goal_input").change(function(){
$.post("./handelform.php", {form: $(this.form).serialize()})

displaying results of php quiz without page reload

This is a simple one, but I just can't figure it out.
I have a simple form:
<form action='#' method="post">
<label for="question-1">Question One</label>
<input type="radio" name="question-1-answers" value="1" />
<input type="radio" name="question-1-answers" value="2" />
<label for="question-2">Question Two</label>
<input type="radio" name="question-2-answers" value="1" />
<input type="radio" name="question-2-answers" value="2" />
<input type="submit" value="Submit Quiz" class="submit"/>
</form>
Then I have simple php in results.php to calculate the results:
<?php
$answer1 = $_POST['question-1-answers'];
$answer2 = $_POST['question-2-answers'];
$result = 0;
$a =array( 0=> "$answer1", 1=> "$answer2");
$result = array_sum($a)/count(array_filter($a));
echo "Your score is: "; echo round($result, 1);
?>
This all works great, but I want the result to show up on the same page as the quiz when the user presses the submit button, without a page reload. I know I need to use jQuery, but everywhere I look has a different way of doing it, and nothing works.
Edit:
So I added the following:
$function() {
$.get('../results.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
}
and
<div class="result">The results are:</div>
and updated the submit button with <input type="submit" value="Submit Quiz" class="submit" onclick="function()"/>
I'm still not getting anything when I click the submit button, and when I check the console the only error I get is: Uncaught SyntaxError: Unexpected token { but I don't know where I have an extra {.
You'll want to use jQuery to load a PHP quiz result HTML page. You then want to inject it into the dom.
Include jQuery, and then this example should work, assuming quiz result page is at (php/quizResult.php) - you can set this up as you like
jQuery
$.get('php/quizResult.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
HTML
<div class="result"></div>
Put the jQuery in a function in JavaScript, and call it when you want to load the results.
Here is an example as Christian has hinted at:
$.post('/callcenter/admin/postContacts', data, function(returnedData) {
// do something here with the returnedData
console.log(returnedData);
});
Your PHP page would then return JSON.
Ref. Pass data from jQuery to PHP for an ajax post

If radio button checked, then submit to different page

I have this:
<form method="post" id="kl" action="step2.php">
<input type="radio" name="rubrik" value="bussines"></input>
<input type="radio" name"rubrik" value="private"></input>
<input type="image" value="submit" src="/images/submit.png" alt="Submit" />
</form>
What i bassicaly want is: When the second radio button is checked, to submit the form to step2a.php, a different file. How can i do this? Jquery, Javascript, php?
You could do this with JavaScript (bind a submit listener that checks the value of the radio button and then sets the action property of the form), but it would be simpler and more reliable to do something (server side) along the lines of:
<form ... action="step-selector.php">
and
<?php
if (isset($_POST['rubrik']) && $_POST['rubrik'] == 'bussines') {
include('step2.php');
} elseif (isset($_POST['rubrik']) && $_POST['rubrik'] == 'private') {
include('step2a.php');
} else {
include('error-state.php');
}
?>
you can do this by modifying the Form into:
<form method="post" id="kl" action="step2.php">
<input type="radio" class="radio" rel="step2.php" name="rubrik" value="bussines"></input>
<input type="radio" class="radio" rel="step2a.php" name"rubrik" value="private"></input>
<input type="image" value="submit" src="/images/submit.png" alt="Submit" />
</form>
I added rel attribute to radio buttons. each has a value of the url. I also added a class to get the element with jQuery.
Now, you will need some Javascript, i will use jQuery code:
$('.radio').click(function (){
rad = $(this);
radRel = rad.attr('rel');
$('form#kl').attr('action', radRel);
});
There are multiple ways of doing it, depending on what you want exactly.
Check this one out, it might help you get there; Radio Button to open pages
You can use form.submit() as onclick-handler (not onchange) and change the action, too.
<input type="radio" name"rubrik" value="private" onclick="this.parentNode.action='yourOtherFile.php'; this.parentNode.submit()"></input>

How to get the value of a checked Radio Button from jQuery $.post after it is submitted to a PHP file

I am completely new to javascript/jquery, and would appreciate any help.
I am having trouble with the function $.post because I am using radio in the form. I need to use the value of the chosen radio in a different file, so that I can process what should be outputted, and then I want to output something in place of where the form is.
Here is the form with type radio input:
<div id='poll'>
<form name='poll_form' id='poll_form'>
<INPUT TYPE="radio" name='poll' value ='poll1'/>Option1<br/>
<INPUT TYPE="radio" name='poll' value='poll2' />Option2<br/>
<INPUT TYPE="radio" name='poll' value='poll3'/>Option3<br/>
<INPUT TYPE="radio" name='poll' value='poll4'/>Option4</br>
<INPUT TYPE='button' value='Submit Vote' onClick="vote();" />
</form>
</div>
Here is the javascript/jquery to define the "vote();" function:
<head>
<script type = "text/javascript" src="jquery.js"></script>
<script type = "text/javascript">
function vote() {
$.post('file.php',$('input:radio[name=poll]:checked').val(),
function(output){
$("#poll").html(output).show();
});
};
</script>
</head>
Is $('input:radio[name=poll]:checked').val() the correct thing to use? And if so, how do I retrieve the value of $('input:radio[name=poll]:checked').val() in file.php?
To post values you would have to declare a post-variable and assign your value to it, i.e.
$.post('file.php',{ poll: $('input:radio[name='poll']:checked').val() }, function() {
$("#poll").html(output).show();
});
In your PHP file you can access the value via
$_POST['poll']

Categories