Send Multiple Data in Ajax

By | November 21, 2012

Ajax is used for send minimal amount of data to another php page and get result from that page. This tutorial will teach you how to send multiple data in ajax. Multiple data in the sense multiple variables. There are two methods

  • jquery serialize()
  • without serialize()

jQuery Serialize() method

index.php
var form2=$(“#form1″).serialize(); -┬áserialize() will get all data from form with id “form1″ and store in form2 variable.
data: form2, - form2 variable will be sent to data.php page.

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
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var form2=$("#form1").serialize();
$.ajax({
type: "POST",
url: "data.php",
data: form2,
success: function(html)
{
$("#load").html(html);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="" id="form1">
Username: <input type="text" name="name" id="name" /><br />
Age:<input type="password" name="age" id="age"/><br />
<input type="submit" name="submit" id="submit" /><br />
<div id="load"></div>
</form>
</body>
</html>

 

data.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$age=$_POST['age'];

echo $name;
echo $age;
}
?>

 

Without Serialize method

index.php
data: “name=”+name+”&pass=”+pass, – ┬áthis will sends data to data.php page

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
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){

var name=$("#name").val();
var age=$("#age").val();
$.ajax({
type: "POST",
url: "data.php",
data:"name="+name+"&age="+age,
success: function(html)
{
$("#load").html(html);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="" >
Username: <input type="text" name="name" id="name" /><br />
Age:<input type="password" name="age" id="age"/><br />
<input type="submit" name="submit" id="submit" /><br />
<div id="load"></div>
</form>
</body>
</html>

 

data.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$age=$_POST['age'];
echo $name;
echo $age;
}
?>

5 thoughts on “Send Multiple Data in Ajax

  1. Shreyas Mulay

    Bro how can we do this without using php file….i mean i dont want to use php file so how can we achieve the same result?

    Reply

Leave a Reply

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