// JavaScript Document // AJAX functions /** * DO NOT TOUCH BEFORE CONTACTING M.K. * In order to trigger a simple ajax request without a form, i.e. using plain data, you need * to pass the data in the url in which case: Both the form and formfields parameters will be * ignored. * * 1. serverAction = The server-side action in the action page. * 2. url = The path to the action page to submit to. * 3. data = Data to post, used ONLY if a form is not provided. * NOTE: All data, including the action, must be included in the data * field if a form is not supplied. * 4. form = The form Object to be submitted. * 5. formfields = Comma seperated IDs of fields whose values are to be retrieved * and posted from the given form to the action page. * 6. buttonsToDisable = Comma seperated IDs of buttons to disable until the AJAX * request returns from processing. Used to disallow multiple presses. * 7. resultFunction = Success result handler function. * 8. errorFunction = Failure result handler function. * 9. loadingSymbolItemId = The ID of the loading animation in the page. * 10. async = True for asynchronous requests/False for synchronous requests. */ function ajaxCall(serverAction, url, data, form, formfields, buttonsToDisable, resultFunction, errorFunction, loadingSymbolItemId, async) { //alert ('tmp: ' + tmp + '\nserverAction: ' + serverAction + '\nurl: ' + url + '\ndata: ' + data + '\nform: ' + form + '\nformfields: ' + formfields + '\nbuttonsToDisable: ' + buttonsToDisable + '\nresultFunction: ' + resultFunction + '\nerrorFunction: ' + errorFunction + '\nloadingSymbolItemId: ' + loadingSymbolItemId + '\nasync: ' + async); var ajaxRequest = generateAjaxInstance(); ajaxRequest.onreadystatechange = function () { if (ajaxRequest.readyState == 4) { if(ajaxRequest.status==200) { if(buttonsToDisable != null && buttonsToDisable.length > 0) { enableButtons(buttonsToDisable, true); } if(loadingSymbolItemId != null) { showAjaxLoaderValidation(false, loadingSymbolItemId); } var results = ajaxRequest.responseText; var tmpContainsError = extractError(results); if (tmpContainsError == null) { if(resultFunction != null) { var arr = extractMsgAndCode(results); resultFunction.call(this, arr); } } else if(errorFunction) { errorFunction.call(this, tmpContainsError); } else { alert (tmpContainsError[0]); } } else { errorInResponse(); } } } var tmp = null; // Switch between submitting a form and plain data. if(form != null) { tmp = getObjFromForm(form, formfields); tmp += "action=" + serverAction; } else if(data != null && data.length > 0) { tmp = data; } // Disable any buttons whose IDs have been passed. if(buttonsToDisable != null && buttonsToDisable.length > 0) { enableButtons(buttonsToDisable, false); } // Show the AJAX loader animation. if(loadingSymbolItemId != null) { showAjaxLoaderValidation(true, loadingSymbolItemId); } // Check if async is undefined, and default to true for an asynchronous request. if(async == null) { async = true; } ajaxRequest.open("POST", url, async); ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajaxRequest.send(tmp); } function errorInResponse() { alert('Connection to server lost! Please reload page.'); } function enableButtons(buttonsStr, enable) { var btnTmp = buttonsStr.split(','); var value = enable ? null : 'true'; for(var i=0; i< btnTmp.length; i++) { document.getElementById(btnTmp[i]).disabled = value; } } /** * This function handles the display of the ajax loader while validation * it should be set to true while validating, and false, when done. */ function showAjaxLoaderValidation(status, itemId) { displayValue = ''; if(document.all) { displayValue = 'inline'; } else { displayValue = 'table-row'; } if (status) { if (itemId){ document.getElementById(itemId).style.display = displayValue; }else{ if(document.getElementById('ajaxLoaderValidation') != undefined) { document.getElementById('ajaxLoaderValidation').style.display = displayValue; } if(document.getElementById('ajaxLoaderValidation2') != undefined) { document.getElementById('ajaxLoaderValidation2').style.display = displayValue; } if(document.getElementById('messageSent') != undefined) { document.getElementById('messageSent').style.display = "none"; } } } else { if (itemId){ document.getElementById(itemId).style.display = "none"; }else{ if(document.getElementById('ajaxLoaderValidation') != undefined) { document.getElementById('ajaxLoaderValidation').style.display = "none"; } if(document.getElementById('ajaxLoaderValidation2') != undefined) { document.getElementById('ajaxLoaderValidation2').style.display = "none"; } } } } function ajaxFunction(param) { displayValue = ''; if(document.all) { displayValue = 'inline'; } else { displayValue = 'block'; } showAjaxLoaderValidation(true) var ajaxRequest; // The variable that makes Ajax possible! try { // Opera 8.0+, Firefox, Safari. ajaxRequest = new XMLHttpRequest(); } catch (e) { // Internet Explorer Browsers. try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // Something went wrong alert("Your browser broke!"); return false; } } } switch (param.id) { // TODO ABDALLAH: Remove this after we r done testing. case "reg_verification_form": ajaxRequest.onreadystatechange = function () { if (ajaxRequest.readyState == 4) { if(ajaxRequest.status==200) { var results = ajaxRequest.responseText; var tmpContainsError = extractError(results); if (tmpContainsError == null) { var arr = extractMsgAndCode(results); //alert(arr[1]); location.href = "smsSection.php"; } else { alert(tmpContainsError[0]); } showAjaxLoaderValidation(false); } else { errorInResponse(); } } } var tmp = getObjFromForm(param,'mobileCode,emailCode'); tmp += "action=reg_step_two"; ajaxRequest.open("POST", "action/_registration_action.php", true); ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajaxRequest.send(tmp); break; case "edit_profile_form": ajaxRequest.onreadystatechange = function () { if (ajaxRequest.readyState == 4) { var results = ajaxRequest.responseText; var tmpContainsError = extractError(results); if (tmpContainsError == null) { //was updating profile location.href = "smsSection.php"; } else { alert(tmpContainsError[0]); document.getElementById('regSubmit').disabled = null; } showAjaxLoaderValidation(false); } } var tmp = getObjFromForm(param,'firstName,lastName,userName,password,oldPassword,email,mobileNumber,birthday,month,year,gender,country'); tmp += "action=update_profile"; ajaxRequest.open("POST", "action/_registration_action.php", true); ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajaxRequest.send(tmp); break; case "forgotPassword_form": ajaxRequest.onreadystatechange = function () { if (ajaxRequest.readyState == 4) { document.getElementById('regSubmit').disabled = false; var results = ajaxRequest.responseText; var tmpContainsError = extractError(results); if (tmpContainsError == null) { var arr = extractMsgAndCode(results); alert(arr[1]); } else { alert(tmpContainsError[0]); } showAjaxLoaderValidation(false); } } document.getElementById('regSubmit').disabled = true; var tmp = getObjFromForm(param,'userEmail,userName'); tmp += "action=forgotPassword"; ajaxRequest.open("POST", "action/_forgotPassword_action.php", true); ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajaxRequest.send(tmp); break; case "contacts_form": ajaxRequest.onreadystatechange = function () { if (ajaxRequest.readyState == 4) { var results = ajaxRequest.responseText; var tmpContainsError = extractError(results); if (tmpContainsError == null) { var arr = extractMsgAndCode(results); document.getElementById('firstName').value = ''; document.getElementById('lastName').value = ''; document.getElementById('mobile').value = ''; document.getElementById('contactSaved').innerHTML = 'Contact Saved Successfully'; document.getElementById('contactSaved').className = 'redTextAlert'; document.getElementById('contactSaved').style.display = 'inline'; if(arr[0]==1) location.href = "searchContact.php"; } else { alert (tmpContainsError[0]); } showAjaxLoaderValidation(false); document.getElementById('selectedIds').value = '-1'; } } var tmp = getObjFromForm(param, 'contactId,selectedIds,firstName,lastName,mobile'); //tmp += 'action=login_user'; ajaxRequest.open("POST", "action/_newContact_action.php", true); ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajaxRequest.send(tmp); break; } } /** * Returns true if an error(system or business) occurred, false otherwise. */ function containsError (data) { //alert(data); if (data.indexOf('COMPILER_ERROR') != -1) { return true; } if (data.indexOf('ERROR')!=-1) { return true; } else { return false; } } /** * Returns null if no error, an array containing the errormsg and errorcode otherwise. */ function extractError (data) { //alert(data); if (containsError(data)) { var arrResult = new Array(); if (data.indexOf('COMPILER_ERROR')!=-1) { arrResult.push("Severe error has occured"); arrResult.push("-2"); return arrResult; } else { var tmp = data.split('~'); arrResult.push(tmp[1]); arrResult.push(tmp[2]); return arrResult; } } else { return null; } } /** * Retrieves the values of the elements in the given form whose IDs match the * given comma seperated IDs String. Then, generates the variable portion of the * HTTP URL request String(variable=value seperated by '&') where the variable * is a token from the IDs String and the value is its corresponding value in * the form. * * NOTE: This function also adds an '&' to the end of the returned String. */ function getObjFromForm (form, IDs) { var returnObj = ''; if (arguments.length == 1) { returnObj = ''; } else { var IDsArr = IDs.split(','); for (var i=0; i'; // Third cell. newCell2.innerHTML = ' '; } /** * Generates an Asynchronous Javascript And XML object based on the client browser. * It first tries to generate an XMLHttpRequest for (Opera 8.0+, Firefox, Safari) browsers, * and if that fails, it tries to generate ActiveXObject for (Internet Explorer) browsers. */ function generateAjaxInstance() { var ajaxRequest = null; try { // Opera 8.0+, Firefox, Safari. ajaxRequest = new XMLHttpRequest(); // The variable that makes Ajax possible! } catch (e) { // Internet Explorer Browsers. try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // Something went wrong. alert("Your browser broke!"); return false; } } } // Return the generated request. return ajaxRequest; } function logout () { var ajaxRequest = generateAjaxInstance(); if (ajaxRequest == null) { return false; } ajaxRequest.onreadystatechange = function () { if (ajaxRequest.readyState == 4) { var results = ajaxRequest.responseText; var tmpContainsError = extractError(results); if (tmpContainsError == null) { /* TODOABD : NOT USING THIS CODE ANYMORE! WILL DISCUSS ISSUES AND REMOVE IT IF NECESSARY.*/ /* ABOHMEID: CODE IS STILL BEING USED TO LOGOUT */ location.href = "index.php"; var arr = extractMsgAndCode(results); if (arr[1] == 1) { document.getElementById('loginUserName').value = ''; // Delete the user name document.getElementById('loginPassword').value = ''; // Delete the password } } else { alert (tmpContainsError[0]); } } } var tmp = 'action=logout_user'; ajaxRequest.open("POST", "action/_login_action.php", true); ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajaxRequest.send(tmp); } function destroyCookies () { var ajaxRequest = generateAjaxInstance(); if (ajaxRequest == null) { return false; } ajaxRequest.onreadystatechange = function () { if (ajaxRequest.readyState == 4) { var results = ajaxRequest.responseText; } } var tmp = 'action=destroy_cookies'; ajaxRequest.open("POST", "action/_destroy_cookie.php", true); ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajaxRequest.send(tmp); } function trim(sString) { while (sString.substring(0,1) == ' ') { sString = sString.substring(1, sString.length); } while (sString.substring(sString.length-1, sString.length) == ' ') { sString = sString.substring(0,sString.length-1); } return sString; } function searchQuery(searchEngine){ var query = document.getElementById("q").value; switch(searchEngine) { case "google": window.open("http://www.google.com/search?q="+query); break; case "yahoo": window.open("http://search.yahoo.com/search?p="+query); break; } } function showHideSubMenu(subMenu) { var subMenu = document.getElementById(subMenu); if(subMenu.style.display == 'none') subMenu.style.display = ''; else subMenu.style.display = 'none'; } /** * this function checks if the format of the phone number is valid * returns: true if valid, false if invalid */ function isValidPhoneNumber(phoneNumber) { if(phoneNumber.substr(0,1) == '+') { phoneNumber = phoneNumber.substr(1,phoneNumber.length); } else if(phoneNumber.substr(0,2) == '00') { phoneNumber = phoneNumber.substr(2,phoneNumber.length); } if (!isNumeric(phoneNumber, 0)) return false; else return true; } /** * this function checks if the format of the email is valid * returns: true if valid, false if invalid */ function isValidEmail(str){ var at = "@"; var dot = "."; var lat = str.indexOf(at); var lstr = str.length; var ldot = str.indexOf(dot); if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr || str.indexOf(dot)== -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr || str.indexOf(at,(lat+1)) != -1 || str.substring(lat-1,lat) == dot || str.substring(lat+1,lat+2) == dot || str.indexOf(dot,(lat+2)) == -1) return false; return true; } /** * DO NOT TOUCH BEFORE CONTACTING M.K. * In order to trigger a simple ajax request without a form, i.e. using plain data, you need * to pass the data in the url in which case: Both the form and formfields parameters will be * ignored. * * 1. form = The form Object to be submitted. * 2. serverAction = The server-side action in the action page. * 3. url = The path to the action page to submit to. * 4. data = Data to post, used ONLY if a form is not provided. * NOTE: All data, including the action, must be included in the data * field if a form is not supplied. * 5. formfields = Comma seperated IDs of fields whose values are to be retrieved * and posted from the given form to the action page. * 6. buttonsToDisable = Comma seperated IDs of buttons to disable until the AJAX * request returns from processing. Used to disallow multiple presses. * 7. resultFunction = Success result handler function. * 8. errorFunction = Failure result handler function. * 9. loadingSymbolItemId = The ID of the loading animation in the page. * 10. async = True for asynchronous requests/False for synchronous requests. */ function validateAndSubmit(form, serverAction, url, data, formfields, buttonsToDisable, resultFunction, errorFunction, loadingSymbolItemId, async) { var isValid = true; if(form) { isValid = validate(form); } // Alert the user of any errors in input. if (!isValid) { return; } else if(!serverAction && form) { ajaxFunction(form); } else { ajaxCall(serverAction, url, data, form, formfields, buttonsToDisable, resultFunction, errorFunction, loadingSymbolItemId, async); } } function validate(form) { var errorMessage = ""; var addNewLine = 0; var numberOfElements = form.elements.length; var isRequiredStr = " is required."; var isNumberStr = " has to be a number."; var isEmailStr = " has to be a valid email."; // Loop over all the elements in the page. for (var i=0; i