Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Sunday, April 15, 2012

Javascript - Object.keys Browser Compatibility

For Object.keys compatibility in all browsers add this code before using Object.keys.

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
  return k;
}

You can now use Object.keys as normal such as Object.keys(myObject).length

Wednesday, May 25, 2011

JavaScript - AJAX / SJAX - Submit Form Data to PHP Script

Below is a function I use to submit form data (POST) to a PHP script using Asynchronous / Synchronous JavaScript And XML.

function runSQL(div, script, data) {
  var
ajax = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest;
  if (div != "") {
    ajax.onreadystatechange = function () {
     if (ajax.readyState == 4) {document.getElementById(div).innerHTML = ajax.responseText}; //AJAX
    };
  }
  ajax.open("POST", script, div != '' ? true : false);
  if (data) {ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")};
  ajax.send(data ? data : null);
  if (div == "") {
    return ajax.responseText; //SJAX
  } else {
    return
;
  }
}

Example of AJAX call:

runSQL('DIV_Content', 'sql.php', 'action=getContents&page=Home&custom=1');

Example of SJAX call:

result = runSQL('', 'sql.php', 'action=getContents&page=Home&custom=1');
//Do something with result

Note: Using AJAX allows the JavaScript to continue executing however using SJAX forces JavaScript to wait for the result before continuing. This is useful if you need to do something with the result such as use it in a calculation elsewhere in JavaScript whereas the AJAX result can just be returned straight to the HTML div element as is, once it is ready.

Thursday, May 19, 2011

jQuery - Tables - Show and Hide Columns

You can hide and show columns in a table by specifying a column index where 1 is the first column in the table.

function toggleColumn(column) {
  $('#iTable tr *:nth-child('+ column +')').toggle();
}

Note: iTable is the name of the HTML table.
Note: The * is used to ensure you show / hide both the TH and TD tags.

Friday, May 6, 2011

jQuery - Datepicker - Disable Specific Dates

You can disable specific dates with the jQuery Datepicker using the beforeShowDay event.

var unavailableDates = ["9-5-2011","14-5-2011","15-5-2011"];

function unavailable(date) {
  dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
  if ($.inArray(dmy, unavailableDates) < 0) {
    return [true
,"","Book Now"];
  } else {
    return [false
,"","Booked Out"];
  }
}

$('#iDate').datepicker({ beforeShowDay: unavailable });

Note: iDate in the last line is the name of the HTML form input element.

To see a working example with some more features please see the jsFiddle example: HERE