Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a reusable function to open and send Ajax

I have noted that in my program every time when I want to declare a object, for example list, save, add, remove I write the following every time in each function.

ajax.open("Get", "./route/action",true);     
ajax.send();

I want to do something like this.

//this.ajax.get('./route/action').update('ajax-content');
./route/action // this is path to my Action class-using servlet

Every time I have to open a connection, give the path to my action class which is a servlet and then send. I do this every time I want to load a list, delete or update.

How can I write a function that I will be just be:

this.ajax.get('./route/action');
// 'ajax.content' is the id of the div where I 
// want to show the list,where after updating AJAX show the update list to the user.
update('ajax-content'); 

For example after adding a user I can see the added user without reloading the whole page. I am working on a maven project using Java EE, Servlet and JavaScript.

like image 234
S. Kiragu Avatar asked Jun 24 '16 12:06

S. Kiragu


2 Answers

A complete code to do that is, The form fields is where now you'd put your form details

var App = App || {};

App.extend = function(proto, literal){
      var newLiteral = Object.create(proto);
      Object.keys(literal).forEach(function(k){
          newLiteral[k] = literal[k];
      })

      return newLiteral;
};

App.Cmp = {
        responseTarget: '',
        httpMethod: 'GET',
        async: true,
        httpUrl: '',
        requestParams: '',
        updateTarget: function(resp){
            document.getElementById(this.responseTarget).innerHTML = resp;
        },
        ajaxRequest: function(){
            var me = this;
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function(){

                if(xhr.readyState == 4){
                    if(xhr.status == 200){
                        me.updateTarget(xhr.responseText);
                    }
                }
            }

            xhr.open(me.httpMethod, me.httpUrl, me.async);
            if(me.requestParams)
                xhr.send(me.requestParams);
            else
                xhr.send();
        },
        fromFields: [],
        form:  function(){
            var me = this;
            var form = '<form>';

            me.fromFields.forEach(function(el){
                form += '<div class="form-group">'
                    + '<div class="input-group">'
                    + '<div class="input-group-addon">' + el.label + '</div>';

                if(el.type == 'select' && el.options){
                    form += '<select class="form-control">';
                        el.options.forEach(function(opt){
                            form += '<option value='+ opt.value + '>' + opt.label + '</option>'
                        });
                    form += '</select>';
                }else
                    form += '  <input type="' + el.type + '" name="' 
                        + el.name + '" class="form-control" id="' + el.id + '">'

                form += '</div></div>';
            })

          form +=  '</form><a class="btn btn-success" id="' + me.formId+ '-save">Save</a>';

          me.updateTarget(form);

          document.getElementById(me.formId+ '-save').addEventListener("click", function(){
              me.submitForm();
          });
    },
    formId: '',
    formUrl: '',
    submitForm: function(){
        var me = this;

        var formValues = me.fromFields.filter(function(el){
            var formEl = document.getElementById(el.id);
            if(formEl && formEl.value)
                return el;

        }).map(function(el){
            var formEl = document.getElementById(el.id);
            return encodeURIComponent(el.name) + '=' 
                + encodeURIComponent(formEl.value);

        }).join('&');

        me.ajaxRequest.call({
            httpMethod: 'POST',
            httpUrl: me.formUrl,
            requestParams: formValues,
            responseTarget: me.responseTarget,
            updateTarget: function(resp){
            document.getElementById(me.responseTarget).innerHTML = resp;
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(params);
            }
        });

    },
    tableStore: '',
    table: function(tableUrl){
        var me = this;
        me.responseTarget = 'ajax-content';
        me.httpUrl = tableUrl;
        me.ajaxRequest();
    }
};

(function(){
    App.Cmp.table("./company/action");
})();
like image 87
S Murani Avatar answered Sep 26 '22 19:09

S Murani


  var App = App || {};//check if App is defined, if not assign
  empty
  //some inheritance here
  //pass some arguments
  App.extend = function (proto,literal){ 
  var newLiteral = Object.create(proto);//new object with the 
  specified prototype object and properties.
  Object.keys(literal).forEach(function(k){
  newLiteral[k] = literal[k];
  return newLiteral;//return some properties of the object in   a
   array
  })
  }
  //define some attributes in the created obj
  App.Cmp{
  responseTarget : '',
  httpMethod : 'GET', //can be overriden in case of POST
  httpUrl : '',
  requstParams : [],
  updateTarget : function (resp){
  document.getElementById(this.responseTarget).innerHTML = resp;
  //this refer to the new created object
  },
  ajaxRequest : function(){
  var me = this; //this refers the scoop of this function
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
  if(xhr.readyState == 4){
  if(xhr.status == 200){
  me.updateTarget(xhr.responseText);
  }
  }
  }
  xhr.open(me.httpMethod, me.httpUrl, me.async);
  //will define the method and give the url to the action
  xhr.send();
  },
  //to use it need we need to extend this.
  //have been using jsp form but can also define a form object 
  that I can extend every time I need a form.
  formFields :
  .
  .
  .
  }
  }
  //now I have something like every time I need a form,list with 
  ajax, 
  //can also add save, delete, e.t.c
  var route = App.extend(App.Cmp,{
  formFields:
  .
  .
  .
  });
like image 29
S. Kiragu Avatar answered Sep 24 '22 19:09

S. Kiragu