JSON, PHP & SQL implementation error - php

I'm trying to work out how to use JSON, php and SQL (initially MSSQL) to populate a type-ahead field of names and, once the name is selected, to also populate a job title and department. This is my first time to use JSON, so I'm starting a bit from scratch here.
I got a partial solution from Experts Exchange (see Fiddle) using static data, but I'm having trouble converting the data I'm pulling from the database to what is being shown in the fiddle.
The code for the fiddle is:-
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = [{
empName: "A1",
empTitle: "AAA1 AAAAA"
}, {
empName: "A2",
empTitle: "AAA2 AAAAA"
}, {
empName: "B",
empTitle: "AAA AAAAA"
}, {
empName: "C",
empTitle: "AAA AAAAA"
}];
var empNames = [];
var empTitles = [];
$(availableTags).each(function(ix, v) {
empNames.push(v.empName);
empTitles.push(v.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
I'm stuck now on implementing the results returned from the database query to work with the fiddle. I believe I've to the data correctly formatted but it's wrong somewhere and I'm not sure where that is.
I'm getting the data from an SQL table with a separate php page called fetchEmpName.php:-
<?php
require('i_PDOConnection.php');
$query = "SELECT empFName + ' ' + empLName as [empName], empTitle, empDept FROM tbl_CouncilStaff WHERE active = 1 AND display = 1 AND (empFName LIKE '%".$search."%' OR empLName LIKE '%".$search."%') ORDER BY empLName";
$stmt = $dbh->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll();
$return_arr = array();
$return_arr['contacts'] = array();
foreach ($data as $row) {
$dataArray['empName'] = $row['empName'];
$dataArray['empTitle'] = $row['empTitle'];
array_push($return_arr['contacts'],$dataArray);
}
echo json_encode($return_arr);
?>
Which (according to the Chrome console log, produces an array like:
{empName: "Bob Smith", empTitle: "Chief Cook and Bottle Washer"}
Which works properly when I replace the fiddle data with the generated data but fails once the static data is replaced by the sql code. So that tells me that the problem lies in the script. At this point, the page has morphed into:
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fetchEmpName2.php'); ?>;
var empNames = [];
var empTitles = [];
$(availableTags).each(function(x, y) {
empNames.push(y.empName);
empTitles.push(y.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
// console.log(event);
// console.log(ui);
// console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
console.log(availableTags);
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
When I run the page, the jquery library throws an error saying
jquery-ui.min.js:8 Uncaught TypeError: Cannot read property 'label' of undefined"
I hope this is enough for someone to sort out where I'm off track - or if there is a better way to solving the problem of filling additional fields from a type-ahead field.
Thanks in advance - any assistance offered would be greatly appreciated.

Related

How do I display the list in the textbox after success response from ajax

I am using CodeIgniter. I am creating the live autocomplete textbox using ajax which is working. I checked in the network tab also I added the alert in the success ajax. I am getting the right output.
Now, How do I display the list in the textbox when user enter the text? should I use Json and how?
I have to display the list of the name when the user enters any letter in the textbox.
Would you help me out in this?
My View
<input type="text" name="cust_name" placeholder="Enter the name" class="form-control" id="title">
Ajax
$(document).ready(function(){
$('#title').autocomplete({
source: baseUrl + "/Search/get_search_record",
select: function (event, ui) {
$('#title').val(ui.item.label);
}
});
});
Controller
public function get_search_record(){
if (isset($_GET['term'])) {
$result=$this->Search_model->search_cust_name($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row)
$arr_result[] = array(
'first_name' => $row->first_name,
'last_name' => $row->last_name,
);
echo json_encode($arr_result);
}
}
}
Model
public function search_cust_name($emp_name){
$this->db->like('first_name', $emp_name , 'both');
return $this->db->get('members')->result();
}
When I enter any text I am getting the like this.
I am getting the output in the network tab
[{"first_name":"Naren","last_name":"Verma"}]
Hope this will help you :
Make sure you have loaded necessary js and css in your file like this :
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Your return data should be in an array form like this
['tarun verma','test sur','first last']
See the working demo : https://jsfiddle.net/xpvt214o/269229/
in controller get_search_record should be like this :
public function get_search_record()
{
if (isset($_GET['term']))
{
$result=$this->Search_model->search_cust_name($_GET['term']);
if (count($result) > 0)
{
foreach ($result as $row)
{
$arr_result[] = $row->first_name .' '. $row->last_name;
}
print_r($arr_result);
exit;
}
}
}
Js should be like this :
$(document).ready(function(){
$('#title').autocomplete({
source: baseUrl + "/Search/get_search_record",
});
});
HTML
<input list="employee_name">
<datalist id="employee_name"> </datalist>
AJAX
$(document).ready(function() {
$("#employee_name").keyup(function() {
var emp_name = $('#employee_name').val();
if (emp_name != '') {
$.ajax({
type: "POST",
url:baseUrl + "/Employee_control/search_with_emp_name",
data: {
emp_name: emp_name
},
success: function(data) {
alert(data);
$('#employee_name').html('');
for(i=1; i<=data.length; i++)
{
$('#employee_name').append('<option value="+data[i]+">');
}
}
});
}
});
});
<textarea name="my_textarea" id="my_id" cols="30" rows="10"></textarea>
success: function(data) {
var string_of_array = data.join("\n");
$('#my_id').val(string_of_array);
}
If this is your case

php code inside jquery function to read json file

I have a myfile.jsonfile like this:
[{"teamA": {"name": "DAR", "games": "4", "season":"RS", "points": "89"}},
{"teamB": {"name": "BAR", "games": "3", "season":"RS", "points": "78"}}]
I usually read the myfile.jsonfile like this:
$mydata=file_get_contents("myjsonfiles/myfile.json");
$decodeddata = json_decode($mydata,true);
So that I can use it in php. For example:
<?php
$teamApoints=$decodeddata["teamA"]["points"];
$teamBpoints=$decodeddata["teamB"]["points"];
$totalpoints=$teamApoints+$teamBpoints;
?>
<div class="apoints"><?php echo $teamApoints; ?></div>
<div class="bpoints"><?php echo $teamBpoints; ?></div>
<div class="totpoints"><?php echo $totalpoints; ?></div>
Now, the problem. I am very new at javascript functions, and I want to use the constantly changing info of the myfile.jsonfile to update the page without reloading it.
Some users gave me the idea, but, as a newcomer, it is difficult for me to implement it:
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<script>
function updatePage() {
$.getJSON('myjsonfiles/myfile.json', function(data) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
jQuery("body").html("");
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
setInterval(updatePage, 5000);
</script>
As this is incorrect, how could I access to the elements of the myfile.json inside js function and use them in php? Or, in case this is not possible, how could I access to the elements of the myfile.jsonfile and replace the content of the divs?
Thanks
Please try this approach:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<script type="text/javascript">
function updatePage() {
$.getJSON('myfile.json', function(data) {
var $string = '';
var sum=0;
$.each( data, function( key, val ) {
var x= Object.keys(val);
sum += parseInt(val[x]["points"]);
$string += "<div class='"+x+"'>"+x+" Points:" + val[x]["points"] + "</div>" ;
});
$string += "<div class='totpoints'>Total Points:"+sum+"</div>"
jQuery("body").html($string);
});
}
jQuery(document).ready(function() {
setInterval(updatePage, 1000);
//set your time as per requirement, so that after this time interval data will update automatically
});
</script>
<body></body>
</html>

Not able to export jqgrid table as excel/pdf.

I successfully created a small jqgrid table. I'm trying to export this table to an excel or pdf file using Jquery. I am new to jquery and jqgrid. Could someone please let me know what is wrong in the code? I would really appreciate some help or suggestions.
I found the export function online. It said I have to just call this function with the grid id. Am I doing something wrong?
export.php file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="CSS/CalibrationKit.css" rel="stylesheet" type="text/css">
<!-- ------------------------JQGRID files-------------------------------- -->
<link rel="stylesheet" type="text/css" media="screen" href="jquery/css/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="jquery/js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="jquery/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="jquery/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
/*jqgrid*/
var mydata = [{
head_mean_volume: "50",
head_std_dev: "2",
head_cv: "3",
offset_factor: "4",
scaling_factor: "5"
}];
$("#projectSpreadsheet").jqGrid({
data: mydata,
datatype: "local",
colNames: ["Head Mean Volume Dispensed", "Head Standard Deviation", "Head %CV", "Whole Head Offset Factor", "Whole Head Scaling Factor"],
colModel: [{
name: 'head_mean_volume',
index: 'head_mean_volume',
editable: false,
}, {
name: 'head_std_dev',
index: 'head_std_dev',
editable: false,
}, {
name: 'head_cv',
index: 'head_cv',
editable: false,
}, {
name: 'offset_factor',
index: 'offset_factor',
editable: false,
}, {
name: 'scaling_factor',
index: 'scaling_factor',
editable: false,
}],
'cellEdit': false,
'cellsubmit' : 'clientArray',
editurl: 'clientArray'
}); /*jqGrid close */
/* createExcelFromGrid */
$('#btnSun').click(function() {
$.fn.myFunction("projectSpreadsheet");
});
$.fn.myFunction = function(gridID,filename) {
var grid = $('#' + gridID);
var rowIDList = grid.getDataIDs();
var row = grid.getRowData(rowIDList[0]);
var colNames = [];
var i = 0;
for(var cName in row) {
colNames[i++] = cName; // Capture Column Names
}
var html = "";
for(var j=0;j<rowIDList.length;j++) {
row = grid.getRowData(rowIDList[j]); // Get Each Row
for(var i = 0 ; i<colNames.length ; i++ ) {
html += row[colNames[i]] + ';'; // Create a CSV delimited with ;
}
html += '\n';
}
html += '\n';
var a = document.createElement('a');
a.id = 'ExcelDL';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename ? filename + ".xls" : 'DataList.xls';
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('ExcelDL').remove();
}
}); /* function close */
</script>
</head>
<body>
<table id="projectSpreadsheet" class="fixed_headers" style="width:875px"></table>
<br><br>
<button id="btnSun">Export Table data into Excel</button>
</body>
</html>
Replace your function with this one and let me know if it works for you.
function(gridID,filename) {
var html = $('#gview_' + gridID).html();
var a = document.createElement('a');
a.id = 'tempLink';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename + ".xls";
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('tempLink').remove();
}

javascript code is not being executed

I am working on this project in which I am trying to get a returned value so I can autofill my input boxes according to what the client selects.
This code however is not executing and I do not know why. When I remove the src="jquery area" $(#dropdown).on is an undefined method; not to sure what to do.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
Here's my full code
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//$DBH->prepare('SELECT first FROM contacts');
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
//get query
$FNresult=$DBH->query('SELECT first FROM contacts');
//set fetch mode
$FNresult->setFetchMode(PDO::FETCH_ASSOC);
$dropdown = "<select name='contacts' id='contacts' >";
while($row =$FNresult->fetch()) {
$dropdown .= "\r\n<option value='{$row['first']}'>{$row['first']}</option>";
// echo getLN();
}
$dropdown .= "\r\n</select>";
echo $dropdown;
//}
/*
// Get last name
function getLN(){
$query = "SELECT last FROM contacts";
$LNresult=mysql_query($query);
$last;
while($row = mysql_fetch_assoc($LNresult)) {
$last = "{$row['last']}";
}
echo $last;
}//end getLN
*/
$DBH = null;
?>
<!-- javascript on client-side -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
/*("#dropdown").on('connection', function (stream) {
console.log('Ah, we have our first user!');
});*/</script>
<form action="insert.php" method="post">
First Name: <input type="text" id="first" name="first"><br>
Last Name: <input type="text" id="last"><br>
Phone: <input type="text" id="phone"><br>
Mobile: <input type="text" id="mobile"><br>
Fax: <input type="text" id="fax"><br>
E-mail: <input type="text" id="email"><br>
Web: <input type="text" id="web"><br>
<input type="Submit">
</form>
here is my new edited script on output page =
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$("#contacts").on('change','#dropdown', function() {
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
here is the php file for backgroundScript.php =
<?
// background script
// retrieve data based on $_POST variable, set to $returnArray
$returnArray = $_POST[array(
'first' => firstName,
'last' => lastName,
)];
/****************************
* the structure of returnArray should look something like
array(
'first' => firstName,
'last' => lastName,
)*/
echo json_encode($returnArray);
?>
this file will send in info so the javascript will then replace form fields with what ever is held in the areas appointed
It would appear that your PHP script is returning some formatted html, which you then try to insert into the dom via .val(). That method is used to set the values of form fields, not insert entire chunks of html. Try using .append() or .html() instead, plus do what Phil suggested above - split your script into multiple blocks.
You need to include your jQuery prior to using it:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Your Code Here
</script>
Better yet would be to use external JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/site.js"></script>
And if you're using HTML5 the type="text/javascript" isn't even needed so:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/site.js"></script>
Even better still would be to use a jQuery CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/site.js"></script>
Also, as others have noted, be sure to use $ at the beginning of your jQuery factories. i.e. $('#dropdown')
-- Update --
Further clarification on project tree, most basic project trees look like this:
root/
|--css/
|--images/
|--js/
|--site.js
|--index.html
-- Update 2 --
Example of a $.post
$.post({
'somescript.php', // Script your posting to
{
someParam1: someData1, // $_POST['someParam1']
someParam2: someData2
// etc etc
},
function(response){
// Do something with JSON response upon successful post
alert(response);
},
'json' // Tells the script that JSON will be returned
});
-- Update 3 --
Okay so basically you want to do is...
Javascript:
var dropdown = $('#dropdown');
dropdown.bind('change', function(){
$post.(
'backgroundScript.php',
{
first: dropdown.val()
},
function(response) {
$('#first').val(response.first);
$('#last').val(response.last);
// Repeat for all of your form fields
},
'json'
);
});
Receive POST param:
$firstName = $_POST['first'];
MySQL query would be something like the following:
$sth = $dbh->prepare('SELECT *
FROM contacts
WHERE first = :first');
$sth->bindParam(':first', $first, PDO::PARAM_STR);
$sth->execute();
Then add all of your MySQL fields into associative array array(key => value) and then json_encode and return array.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
<script>
In your PHP you should have something like this
echo json_encode(array('first' => $some_value, 'last' => "Other value"));
Shouldn't
("#dropdown").on('change', function() {
be
$("#contacts").on('change', function() {

datepicker call back not working in IE

I am using datepicker with php and jQuery to show events however this script will not work in IE and I cant figure out why. I think it has something to do with the $.get jQuery but not sure why this will not work
<?
// DB CONNECTION
?>
<link type="text/css" href="/css/calendar-theme/jquery-ui-1.8.16.custom.css" rel="stylesheet" />
<script type="text/javascript" src="/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui-1.8.16.custom.min.js"></script>
<?
// DB QUERY DB
$sql = "SELECT MONTH(eStart) as mon, DAY(eStart) as day, YEAR(eStart) as year FROM events WHERE eStart LIKE '%$date%' ORDER BY eStart ASC";
$rows = $db->query($sql);
while ($record = $db->fetch_array($rows)) {
$dates .= "new Date(".$record[year].", ".$record[mon]."-1, ".$record[day]."),";
}
$dates = rtrim($dates, ',');
?>
<script type="text/javascript">
$(document).ready(function() {
var dates = [<?= $dates; ?>];
$('#datepicker').datepicker({
numberOfMonths: [1,1],
beforeShowDay: highlightDays
});
$('#datepicker').click(function(evt){
// put your selected date into the data object
var data = $('#datepicker').val();
$.get('/getdata.php?date='+ encodeURIComponent(data), function(data) {
$('#events').empty();
$('#events').html(data).show();
evt.preventDefault();
});
});
function highlightDays(date) {
for (var i = 0; i < dates.length; i++) {
if (dates[i].getTime() == date.getTime()) {
return [true, 'highlight'];
}
}
return [true, ''];
}
});
</script>
<style>
#highlight, .highlight {
background-color: #000000;
}
</style>
<div id="datepicker" style="float:left;margin: 0 10px 0 0;font-size: 72.5%;"></div>
<div id="events" style="float:left;font-size: 10pt;height: 300px;">
<p>Select a date on the calendar to see events.</p>
</div>
<div style="clear:both"></div>
Here it is with no php, just the HTML output
<link type="text/css" href="/css/calendar-theme/jquery-ui-1.8.16.custom.css" rel="stylesheet" />
<script type="text/javascript" src="/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui-1.8.16.custom.min.js"></script>
<script>
$(document).ready(function() {
var dates = [new Date(2011, 11-1, 3),new Date(2011, 11-1, 11),new Date(2011, 11-1, 19),new Date(2011, 11-1, 26),new Date(2011, 12-1, 11),new Date(2012, 6-1, 16),new Date(2012, 7-1, 1),new Date(2012, 9-1, 20),new Date(2012, 10-1, 25)];
$('#datepicker').datepicker({
numberOfMonths: [1,1],
beforeShowDay: highlightDays
});
$('#datepicker').click(function(evt){
// put your selected date into the data object
var data = $('#datepicker').val();
$.get('/getdata.php?date='+ encodeURIComponent(data), function(data) {
$('#theevents').empty();
$('#theevents').html(data).show();
evt.preventDefault();
});
});
function highlightDays(date) {
for (var i = 0; i < dates.length; i++) {
if (dates[i].getTime() == date.getTime()) {
return [true, 'highlight'];
}
}
return [true, ''];
}
});
</script>
<style>
#highlight, .highlight {
background-color: #000000;
}
</style>
<div id="datepicker" style="float:left;margin: 0 10px 0 0;font-size: 72.5%;"></div>
<div id="theevents" style="float:left;font-size: 10pt;height: 300px;">
<p>Select a date on the calendar to see theevents.</p>
</div>
<div style="clear:both"></div>
Your dates array in JavaScript will have a stray trailing comma and that is probably making IE append a stray null to your array:
$dates .= "new Date(".$record[year].", ".$record[mon]."-1, ".$record[day]."),";
# ----------------------------^
So your JavaScript looks like this:
var dates = [ new Date(...), new Date(...), ..., ];
and IE thinks that you mean this:
var dates = [ new Date(...), new Date(...), ..., null ];
And then, in your for loop inside highlightDays, you'll try to call getTime() on null:
for (var i = 0; i < dates.length; i++) {
if (dates[i].getTime() == date.getTime()) { // <---------- Right here
return [true, 'highlight'];
}
}
That will give you a run-time error in your JavaScript and then all your JavaScript stops working.
Fix your var dates to not include the trailing comma.
Once that's out of the way, it looks like you have a stacking problem with IE. The individual cells within the calendar will look something like this:
<td class=" " onclick="DP_jQuery_1323234722897.datepicker._selectDay('#datepicker',11,2011, this);return false;">
<a class="ui-state-default" href="#">1</a>
</td>
The return false in the onclick attribute is your problem. If you clear those attributes after binding the datepicker:
$('#datepicker td').attr('onclick', '');
then #datepicker should respond to your click. You'll probably want to move your evt.preventDefault(); from the $.get callback up to the click handler as well.
Demo: http://jsfiddle.net/ambiguous/XanvW/4/
And if you want your click handler to be called after the date is chosen (rather than "instead of selecting the date" as I thought), then you want the onSelect callback:
Allows you to define your own event when the datepicker is selected.

Categories