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);
    }
5
  • 2
    Nice, but what ajaxRequest is exactly? Besides, can you change the request to POST? Having more than 20 params can be dangerous considering some browsers have url limit. Commented Dec 30, 2014 at 15:17
  • 1
    @DontVoteMeDown i provided ajaxRequest function. I know that That's why i am asking any batter approach to do this. Commented Dec 30, 2014 at 15:19
  • I see. Check this post. Commented Dec 30, 2014 at 15:21
  • 1
    @DontVoteMeDown I know this. So how to solve this problem. Commented Dec 30, 2014 at 15:25
  • 1
    can some buddy explain why 2 down vote is there ? Commented Dec 30, 2014 at 15:38

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

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.
@NaimishViradia: You could loop over the elements in the form and create this params object.
can i do this same for post also ?
@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.
Hi Just last question can explain reason for down vote and how to undo it.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.