0

So I want to use ajax request and I know how to use it.

But problem that i had that I want to pass parameters to request. So My first page had 4 parameter then I build url like this,

var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;

but now parameter is increasing like now I have 20 more. So now building url like this going to be messy approach. Is there a better way to do this.

Here is my function where i am building URL in javascript function.

function closeAssessment() {

            var closeReason = document.getElementById("SectionClousureReason");
            var closeReasonStr = closeReason.options[closeReason.selectedIndex].value;
            var closeCmt=document.getElementById("SectionCloseAssessmentCmt").value;

                var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
                ajaxRequest(url);
                return;

    }

edit:

As you ask here is my ajaxRequest function,

function ajaxRequest(url) {
        strURL = url;
        var xmlHttpRequest = false;
        var self = this;
        // Mozilla, Safari
        if (window.XMLHttpRequest) {
            self.xmlHttpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
            self.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        self.xmlHttpRequest.open("POST", strURL, true);
        self.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        self.xmlHttpRequest.onreadystatechange = function() {
            if (self.xmlHttpRequest.readyState == 4) {
                if (self.xmlHttpRequest.status == 200) {
                    var htmlString = self.xmlHttpRequest.responseText;
                    var parser = new DOMParser();
                    var responseDoc = parser.parseFromString(htmlString, "text/html");
                    window.close();
                } else {
                    ajaxFailedCount++;
                    // Try for 1 min (temp fix for racing condition)
                    if (ajaxFailedCount < 1200) {window.setTimeout(function() {ajaxRequest(url)}, 50);}
                    else {alert("Refresh failed!")};
                }
            }
        }
        self.xmlHttpRequest.send(null);
    }
JBaba
  • 590
  • 10
  • 30

2 Answers2

2

You could make an object with the key/value pairs being what you want added to the URL.

var closeReason = document.getElementById("SectionClousureReason");
var params = {
    PAGE_ID: 'BPCLA',
    ACTION: 'closeAssessment',
    SAVE_FLAG: 'true',
    closeReasonStr: closeReason.options[closeReason.selectedIndex].value,
    closeCmt: document.getElementById("SectionCloseAssessmentCmt").value
};

Then add them to the URL via a loop.

var url = "./ControllerServlet?";
var urlParams = Object.keys(params).map(function(key){
    return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');

url += urlParams;
ajaxRequest(url);

Note: I added encodeURIComponent just to be safe.

EDIT: From your comment, it seems you want to submit a <form> but you want to use AJAX to do so. In that case, you can loop over the form elements and build the above params object.

var params = {
    PAGE_ID: 'BPCLA',
    ACTION: 'closeAssessment',
    SAVE_FLAG: 'true'
};

var form = document.getElementById('yourForm'),
    elem = form.elements;

for(var i = 0, len = elem.length; i < len; i++){
    var x = elem[i];
    params[x.name] = x.value;
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 1
    if i use this approach still i need to retrieve all parameter and pass in this object. We have form element. can't we pass full form in request ? which already has all elements. – JBaba Dec 30 '14 at 15:23
  • 1
    @NaimishViradia: You could loop over the elements in the form and create this `params` object. – gen_Eric Dec 30 '14 at 15:25
  • 1
    can i do this same for post also ? – JBaba Dec 30 '14 at 15:29
  • 2
    @NaimishViradia: It should work for POST too. Just do `self.xmlHttpRequest.send(urlParams);`. Actually on modern browsers, you can just do `var data = new FormData(document.getElementById('yourForm')); self.xmlHttpRequest.send(data);` without needing any loops. – gen_Eric Dec 30 '14 at 15:31
  • Hi Just last question can explain reason for down vote and how to undo it. – JBaba Dec 30 '14 at 15:46
0

Build up an object of your parameters and put them in the uri through a loop like this:

var values= {
    page_id: 'BPCLA',
    action:  'test'
},
uri_params = [],
uri = 'http://yoururl.com/file.php?';

for (var param in values) uri_params.push( encodeURIComponent( param ) + '=' + encodeURIComponent( values[ param ] ) );

uri = uri + uri_params.join( '&' );
console.log( uri );

Or consider using POST to transport your parameters, as many browsers have limitations on the query string.


Edit: you can also build yourself a function which traverses your form and builds up the values object for you so you don't have to do it manually. Be aware however that anyone can inject custom url paramters simpy by appending form elements before submitting the form (by using the developer tools for example) so keep that in mind.

If you are using jQuery you can use .serializeArray() or have a look at this answer for a possible function you could use.

Community
  • 1
  • 1
Marco Kerwitz
  • 5,294
  • 2
  • 18
  • 17