1
\$\begingroup\$

I've written a short snippet of code to replace JQuery's $.post ( to get ride of JQuery, mainly ). The function does seem to work. But, since I might be using this function in a couple of other pages, I'm just hoping to get a general review of the code.

I'm not confident the parameter formatting is done properly ( I couldn't find a lot of information on the web concerning how to pass parameters to .send( ). So if anyone sees that I have done it correctly or not, that would help.

Here's the code:

function FileRequest(data, successFunction) {
  if(window.XMLHttpRequest)
    request = new XMLHttpRequest();
  else request = new ActiveXObject("Microsoft.XMLHTTP");
  request.onreadystatechange = function () {
    if((request.readyState == 4) && (request.status == 200)) {
      if(typeof (successFunction) == "function") successFunction(request.responseText);
    }
  }
  request.open("POST", "fileHandler.php", true);
  if(typeof (data) != "undefined") {
    var parameterNames = ["command=",
        "arg1=",
        "arg2="
    ],
      parameters = "";
    for(var i = 0; data[i] && (i < 3); i++) {
      parameters += parameterNames[i] + encodeURI(data[i]);
      if(data[i + 1]) parameters += "&";
    }
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", parameters.length);
    request.send(parameters);
  } else request.send();
}

Here's an example of it's use:

FileRequest(["load", "Projects/test.c"], function (data) {
  alert(data);
});
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

First of all, I'd suggest you use a library for several reasons:

  • It's abstracted a lot of cross-browser differences

  • Spread the task of the code to the community. That way you focus more on the task at hand, rather than fixing some bugs.

  • More event and processing support, like on errors, on complete, on success, on beforesend and others.

Anyways, moving to your code

function FileRequest(data, successFunction) {

  //The compiler pulls up variable and function declarations.
  //To avoid visibility confusion, we'll write them that way as well
  var parameters = '';
  var key;

  if(window.XMLHttpRequest)request = new XMLHttpRequest();
  else request = new ActiveXObject("Microsoft.XMLHTTP");

  request.onreadystatechange = function () {
    //the early return pattern is best to avoid deep indention
    //so if the request isn't complete and successful, return
    //also, always use strict comparison when possible
    if(!(request.readyState === 4 && request.status === 200)) return;

    if(typeof successFunction === "function") successFunction(request.responseText);
  }

  //the third parameter defaults to true so we can omit
  request.open("POST", "fileHandler.php");

  //for scalability, you should not hard-code the parameter names
  //allow the user of the API to define the data name.
  //thus we use objects, and the for-in loop

  //since we use objects, we'll have to check if it is
  //the simplest check is to check if it's not null, it's an object but not an array
  if(data && typeof data === 'object' && !(data instanceof Array)){

    for(key in data){
      //similar to early-return pattern, the early continue
      //which skips early if we the condition is met.
      //if the key isn't from the data but from prototype, we skip
      if(!data.hasOwnProperty(key)) continue;

      //append to parameters
      parameters += key + '=' + encodeURI(data[key]) + '&';

    }
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", parameters.length);
  }

  //so we send either a blank or something
  request.send(parameters);
}

FileRequest({
    command : 'load',
    arg1 : 'Projects/test.c'
  },
  function (data){
    //when debugging, use console.log if the browser supports it
    console.log(data);
  }
);
\$\endgroup\$
3
  • \$\begingroup\$ Thanks Joseph, that helps a lot. I agree with your points about using libraries. I usually just re-implement these functions just for practice, mainly. \$\endgroup\$
    – tay10r
    May 11, 2013 at 5:21
  • 1
    \$\begingroup\$ I also noticed that you removed encodeURI( ) from the parameter data. I think that should still be there, if you get a chance \$\endgroup\$
    – tay10r
    May 11, 2013 at 5:25
  • \$\begingroup\$ @TaylorFlores yup, seem to have missed that. \$\endgroup\$
    – Joseph
    May 11, 2013 at 5:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.