Jump to content
Larry Ullman's Book Forums
skim5_1999

Ajax & Posting Radio Button Value

Recommended Posts

Hello

I'm building a restaurant reservation form which needs to do 3 things -

1) Allow users to input # of people reserving for (Drop down)

2) Then dynamically based on # of people show available rooms (Radio button)

3) Then based on selected room, show date availability via (jquery datepicker)

 

I need all 3 items to access mysql database and appear on same page without refresh.

I have 1 & 2 working well but can't figure out how to pass on #2's selected room value onto a php and datepicker id to show dynamically. However, #3, as an independent file actually works well.

 

Hence I have a challenge of linking 2 to #3. I'd greatly appreciate your expert input and apologies in advance for the length of the codes below.

 

View.html

 


<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>

<script src="js/ajax.js"></script>


<script type="text/javascript">
function showUser(str)
{
var venue = '<?php echo $_GET['VenueID'] ?>';

if (str=="")
 {
 document.getElementById("txtHint").innerHTML="";
 return;
 }


var ajax = getXMLHttpRequestObject();

ajax.onreadystatechange=function()
 {
 if (ajax.readyState==4 && ajax.status==200)
{
document.getElementById("txtHint").innerHTML=ajax.responseText;
}
 }
//xmlhttp.open("GET","test.php?c="+str,true);
ajax.open("GET","roomselect.php?c="+str+"&venue="+venue,true);
ajax.send(null);

}


</script>
</head>
<body>

<form>

<select name="username" onchange="showUser(this.value)">
<?php $venue = $_GET['VenueID'];?>
<option value="">Select # of People here </option>
<?php
while ($row=mysql_fetch_array($result))
{
echo "<option value=\"".$row['Capacity']."\"";
	echo ">".$row['Capacity']."</option>\n";
;
}
?>


</select>
</form>
<br />
<br />
<br />

<div id="txtHint"><b>Person info will be listed here.
</b></div>
<br />
<br />
<br />


<h3>Would like to show a button that upon clicking, would show datepicker here</h3> <br/>


</body>

 

Here's the Roomselect.php which the above references and contains the radio select buttons for rooms.

 

 



<?php
$c=$_GET["c"];
$id = &$_GET["venue"];

$con = mysql_connect('DBHOST', 'DBUSER', '');

if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }


mysql_select_db("DBNAME", $con);


if(isset($id ) && is_numeric($id)) {


$sql="SELECT * FROM venue_room WHERE MaxCap > $c and VenueID =$id";

$result = mysql_query($sql);

echo mysql_error($con);

while($row = mysql_fetch_array($result))
{
 echo '

 <input type ="radio" name="'.$row['RoomName'].'" id="'.$row['RoomID'].'" value = "'.$row['RoomID'].'" >
 <img src = " '.$row['Image1'],'" alt="" height="100" width="120" /> in ' . $row['RoomName'] . ' at venueID '.$id.' with capacity from '.$row['Capacity'].' to '.$row['MaxCap'].'</br>



 '
;  
}



} else {
echo "Oops! Sorry, but this link seems to not be working. Please press back and try again!" ;
}

?>

 

 

As mentioned, the above two files have #1 & #2 working well together on same page without refresh.

 

 

Now for #3...below are the independent datepicker files which work well on its own. I just can't figure out how to link the below to #1 & #2

 

Calendar.html

 


<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all"/>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>


<script>
$(document).ready(function()
{
var selected_dates = new Array();
// get all the events from the database using AJAX
selected_dates = getSelectedDates();

$('#datepicker').datepicker({
//Image: '/images/logo.png',//delete this and the next two lines (so first line showing is dateFormat to go to the way it was before.  And then must change
//ImageOnly: true,
//showOn: 'both',
dateFormat: 'yy-m-d',
inline: true,
beforeShowDay: function (date)
{
// get the current month, day and year
// attention: the months count start from 0 that's why you'll need +1 to get the month right
var mm = date.getMonth() + 1,
dd = date.getDate(),
yy = date.getFullYear();
var dt = yy + "-" + mm + "-" + dd;

if(typeof selected_dates[dt] != 'undefined')
{
// put a special class to the dates you have events for so you can distinguish it from other ones
// the "true" parameter is used so we know what are the dates that are clickable
return [true, " my_class"];
}

return [false, ""];
},


onSelect : function(date) {
$('#date_select').val(date);
$('#date_selection_container').html(date);
}



});
});
function getSelectedDates()
{
var the_selected_dates = new Array();
$.ajax(
{
	url: 'dateselect.php',
	dataType: 'json',
	async: false,
	success: function(data)
	{
$.each(data, function(n, val)
		{
			the_selected_dates[val.event_date] = val;
		});
	}
});
return the_selected_dates;
}



</script>
</head>

<body>
<h3>3. Select Date</h3> <br/>

<div id="datepicker"></div>
<!--div id="date_selection_container"></div-->

</body>

</html>

 

And finally the dateselect.php which the above calendar.html file references

I fully admit I found the below on a website which uses PHP PDO which I'm not familiar with. I stuck to it though because it's working

 



<?php
session_start();
// Initializations of the variables used
$dates = array();
// MYSQL connection credentials

include_once "Connection.php";


// PDO - connect to the database
try
{
$dbh = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);


}
catch (PDOException $e)
{
echo 'Error!: ' . $e->getMessage() . '<br/>';

}

// take the events from the table named "events"

try
{
$id = (int)$_SESSION['VenueID']; //leave it as session as needed for multiple pages
$room = (int)$_POST['RoomID'];
$sql = '
SELECT *
	FROM venue_room_availability
	WHERE IsAvailable = "Y" and RoomID=:Room and VenueID = :Venue
	';
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':Venue',$id,PDO::PARAM_INT);
$stmt->bindParam(':Room',$room,PDO::PARAM_INT);
$stmt->execute();

}
catch (PDOException $e)
{
print($e->getMessage());
die;
}

while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
// because $row['event_date'] will have this form: 2012-01-10 and in Javascript we have 2012-1-10,
// we need to rewrite it the way we use it in Javascript so we can compare it
$row['event_date'] =  date("Y-n-j", strtotime($row['event_date']));
$dates[] = $row;
}

echo json_encode($dates);

?>


Share this post


Link to post
Share on other sites

skim5_1999, it's good that you've made so much apparent progress through your own hard work.

I always like to see that sort of thing on these boards.

 

With that said, I'm honestly not going to look through all your code to figure it out.

Most likely, the key to getting the jQuery date picker library to properly integrate with everything else is to send it dates in the proper format.

I don't know how the date picker works, but assuming you provide a method with some sort of date(s), what you'll probably want to do is (based on the radio button selection) call a PHP script via Ajax to get the proper date(s) from the DB, format those dates so that they're of the proper format for the date picker function, and then send those dates back to the JS side.

 

You can format the date(s) on either the PHP side or the JS side, whichever is more convenient.

 

Does that (overly) general answer help at all?

Share this post


Link to post
Share on other sites

I just realized that this is related to the other date picker topic you started. I thought it sounded familiar, but I wasn't sure.

Anyway, please let me know what you think of my response, and I'll try to help out as much as possible (within reason).

Share this post


Link to post
Share on other sites

Hello, HartleySan!

Yes, this is the same topic I started awhile ago. I followed through what you recommended above and was able to get the datepicker dynamically appear based on selected radio button. So that's progress...!

BUT!! my problem is still integrating this to the steps which precede it.... I have ajax calls in two successive motions and they seem to conflict with each other. More specifically.,.With my reservation form

 

(1) You first select # of people via dropdown. The value you select here then calls a "roomselect.php" script via ajax

(2) then the radio buttons from roomselect.php shows up via an initially hidden div. Again, the button selected here opens the "calendar.html" URL via ajax which is displayed on the same page via an initially hidden div.

 

Because i was having so much trouble just getting the datepicker to show up, I tried to build step #2 above separately from #1. I got #2 to work fine. But now I'm trying to integrate the working #2 to #1, and for some reason the successive ajax calls cause a conflict. The jquery ajax in step #2 won't even fire up.

 

The codes to step #1 is as follow

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>

<script src="js/ajax.js"></script>


<script type="text/javascript">
function showUser(str)
{
var venue = '<?php echo $_GET['VenueID'] ?>';

if (str=="")
 {
 document.getElementById("txtHint").innerHTML="";
 return;
 }


var ajax = getXMLHttpRequestObject();

ajax.onreadystatechange=function()
 {
 if (ajax.readyState==4 && ajax.status==200)
{
document.getElementById("txtHint").innerHTML=ajax.responseText;
}
 }
//xmlhttp.open("GET","test.php?c="+str,true);
ajax.open("GET","roomselect.php?c="+str+"&venue="+venue,true);
ajax.send(null);

}
</script>
</head>
<body>

<form>

<select name="username" onchange="showUser(this.value)">
<?php $venue = $_GET['VenueID'];?>
<option value="">Select # of People here </option>
<?php
while ($row=mysql_fetch_array($result))
{
echo "<option value=\"".$row['Capacity']."\"";
	echo ">".$row['Capacity']."</option>\n";
;
}
?>


</select>
</form>

<div id="txtHint"><b>List of Rooms with radiobuttons will be listed here.</b></div>

</body>

 

The codes to step #2 is as follow. The "alert" attempt won't even work so the ajax isn't working. I've tried building in jquery no conflict, etc. but to no avail. Again, this file works if it's fired up independently from step #1. Can you help?


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>


<script language="javascript" type="text/javascript">

$(document).ready(function() {
$('.button').click(function() {
	var valueSelected = this.value;
	var buttonSelected = this.id.replace(valueSelected + '_','');
	//alert('Button Selected: ' + buttonSelected + "\nValue Selected: " + valueSelected);
	$.ajax({
		//type: "GET",
url: 'calendar.html',
		//url: 'test.php?entered=' + valueSelected + '&id=' + buttonSelected,
		dataType:  'html',
		cache: false,
async: false,
		success: function(data) {
			$('#ajaxDiv').html(data);
//$('#ajaxDiv').load("calendar.html");
//$( "#datepicker" ).datepicker();


		},
		error: function (response, desc, exception) {
			// custom error
		}
	});

});
});

</script>

<fieldset>
<legend>Posts</legend>
<?php
$c=$_GET["c"];
$id = &$_GET["venue"];
$con = mysql_connect('DBHOST', 'USERNAME', '');

if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }


mysql_select_db("DBNAME", $con);

$sql="SELECT * FROM venue_room WHERE MaxCap > $c and VenueID =$id";
;
$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
{
echo'


<input type="radio" id='.$row['RoomID'].' value='.$row['RoomID'].' name="selected_room" class="button" /> <label for='.$row['RoomID'].'>'.$row['RoomID'].'</label> <br/>

'
;
}
?>

</fieldset>
<div id="ajaxDiv">calendar should show here</div>

Share this post


Link to post
Share on other sites

I did not carefully analyze the code, but my guess is that you're using the jQuery ready method to set up the date-picker Ajax call, which you shouldn't, because you don't know how to set up the date picker Ajax call until after the user selects the number of rooms, etc.

 

Anyway, I could be wrong, but I would try waiting to initialize the Ajax call for the date picker until after the number of rooms have been selected, and the corresponding HTML for step 2 has been displayed.

 

Please let me know if that helps.

Share this post


Link to post
Share on other sites

Hi, HartleySan,

Actually, the problem really seems to be the fact that the below jquery ajax code isn't firing up because it's preceded/called upon by another set of ajax. If I tried to open this file on my own, the calendar.html file opens up beautifully...but it's only when the file is opened via a preceding ajax Get call.

I'm at the end of my wits - any chance you can see what's wrong with the codes below so that when it's preceded by another ajax, it doesn't get triggered? I've heard that "bind" or "live" could help, but I don't know jquery enough to know how to effectively incorporate this.

Many thanks in advance for your guidance.

 




$(document).ready(function() {

   $('.button').click(function() {
       var valueSelected = this.value;
       var buttonSelected = this.id.replace(valueSelected + '_','');
       //alert('Button Selected: ' + buttonSelected + "\nValue Selected: " + valueSelected);
       $.ajax({
       url: 'calendar.html',
        //data:  '',
           cache: false,
           async: false,
           success: function(result) {
               $('#ajaxDiv').html(result);

           },
           error: function (response, desc, exception) {
               // custom error
           }
       });

   });
});

Share this post


Link to post
Share on other sites

I almost never use jQuery, so it's hard for me to comment, but I imagine that in general you'd want to set async to true, not false. That might be the problem.

 

Really though, as a general rule, to keep things as simple as possible, I would not set up the onclick event that initializes an Ajax object until all the relevant radio buttons are displayed on the page. In other words, I wouldn't run the above code when the page is first loaded.

 

Like I (think I) asked before, are you getting any errors when you execute your code? Also, try alerting values to various parts of the script to ascertain exactly where the problem is.

 

I apologize, but I usually only check these boards at work, and I'm stuck with using IE6 and have no way of testing server-side scripts, so I don't have the means to test things out to help you. Sorry.

 

If I get the time later, I will try to test something out, but please don't wait for me, as it might not be right away. I really do encourage you to at least try the things above and see if you can even get it working first.

Share this post


Link to post
Share on other sites

HartleySan,

Thank you and please don't feel the need to apologize when you are trying to generously help me during your spare time. Your logic makes sense and another developer friend commented the same.I'll try to see how to hold back the ajax trigger until after the radio buttons have loaded.

The most frustrating thing is that the firebug console shows nothing.. no errors..not even a little help.

My condolence to you for only having IE6 to work with!

Thank you again

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...