How to make a form using ajax, onchange event, reload to SAME page
- by user1348220
I've been studying this for a while and I'm not sure if I'm going about this the right way because every form I setup according to examples, it doesn't do what I need.
I need to setup a form that will:
set session when you select from dropdown menu
not reload/refresh page (i've read that using AJAX solves this)
submit and stay on SAME page (confused because most AJAX examples send it to different process.php page which is supposedly "invisible" but it doesn't "stay" on the same page, it redirects.
Basically, client selects quantity of 1 to 10. If they select "2"... it does NOT reload the page.. but it DOES set a session[quantity]=2. Should be simple... but do I POST to same page as form? or POST to different page and it somehow redirects?
Also, one test I did it kept pasting my "echo session[quantity]" down the page like 7, 2, 3, 5, etc. etc. each time instead of replacing it.
I would paste code but it's all over the place and I'm hoping for direction on which methods to use. Feel I need to start all over again.
Edit: trying to add code below but can't seem to paste it properly.
<? ob_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php session_start(); ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Submit Form with out refreshing page Tutorial</title>
<!-- JavaScript -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var gender = $("#gender").val();
var dataString = '&gender=' + gender;
if(gender=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<style type="text/css">
body{
}
.error{
color:#d12f19;
font-size:12px;
}
.success{
color:#006600;
font-size:12px;
}
</style>
</head>
<body id="public">
<div style="height:30px"></div>
<div id="container">
<div style="height:30px"></div>
<form method="post" name="form">
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Your gender is <?php echo $_SESSION['gender'];?></span>
</div>
</form>
<div style="height:20px"></div>
</div><!--container-->
</body>
</html>
<? ob_flush(); ?>
and here is my page where the POST goes called join.php (called that in example so I went with it for now)
<?php
session_start();
if($_POST)
{
$gender = $_POST['gender'];
$_SESSION['gender'] = $gender;
}
else
{ }
?>