Insert Data Using Radio Button in PHP Ajax

By | October 17, 2012

Using Ajax, we can insert data into mysql database using radio button without  refreshing the page. In some concept, we need to insert data into database and selected option value should remain as selected even after insert into database. This can be achieved when page wouldn’t refresh (i.e.,  using ajax script)

 

Database

[code type=sql]

CREATE TABLE `freeze`.`tb` (
`id` INT( 3 ) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 50 ) NOT NULL ,

PRIMARY KEY ( `id` )

) ENGINE = INNODB;

[/code]

 

Stylesheet

/this stylesheet will be used for validation error message.

[code type=css]

 <style type=”text/css”>

.bg
{
color:#00F;
font-weight:bold;
margin:10px;
}
</style>

[/code]

 

HTML

$(“#submit”).click(function() – this function triggered when submit button is clicked.

var game=$(‘input[type=”radio”]:checked’).val();  – this jquery code will get checked radio button value and store in variable game.

If any of the value is not selected then alert box with message “Select any value” , else ajax function will be called.

[code type=html]

<html>
<head>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js”>
</script>
<script type=”text/javascript”>
$(document).ready(function(){
$(“#submit”).click(function(){
var game=$(‘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: “game=”+game,
success: function()
{
$(“#msg”).addClass(‘bg’);
$(“#msg”).html(“value Entered”);
}
});
}
return false;
});
});

</script>

</head>
<body>
<div id=”msg”></div>
<form method=”post” action=””>
Select your favourite game:<br/>
<input type=”radio” name=”game” value=”football”> Football<br />
<input type=”radio” name=”game” value=”volleyball”> Volleyball<br />
<input type=”radio” name=”game” value=”tennis”> Tennis<br /><br />
<input type=”submit” name=”submit” id=”submit”>
</form>
</body>
</html>

[/code]

 

ajax-check.php

[code type=php]

<?php
$query=mysql_connect(“localhost”,”root”,””);
mysql_select_db(‘cat’,$query);
if(isset($_POST[‘game’]))
{
$choice=$_POST[‘game’];
mysql_query(“insert into tbb values(”,’$choice’)”);
}
?>

[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *