Checkbox values getting without page loading using AJAX - php

I have a problem getting checkbox value in the following code(without page loading).
If I click on checkboxes the values can be passed through the array variable check. But whenever I click checkbox I get " Array ( [0] => undefined )".
Here is my code:
index.html
<script src="create_ajax_object.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function display() {
var ajax = create_ajax_object();
if (ajax) {
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("target").innerHTML = ajax.responseText;
}
}
ajax.open("POST", "fetchdata.php", true);
var check = new Array();
var "check[]=" + encodeURIComponent(document.myForm.user.value);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(check[]);
} else {
alert("Your browser doesnt support AJAX!");
}
} </script>
<br>
<form name='myForm'>
<input type="checkbox" name="user" value="First" onclick="display();">1
<br>
<input type="checkbox" name="user" value="Second" onclick="display();">2
<br>
<input type="checkbox" name="user" value="Third" onclick="display();">3
<br>
</form>
</html>
fetchdata.php
<?php
$no=array($_POST['check']);
foreach($no as $n)
{
print_r($n);
}
?>

The variable document.myForm.user is array of checkbox objects, you have to iterate over it and check checked property of each element.

Related

How do I get all radio buttons and their textbox values?

Description: On the form appears radio buttons with textboxes. Their count = count that you entered in textbox. In test.php file I need get all radio buttons and their textbox values, it does not matter - checked, unchecked radio buttons state.
Error is that I get only the most recent values of radiobutton and textbox. I do not see values of previous radiobuttons and textboxes.
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function getnewElementID()
{
var elementID = 0;
if($(".form-element").length > 0)
elementID = $(".form-element").length;
return elementID;
}
$(document).ready(function() {
$('#ok1').click(function () {
var n = $('#box1').val();
var index = 0;
var newElementID = getnewElementID();
if($(".RadioDiv").length > 0)
index = $(".RadioDiv").length;
var newElement = "<div class='RadioDiv form-element'><input type='hidden' name='RadioElements["+newElementID+"]' value='radiogroup'/>\n<input type='text' size='50' name='RadioElementsQueations["+newElementID+"]' placeholder='question...' >";
for (var i=1;i<=n;i++)
{
newElement+="<ol><input type='radio' name='RadioElementsValues["+newElementID+"]' value='radio_"+index+"' for='RadioElementsValuesText["+newElementID+"]'>\n\<input type='text' id='radtext' name='RadioElementsValuesText["+newElementID+"]' size='30' value='choice.."+index+"' ></ol>";
index++;
}
newElement+="</div>";
$("#myForm").append(newElement);
});});
$(document).ready(function() {
$('#submit').click(function () {
var data = $("#myForm").serialize();
if($('input[type="radio"]:checked').length == "0") {
alert("Select any value");
} else {
$.post (
"test.php",
data,
function (response) {
$('#message').html(response);
}
);
}
return false;
});
});
</script>
</head>
<body>
<form id ="myForm" action="test.php">
<label>Select your favourite Activities:</label><br/>
<input type="button" name="ok" value="ok" id="ok1">
<input type="text" value="" id="box1" name="count" size="1"><br/>
<input type="submit" id="submit"/> <br/>
</form>
<div id="message"></div>
</body>
</html>
test.php
<?php
var_dump($_POST);
$elements = $_POST['RadioElementsValuesText'];
if(is_array($elements));
for ($index = 0; $index<sizeof($elements);$index++)
{
$astring = implode("<br/>", $elements);
echo "Choices: ". $astring."<br/>";
}
?>
You should use checkboxes instead of radio button.
In a post request, only one radio button value will be send for the group name (here 'RadioElementsValuesText').
Use javascript to reproduce the radio button behavior on your checkboxes (only one checked at a time).

Getting NaN from form PHP form using JS

I'm getting a NaN value if i try to do any math with the two vars i pull form the form. It also gives me NaN if i try it parseInt it. IDK if it helps but the values are pulled from the URL using PHP; example: .../serch.php?animal=all&color=any&sunSd=all&lifeSpn=all&limiterF=5&limiterT=20
limiterF and limiterT are the vars I'm working with.
html:
<form id='serchForm' action="serch.php" method="GET">
...
<fieldset>
From: <input type='text' id = 'limiterFid' name='limiterF' value=<?php if (!empty($_GET['limiterF'])) {echo $limiterF;} else {echo 0;} ?> size="2" /><br />
To: <input type='text' id = 'limiterTid' name='limiterT' value=<?php if (!empty($_GET['limiterT'])) {echo $limiterT;} else {echo 20;} ?> size="2" />
</fieldset>
<input type="submit" id="submitNew" />
<input type="submit" id="nextSerch" />
JS:
$(document).ready(function() {
$("#serchForm input").click(function(e) {
if(e.target.id == 'submitNew') {
e.preventDefault();
$('#limiterFid').attr("value", 0);
$('#limiterTid').attr("value", 20);
$("#serchForm").submit();
} else if (e.target.id == 'nextSerch') {
e.preventDefault();
var limiterF = $('#limiterFid').value,
limiterT = $('#limiterTid').value;
limiterT = limiterF + limiterT;
limiterF = parseInt(limiterF, 5);
$('#limiterFid').attr("value", limiterF);
$('#limiterTid').attr("value", limiterT);
$("#serchForm").submit();
} else {
return;
}
});
});
This is what it will return when you click nextSerch:
.../serch.php?animal=all&color=any&sunSd=all&lifeSpn=all&limiterF=NaN&limiterT=NaN
value is a property of the DOM element not the jQuery object. You can use either val() or value on the original DOM element.
$('element').val()
// OR
$('element')[0].value
Also to set values you typically don't use attr, you use val.
$('element').val('newValue')
Use the .val() method, as value will returned undefined as it is attempting to call the 'value' property of a jQuery object:
$(document).ready(function() {
$("#serchForm input").click(function(e) {
if(e.target.id == 'submitNew') {
e.preventDefault();
$('#limiterFid').val(0);
$('#limiterTid').val(20);
$("#serchForm").submit();
} else if (e.target.id == 'nextSerch') {
e.preventDefault();
var limiterF = $('#limiterFid').val(),
limiterT = $('#limiterTid').val();
limiterT = limiterF + limiterT;
limiterF = parseInt(limiterF, 5);
$('#limiterFid').val(limiterF);
$('#limiterTid').val(limiterT);
$("#serchForm").submit();
} else {
return;
}
});
});

Jquery for submiting without refresh (no validation required)

I have a form for Tags that is working OK, with some server validation, I would like to add a Jquery to submit the content without refreshing:
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input type="submit" value="Add" name="add" />
</div>
</form>
Any advice will be highly appreciated.
Check out the jQuery Form Plugin. Using it, you can submit a form without reloading the page like so:
<form id="aForm" action="target.php" method="post>
...
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#aForm").ajaxForm();
});
</script>
The ajaxForm() function also supports all options (such as a callback function) that can be passed to the standard jQuery $.ajax function.
$(document).ready(function() {
$(form).submit( function() { // could use $(#submit).on('click', function(){ as well
$.ajax({
url: 'yourposturl',
data: $(form).serialize(),
Success: function() {
alert('ok');
}
}); //end ajax
return false;
}); //end submit()
});
Should take all form vars , serialize them so the server can receive, the return false is so page doesnt refresh on submit (stops propagation and default)
Add the JQuery javascript library
Turn the submit into a button
<button id="submitbutton" >Add</button>
Add ids to your inputs
<input type="text" id="tag" name="tag" />
And add the jquery to the click for the button ...
<script type="text/javascript">
$(document).ready(function() {
$("#submitbutton").button().click(function(){
$.post("tags.php",{id: $("#id").val(), tag: $("#tag").val()});
});
});
</script>
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input class="button" type="button" value="Add" name="add" />
</div>
</form>
$(function(){
$('.button').click(function(){
var data = $('form').serializeToObject();
$.post('tags.php', data);
});
});
// jQuery Extension to serialize a selector's elements to an object
$.fn.serializeToObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

jQuery - how to show external web page if > 2 checkbox selected?

What I'm trying to do is when user click the 2 checkboxes it will pop up new window web page. I got the solution for 1 checkbox but i have hard time figuring out on how to do in both. I tried or || or and && but i didnt work.
Here my code:
<?php
// when user clicked no checkbox
if(isset($_POST['bus']) &&
$_POST['bus'] == 'bar' && $_POST['bus'] != 'carryout')
{
echo '<script type="text/javascript" language="javascript"> window.open("http://yahoo.com", target="_self");
</script>';
}
// when user clicked yes checkbox
if(isset($_POST['bus']) &&
$_POST['bus'] == 'bar' && $_POST['bus'] != 'carryout')
{
echo '<script type="text/javascript" language="javascript">
window.open("http://google.com", target="_self");
</script>';
}
else{
/// when user clicked both checkboxes
if(isset($_POST['bus']) && $_POST['bus'] == 'bar' &&
$_POST['bus'] == 'carryout')
{
echo '<script type="text/javascript" language="javascript">
window.open("http://getvms.com", target="_self");
</script>';
}}
?>
form action="<?php echo $PHP_SELF;?>" method="post">
Type of restaurant are you?<br>
<br>
BAR
input type="checkbox" name="bus" id="1" value="bar" ?php if(isset($_POST['bus'])) ?>/><br>
CARRYOUT input type="checkbox" name="bus" id="2"value="carryout" ?php if(isset($_POST['bus']))?>/>
input type="submit" name="formSubmit" value="Submit" />
</form>
Track your checked state
If you need to count checkboxes then introduce an array of values. SUppose your checkboxes are named as:
<input type="checkbox" name="cb1" data="singleURL1" />
<input type="checkbox" name="cb2" data="singleURL2" />
then you could be doing it this way:
$(function(){
var checked = {
cb1: false,
cb2: false,
both: function(){
return this.cb1 && this.cb2;
},
allUrl: "some combined URL"
};
$(":input:checkbox").click(function(){
checked[this.name] = this.checked;
if (checked.both() === true)
{
var url = checked.allUrl;
// open combined URL
}
else
{
var url = $(this).attr("data");
// open single checkbox URL
}
});
});
I've put all the code inside a DOM ready anonymous function enclosure that can be used as is.
Using jQuery, you can do $('input:checkbox').click(function(){...})
<?php
$url = false;
if(isset($_POST['bar']) && isset($_POST['carryout'])) $url = 'http://carryoutbar.com';
elseif(isset($_POST['carryout'])) $url = 'http://carryout.com';
elseif(isset($_POST['bar'])) $url = 'http://bar.com'; // nice place, pay foo a visit!
if($url) echo '
<script type="text/javascript" language="javascript">
window.open("' . $url . '", target="_self");
</script>';
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Please select:<br/>
<input type="checkbox" name="bar" value="1" /> BAR<br/>
<input type="checkbox" name="carryout" value="1" /> Carryout<br/>
<input type="submit" name="formSubmit" value="Submit" />
</form>

How to get checked radio button value using AJAX in PHP?

I'm going to get the checked radio button value using AJAX in PHP. I have done the following code, but i can't continue.
I need your help.
ajax_radio.php
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<input type="radio" name="radio1">Blue</input>
<input type="radio" name="radio2">White</input>
<input type="radio" name="radio3">Red</input>
<input type="button" name="btn" value="Click" onClick="hello('a')"></input><br />
<input type="text" id="btn_get" name="get_btn_value"></input>
</body>
</html>
ajax.js
var xmlHttp;
function GetXmlHttpObject(){
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
try{
xmlHttp = new ActiveXObject(Msxml2.XMLHTTP);
}
catch(e){
try{
xmlHttp = new ActiveXObject(Microsoft.XMLHTTP);
}
catch(e){
alert("doesn't support AJAX");
return false;
}
}
}
}
function hello(a){
GetXmlHttpObject();
xmlHttp.open("GET","ajax_radio.html?",true);
xmlHttp.onreadystatechange = response;
xmlHttp.send(null);
}
function response(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var radio_text = xmlHttp.responseText;
document.getElementById('btn_get').innerHTML = radio_text;
}
}
}
Do you know how to complete this? Thanks in advance. :)
Edit:
I can't post the code here right now, because of the low speed of network. I'm sorry.
I have shared it in rapidshare. Can you download it firstly, and help then? Thanks a lot.
I have to update it when i go back home. Too bad.
because I mostly use Jquery I wrote here a jquery snipped that checks radio button values because it is much easier and cleaner:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.0");
</script>
<script type="text/javascript">
$(function() {
$('#buttoncheck').click(function () {
var var_name = $("input[name='radio1']:checked").val();
$('#btn_get').val(var_name);
});
});
</script>
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<input type="radio" value="Blue" name="radio1">Blue</input>
<input type="radio" value="White" name="radio1">White</input>
<input type="radio" value="Red" name="radio1">Red</input>
<input id="buttoncheck" type="button" name="btn" value="Click"></input>
<br />
<input type="text" id="btn_get" name="get_btn_value"></input>
</body>
</html>
Take a look for jquery here: Jquery
Explanation:
This part selects the item with the ID #buttoncheck and checks if its ran: $('#buttoncheck').click(function () {
Then it will run the code in the function. This code gets the value of a input box with the name radio1. the ':checked' makes sure that it only selects the value of the checked radio button:
var var_name = $("input[name='radio1']:checked").val();
And last. This puts the value of the variable into the item with #btn_get as id:
$('#btn_get').val(var_name);

Categories