How to create generic request processing method using javascript or ajax

SendRequest.js File (Generic Request Processing file)

 
function sendRequest($ajaxUrl,$arguments,$timeStamp,$ajaxResponseLayer){
 
 var $currentTime = new Date();
 var $timeStamp = $currentTime.getHours() + $currentTime.getMinutes()
 + $currentTime.getSeconds() + $currentTime.getMilliseconds()
 + $currentTime.getDay() + $currentTime.getMonth()
 + $currentTime.getFullYear() + Math.random();

 $.ajax({
 url : $ajaxUrl + "?" + $arguments + "&stamp=" + $timeStamp,
 cache : false,
 beforeSend : function() {
 /* call method before send request to server  */
 showProgressBar();
 },
 complete : function($response, $status) {
 /* hide progress bar once we get response */
 hideProgressBar();
 if ($status != "error" && $status != "timeout") {
 /* for set response in div */
 if($ajaxResponseLayer !="")  
 { 
  if($response.responseText.search("showMessage")>-1){
  //alert('in if ::');
  $("#errorDiv").html($response.responseText.trim());
  processAfterResponse($ajaxUrl,$arguments,$timeStamp,$ajaxResponseLayer,$response.responseText);
  return false;
  }
  $("#"+$ajaxResponseLayer).html($response.responseText);
  processAfterResponse($ajaxUrl,$arguments,$timeStamp,$ajaxResponseLayer,$response.responseText);
 }
 
 }
 },
 error : function($obj) {
 /* call when error occurs */
 hideProgressBar();
 alert("Something went wrong while processing your request."+$obj.responseText);
 }
 });  
}

function processAfterResponse($ajaxUrl,$arguments,$timeStamp,$ajaxResponseLayer,$response){
  if($ajaxUrl =='enterURLAfterProcessing.html'){

   }
}

function closeDialogBox(modelId){
  $("#"+modelId).dialog( "close" );
}

function showProgressBar() {
  document.getElementById('ajax_loader').style.display = 'block';
}

function hideProgressBar() {
  document.getElementById('ajax_loader').style.display = 'none';
}

function IsEmail(email) {
  var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

function onlyIntegerNumber(evt){
  var e = evt; // for trans-browser compatibility
  var charCode = e.which || e.keyCode;
  if(charCode == 9){
    return true;
  }
  if((charCode >=35 && charCode <38 alert="" charcode="" digit="" e.which="=0){" enter="" false="" humanmsg.displaymsg="" if="" lease="" noty="" only="" options="" return=""> 31) && (charCode < 48 || charCode > 57) ){
          alert('Please enter only digit (0-9)');
         return false;
   }else{
    return true;
   }
}

function isNumberKey(evt){
    var e = evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    
    if(charCode == 46 || charCode == 9){
     return true;
    }
    if((charCode >=35 && charCode <38 .="" alert="" characters="" charcode="" e.which="=0){" false="" if="" llow="" numeric="" only="" or="" return=""> 31) && (charCode < 48 || charCode > 57) ){
       noty(options);
           return false;
     }else{
    return true;
     }
}
if(typeof String.prototype.trim !== 'function') {
   String.prototype.trim = function() {
     return this.replace(/^\s+|\s+$/g, ''); 
   };
}


Note : We have to take good care while using trim() function of JavaScript. because it has compatibility issue with IE 8 and older version. So we have to put following line of code in JS, where we used trim function, otherwise function will be given an exception so JavaScript will not be processing further.
if(typeof String.prototype.trim !== 'function') {
   String.prototype.trim = function() {
     return this.replace(/^\s+|\s+$/g, ''); 
   };
}

posted under | 2 Comments

Validate Email Address Using JavaScript

Following code used to validate the email address.


 
function IsEmail(email) {
     var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]  {2,4})+$/;
    return regex.test(email);
}
Example :
We can test email address by above function like :
This function return boolean value , it will return either true or false based on the validation test.
If user has supplied wrong email address then it  will return false otherwise return true.

 
 IsEmail("chauhanvipul87@gmail.com"); -->    output : true
 IsEmail("chauhan.com")               -->    output : false

posted under | 0 Comments

How to open PDF file in new tab using Servlet & Javascript ?

//This functions call when user click on print declaration form button 
public void openPDF(HttpServletRequest req,HttpServletResponse res){
 try {
      ServletContext context = req.getServletContext();
      String contextpath = context.getRealPath("/")+GlobalVariables.OUTPUT_FOLDER;
      HttpSession session = req.getSession();   
      String user_order_id ="";
      if(session.getAttribute("user_order_id") != null){
         user_order_id = session.getAttribute("user_order_id").toString(); //when user_order_id already exists in session .
       }
      String fileName = user_order_id+"-PrintLabels.pdf";
      res.setContentType("application/pdf");
      res.setHeader("Expires", "0");
      res.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
      res.setHeader("Content-Disposition","inline;filename=" + fileName);
      res.setHeader("Accept-Ranges", "bytes");
      File nfsPDF = new File(contextpath+ fileName);
      FileInputStream fis = new FileInputStream(nfsPDF);
      BufferedInputStream bis = new BufferedInputStream(fis);
      ServletOutputStream sos = res.getOutputStream();
      byte[] buffer = new byte[2048];
      while (true) {
        int bytesRead = bis.read(buffer, 0, buffer.length);
        if (bytesRead < 0) {
          break;
        }
      sos.write(buffer, 0, bytesRead);
      sos.flush();
      }
      sos.flush();
      bis.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
} 

Call appropriate servlet url to call this method. Note : Return type must be void. Example : if we have servlet URL like "printLable.html" then open this url dynamically using my earlier post for Open number of new tabs in Browser Using Javascript

posted under | 5 Comments

How to open more then one new tabs in browser using javascript

To open no of new tabs in browser , We have to dynamically create forms on fly on any particular event like page load, on click etc.
//helper function to create the form
function getNewSubmitForm(val){
 var submitForm = document.createElement("FORM");
 document.body.appendChild(submitForm);
 submitForm.method  = "POST";
 submitForm.target  ="_BLANK";
 submitForm.name     ="frm";
 submitForm.id        = val;
 return submitForm;
}
Above function create form element and its set its attributes.
//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
    //Create an input type dynamically.
    var element = document.createElement("input");
    //Assign different attributes to the element.
    element.setAttribute("type", "hidden");
    element.setAttribute("value", elementValue);
    element.setAttribute("name", elementName);
    inputForm.appendChild(element);
    return element;
}
This function set the hidden fields and value of form elements.
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(val){
     var submitForm = getNewSubmitForm(val);
     createNewFormElement(submitForm, "act", "checkurl");
     createNewFormElement(submitForm, "websiteId", val);
     submitForm.action= "test-url.php";
     submitForm.submit();
     return false;
}
Above function create form element and submit form.
function start(start,end){
     for(var i=start;i<=end;i++){
         alert(i);
         createFormAndSubmit(i);
     }
}
By giving start and end limit , we can create no of forms as per our requirements. We can you above function using this single function,it will invoke other functions automatically :
  onclick="start(1,10)"

posted under | 1 Comments

How to find number of dots from string using Javascript


Find number of dots from string using javascript

By using this function we can get the no of repeated character from the string using java script.
function count(s1, letter) {
    return s1.match( new RegExp(letter,'g') ).length;

}
Example 1:
  count('Yes. I want. to. place a. lot of. dots.','\\.'); //=> 
  output : 6
Example 2:
  count('2....3','\\.'); //=> 
  output : 4

posted under | 0 Comments
Newer Posts Home

Followers

Powered by Blogger.

Populares

Custom Search