Multiple radio buttons ajax post - php

I'm new in web programming and I really need your help. I have a form with several radio buttons and I want to insert them into mysql through an ajax post. I can do it for a single button but for more than one I don't have idea how to do it.
This is a part of my html and jquery:
<html>
<script>
$(document).ready(function () {
$("#submit").click(function () {
var q1 = $('input[type="radio"]:checked').val();
if ($('input[type="radio"]:checked').length == "0") {
alert("Select any value");
} else {
$.ajax({
type: "POST",
url: "ajax-check.php",
data: "q1=" + q1,
success: function () {
$("#msg").addClass('bg');
$("#msg").html("value Entered");
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="msg"></div>
<form method="post" action="">
<div class="Clear">
question1:bla bla bla
<input class="star required" type="radio" name="q1" value="1" />
<input class="star" type="radio" name="q1" value="2" />
<input class="star" type="radio" name="q1" value="3" />
<input class="star" type="radio" name="q1" value="4" />
<input class="star" type="radio" name="q1" value="5" />
</div>
<br />
<div class="Clear">
question2:bla bla bla
<input class="star required" type="radio" name="q2" value="1" />
<input class="star" type="radio" name="q2" value="2" />
<input class="star" type="radio" name="q2" value="3" />
<input class="star" type="radio" name="q2" value="4" />
<input class="star" type="radio" name="q2" value="5" />
</div>
<input type="submit" name="submit" id="submit" />
</form>
</body>
</html>
And here is how I insert the button in mysql:
<?php
$query = mysql_connect("localhost", "root", "");
mysql_select_db('db', $query);
if (isset($_POST['q1'])) {
$choice1 = $_POST['q1'];
$choice2 = $_POST['q2'];
mysql_query("INSERT INTO tb VALUES('','$choice1')");
}
?>
I've tried to make a var for each button but dosen't worked.
How could I post all values in php and what should I change into my ajax and php?
Thanks!
This is how I did the .php
<?php
$query=mysql_connect("localhost","root","");
mysql_select_db('cosmote',$query);
$q = array();
for ($i = 1; $i <= 2; $i++) {
$q[$i] = isset($_POST['q'+$i]) ? mysql_real_escape_string($_POST['q'+$i]) : 0;
}
mysql_query("INSERT INTO tabel (q1,q2) VALUES ('$q[1]','$q[2]')");
?>

OK, here is how to do it. First, add an id to the form:
<form id="myform" method="post" action="">
This will make it easier to access via jQuery. Then, pass the serialized form as the POST data to your PHP script:
$(document).ready(function () {
$("#submit").click(function () {
if ($('input[type="radio"]:checked').length == "0") {
alert("Select any value");
} else {
$.ajax({
type: "POST",
url: "ajax-check.php",
data: $("#myform").serialize(),
success: function () {
$("#msg").addClass('bg');
$("#msg").html("value Entered");
}
});
}
return false;
});
});
After that, you can get the radio button values from the $_POST array in your PHP script:
$_POST['q1'] // value of q1, can be 1-5
$_POST['q2'] // value of q1, can be 1-5
EDIT: The problem with your PHP code is that you used + instead of . for concatenating strings. Write this instead:
$q[$i] = isset($_POST['q'.$i]) ? mysql_real_escape_string($_POST['q'.$i]) : 0;
After this, I'm pretty sure it will work.

You could use .serialize() on the form, it will give you the values of the form as if you was submitting it regularly data: $('form').serialize(),

Related

form submit with two actions

I am trying to create a page where the form submit will execute two actions. In index.php,First action is it will use ajax to send data to be saved in the database. Second action is it will change page to index1.php. The code I created successfully saves data to the database but it does not change to index1.php. What is the problem with my code?
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var radio1 = $("input[name=group1]:checked").val();
var radio2 = $("input[name=group2]:checked").val();
var radio3 = $("input[name=group3]:checked").val();
var radio4 = $("input[name=group4]:checked").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = '&submit1='+ radio1 + '&submit2='+ radio2 + '&submit3='+ radio3 + '&submit4='+ radio4;
if(radio1==''||radio2==''||radio3==''||radio4=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
</script>
<form action="index1.php" method="post">
<hr>
<label>Alignment: </label>
<input type="radio" name="group1" value="5"> 5
<input type="radio" name="group1" value="4"> 4
<input type="radio" name="group1" value="3"> 3
<input type="radio" name="group1" value="2"> 2
<input type="radio" name="group1" value="1"> 1
<hr>
<label>Blend: </label>
<input type="radio" name="group2" value="5"> 5
<input type="radio" name="group2" value="4"> 4
<input type="radio" name="group2" value="3"> 3
<input type="radio" name="group2" value="2"> 2
<input type="radio" name="group2" value="1"> 1
<hr>
<label>Warp: </label>
<input type="radio" name="group3" value="5"> 5
<input type="radio" name="group3" value="4"> 4
<input type="radio" name="group3" value="3"> 3
<input type="radio" name="group3" value="2"> 2
<input type="radio" name="group3" value="1"> 1
<hr>
<label>Overall: </label>
<input type="radio" name="group4" value="5"> 5
<input type="radio" name="group4" value="4"> 4
<input type="radio" name="group4" value="3"> 3
<input type="radio" name="group4" value="2"> 2
<input type="radio" name="group4" value="1"> 1
<hr>
<input type="submit" id="submit" name="submit" value="Submit" class="button">
</form>
You need to change location after ajax success:
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
window.location = '/index1.php';
}
});

how to select specfic hidden element from a form in a loop in javascript?

So basically, my loop outputs four times the html below with different values in $show_id.
Everyform returns the $show_id value of the first form instead of the value of the form when the function is called. How do I fix that ?
my javascript
<script type="text/javascript" >
function addScore() {
var show_id = $('#show_id').val();
var user_id = $('#user_id').val();
var score = $('input[name=tvshowrating]:checked').val();
if(score=='')
{
alert('PleaseEnter A Score');
}
else
{
$("#flash").show();
$("#flash").html('<img src="ajax-loader.gif" />Loading Score...');
$.ajax({
type: "POST",
url: "showscoreajax.php",
data:{
"show_id" : show_id,
"user_id" : user_id,
"score" : score //we are passing the name value in URL
},
cache: false,
success: function(data){
$("#flash").html('Added');
}
});
}
return false;
};
</script>
myhtml
<div id="flash"></div>
<form id="form3B">
<div class="your-score">
<div class="">Your Score</div>
<input class="hover-star" type="radio" name="tvshowrating" value="1" title="1"/>
<input class="hover-star" type="radio" name="tvshowrating" value="2" title="2"/>
<input class="hover-star" type="radio" name="tvshowrating" value="3" title="3"/>
<input class="hover-star" type="radio" name="tvshowrating" value="4" title="4"/>
<input class="hover-star" type="radio" name="tvshowrating" value="5" title="5"/>
<input class="hover-star" type="radio" name="tvshowrating" value="6" title="6"/>
<input class="hover-star" type="radio" name="tvshowrating" value="7" title="7"/>
<input class="hover-star" type="radio" name="tvshowrating" value="8" title="8"/>
<input class="hover-star" type="radio" name="tvshowrating" value="9" title="9"/>
<input class="hover-star" type="radio" name="tvshowrating" value="10" title="10"/>
<input type="hidden" id="show_id" value="<?php echo $row[0]; ?>" />
<input type="hidden" id="user_id" value="<?php echo $user_id ?>" />
<span id="hover-test" style="margin:0 0 0 20px;"></span>
<input id="submitscore" type="submit" value="Submit scores!" onclick="addScore()" />
</div>
</form>
</div>
</div>
This is because you cannot have duplicate id's unlike duplicate class you need different ids for each form. something like this
<input type="hidden" id="show_id-form3B" value="<?php echo $row[0]; ?>" />
Then it will be possible for you to get unique value of each different forms. Some thing like this
function addScore(formId) {
var show_id = $('#show_id-'+formId).val();
var user_id = $('#user_id-'+formId).val();
//add your code
}

validate radio button

How to validate radio button through javascript?
Male <input type="radio" name="sex" value="male" />
female <input type="radio" name="sex" value="female" />
try
document.getElementsByName('sex').value == 'male'
^
Reference
one more
Try the following, include jQuery
$(document).ready(function(){
$('#submit').click(function() {
if (!$("input[#name='sex']:checked").val()) {
alert('Nothing checked!');
return false;
}
else {
alert('A radio button is checked!');
}
});
});
Your html should look like this
<form method="post" id="form">
Male <input type="radio" name="sex" value="male" />
female <input type="radio" name="sex" value="female" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
Remember to include the jQuery api's
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.2.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js" type="text/javascript"></script>
I think you are looking for required validation:
Check the following code:
<html>
<head>
<script language='javascript'>
function submit_form(){
var temp=document.getElementsByName("gender");
if(temp[0].checked == true || temp[1].checked == true )
{
document.forms["f1"].submit();
}
else
{
alert("Please Select a Gender");
}
}
</script>
<body>
<form id="f1" action="custom.html" method="post">
<input type="radio" name="gender" value="male"/>
<input type="radio" name="gender" value="female"/>
<input type="button" id="s1" onclick="submit_form()" value="Submit" />
</form>
</body>
</html>

How can I use the same checkboxes to submit multiple times to create multiple sets of selections?

I want to have a set of checkboxes that use AJAX to post to a PHP page, but after the post I want to be able to use the same checkboxes to send another set of selections to the same PHP page, up to a specified number of sets, and then use the sets as data in the PHP page.
I can't figure out how this would be implemented. Any ideas?
index.php:
<form id="checkboxes">
<input type="checkbox" id="1" name="checkboxes[]" value="1" />
<input type="checkbox" id="2" name="checkboxes[]" value="2" />
<input type="checkbox" id="3" name="checkboxes[]" value="3" />
<input type="checkbox" id="1" name="checkboxes[]" value="4" />
<input type="checkbox" id="1" name="checkboxes[]" value="5" />
<input type="button" id="button" name="submit" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#button").click(function() {
$.ajax({
type: "POST",
url: "process.php",
data: $("form#checkboxes").serialize(),
success: function(data) {
$("#div").load('success.php')
}
});
})
})
</script>
process.php:
$data = array();
foreach($_POST['checkboxes'] as $key => $value){
$data[] = "$value";
}
You need to use Sessions, if you want data to prevail over time. So, you can use it this way:
<?php
session_start();
if (!isset($_SESSION["data"]))
$_SESSION["data"] = array();
foreach($_POST['checkboxes'] as $key => $value){
$_SESSION["data"] = "$value";
}
// Print out the final array, if there's a parameter final!
if (isset($_GET["final"]))
foreach ($_SESSION["data"] as $data)
echo $data;
?>
And for the JavaScript, you need to reset the thingy:
<form id="checkboxes">
<input type="checkbox" id="1" name="checkboxes[]" value="1" />
<input type="checkbox" id="2" name="checkboxes[]" value="2" />
<input type="checkbox" id="3" name="checkboxes[]" value="3" />
<input type="checkbox" id="1" name="checkboxes[]" value="4" />
<input type="checkbox" id="1" name="checkboxes[]" value="5" />
<input type="button" id="button" name="submit" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#button").click(function() {
$.ajax({
type: "POST",
url: "process.php",
data: $("form#checkboxes").serialize(),
success: function(data) {
$("#div").load('success.php');
$("form#checkboxes > input[type='checkbox']").removeAttr('checked');
}
});
});
});
</script>
You would use the success function of the ajax call. We would get the value of each checked box and then submit the form through ajax, prevent Default, and then uncheck all boxes after form submit.
$('something').submit(function(e){
e.preventDefault();
var checked = [];
$.each($('input[type=checkbox]'), function(i,v){
if($(this).is(':checked')){
checked.push($(this).val());
}
});
$.ajax({
url: 'someurl.ext',
type: 'post',
data: checked,
success: function(data){
$.each($('input[type=checkbox]'), function(i,v){
$(this).prop('checked', false');
});
}
});
});

If a radio value is ==1 then request ajax

I have a registration form that i'm creating. In my html file, I have two radio boxes,
<input type="radio" name="whatever" value="0" id="whatever" checked//> No
<input type="radio" name="whatever" value="1" id="whatever"> Yes
If the value is 1 it should send an email using ajax, here is what I have,
if($("input[name='whatever']").val()=='2'){
$.ajax({
type: 'POST',
url: base + 'email',
data: vData,
success: function() {
// alert( "I'm the callback")
}
});
}
Thanks in advance for the help.
Start by fixing your markup so that you don't have duplicate ids:
<input type="radio" name="whatever" value="0" checked="checked" /> No
<input type="radio" name="whatever" value="1" /> Yes
and then you could use the :checked selector to detect the value of the currently selected radio button:
if($(':radio[name="whatever"]:checked').val() == '1') {
// the Yes radio button was checked =>
// you could do your AJAX request here ...
}
or give your radio buttons unique ids:
<input id="no" type="radio" name="whatever" value="0" checked="checked" /> No
<input id="yes" type="radio" name="whatever" value="1" /> Yes
and then:
if($('#yes').is(':checked')) {
// the Yes radio button was checked =>
// you could do your AJAX request here ...
}

Categories