Insert Data Using Radio Button in PHP Ajax

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

1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE `freeze`.`tb` (
`id` INT( 3 ) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 50 ) NOT NULL ,

PRIMARY KEY ( `id` )

) ENGINE = INNODB;

 

Stylesheet

/this stylesheet will be used for validation error message.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div> <style type="text/css"></div>
.bg
{
color:#00F;
font-weight:bold;
margin:10px;
}
</style>

 

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<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>

 

ajax-check.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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')");
}
?>

About prasad k

Prasad Kuppusamy has written 81 post in this blog.

i m php developer, web designer.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

areosystyle-exsolve