Sunday, 04 May 2014 11:02

Some useful javascript

Written by
Some useful javascript
Create an XML HTTP Request (XHR) object
  1. function create_XMLHttpRequest() { //create new XHR object
  2. if (window.XMLHttpRequest)
  3. {// code for IE7+, Firefox, Chrome, Opera, Safari
  4. xmlhttp=new XMLHttpRequest();
  5. } else {// code for IE6, IE5
  6. xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  7. }
  8. return xmlhttp;
  9. }
 
 
Send request to Server and receive response from server
  • Get replay from php web server: serverResponseInfo=httpGetRequest("http://domain/myReply.php")
  • Read content from a text file: serverResponseInfo=httpGetRequest("myTextFile.txt")
  • Read content from a text file: document.getElementById("myDiv").innerHTML=loadXMLDoc("myTextFile.txt");
function httpGetRequest(url)
{
   xmlhttp= create_XMLHttpRequest();
   xmlhttp.open("GET",url,false);
   xmlhttp.send();
   return xmlhttp.responseText;
}
 
 
Check if file exist
  • To check a file if exist in www root directory: fileExists("/settings.xml")
  • To check a file if exist in the current directory: fileExists("settings.xml")
  1. function fileExists(filename) {
  2. xmlhttp= create_XMLHttpRequest(); //create new XHR object
  3. if(!xmlhttp) return false;
  4. try
  5. {
  6. xmlhttp.open("HEAD", filename, false);
  7. xmlhttp.send(null);
  8. return (xmlhttp.status==200) ? true : false;
  9. }
  10. catch(er)
  11. {
  12. return false;
  13. }
  14. }
 
 
Load an XML file using XML HTTP Request
Eg. loadXML("settings.xml")
  1. function loadXML(XML_filename) {
  2. xmlhttp= create_XMLHttpRequest();
  3. xmlhttp.open("GET",XML_filename ,false);
  4. xmlhttp.send();
  5. return xmlhttp.responseXML;
  6. }
 
 
Convert XML to string
  1. function xmlToString(xmlDoc){
  2. if(xmlDoc.xml){
  3. // MSIE
  4. xmlString = xmlDoc.xml;
  5. }else{
  6. xmlString = (new XMLSerializer).serializeToString(xmlDoc);
  7. }
  8. return xmlString;
  9. }
 
 
Create a string based on date
Example of output: 2014_0502
  1. function createString_accordingDate() {
  2. var today = new Date();
  3. var dd = today.getDate();
  4. var mm = today.getMonth()+1;//January is 0!
  5. var yyyy = today.getFullYear();
  6. if(dd<10){dd='0'+dd} ;
  7. if(mm<10){mm='0'+mm};
  8. return (yyyy + "_" + mm + dd);
  9. }
.
Read 8223 times Last modified on Wednesday, 07 May 2014 22:01
Back to Top