Insert Values into Database Using Ajax

By | September 2, 2012

Using ajax and php script we can insert data into database. Without using ajax, we can insert data into database. But the difference between both are page won’t refresh when we use ajax with php. Without using ajax page will refreshes. While inserting values into database using ajax webpage won’t refresh, an additional php page will be used to process database operations.

When submit button is clicked, ajax function will be called with method as POST, url as ajax.php and sucess message.

index.php

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
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "name="+ name ,
success: function(){
alert("sucess");
}
});

});
});
</script>
</head>

<body>
<form action="" method="post">
Name:<input type="text" name="name" id="name" /><br />
<input type="submit" name="submit" id="submit" />
</form>
</body>
</html>

 

ajax.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>

<body>

<?php
$query=mysql_connect("localhost","root","");
mysql_select_db("freeze",$query);
$name=$_POST['name'];

mysql_query("insert into tt values('','$name')");
?>
</body>
</html>

2 thoughts on “Insert Values into Database Using Ajax

  1. mehran

    hi
    i want send multiple data from test.php page for check.php page with $.ajax() method and i want insert data to database but when inserted in database not show my data in table(just insert 0 in all columns).please help me for solve this problem

    Reply

Leave a Reply

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

coemption-knowledgeless