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.
[code type=html]
<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>
[/code]
data.php
[code type=html]
<?php
if(isset($_POST[‘submit’]))
{
$name=$_POST[‘name’];
$age=$_POST[‘age’];
echo $name;
echo $age;
}
?>
[/code]
Without Serialize method
index.php
data: “name=”+name+”&pass=”+pass, – this will sends data to data.php page
[code type=html]
<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>
[/code]
data.php
[code type=html]
<?php
if(isset($_POST[‘submit’]))
{
$name=$_POST[‘name’];
$age=$_POST[‘age’];
echo $name;
echo $age;
}
?>
[/code]
Thanks, it is exactly what I was searching.
Thanks for the code … It’s very useful….
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?
how to upload image from same form
that article will be uploaded soon