JavaScript Custom ajax() function - Replacing jQuery

Ghost

Active Coder
Moderator
Apr 19, 2019
317
142
43
Hello all,

Today I want to quickly show you my custom ajax() function that uses core JavaScript.
I am slowly creating functions with JS that make using core JS easier for a site, without adding in all of the bloat from a library like jQuery.
I started off with an AJAX function because I have noticed that a lot of our sites use jQuery for two reasons: Bootstrap requirements & AJAX.
However, not all of our sites (that we make for clients, or for ourselves) use Bootstrap, but many of our developers have gotten so accustomed to using jQuery that they want to use it even when a project really doesn't need it... So, I've started making functions that take care of annoying things like AJAX & modal pop ups for projects that really don't need jQuery, but could benefit from some easy to use functions :)

I don't want to go through every single line, so this won't be labeled as a tutorial, but you can feel free to use the function in your own projects :)
As you can see, the first block of code is the full AJAX request, which is a lot easier to use as a function. You can just use the function (2nd code block below) to make your life a lot easier, without using a big library such as jQuery to do so :)


Current code:
JavaScript:
function ajax(object){
    if(object.method.length > 0 && typeof object.method != undefined){
        var Request = new XMLHttpRequest();
        if(typeof object.url != 'undefined' && object.url.length > 0 && typeof object.method != 'undefined' && object.method.length > 0){
            if(typeof object.data === "object"){
                var encodeURIString = "";
                for (var objProperty in object.data){
                        if (object.data.hasOwnProperty(objProperty)){
                                if(encodeURIString.length > 0){
                                    encodeURIString += '&';
                                }
                                encodeURIString += encodeURI(objProperty + '=' + object.data[objProperty]);
                        }
                }
            } else {
                encodeURIString = "";
            }
            if(object.method === "POST"){
                Request.open(object.method, object.url);
                Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                Request.send(encodeURIString);
            } else if(object.method === "GET"){
                if(encodeURIString != ""){
                    object.url = object.url + "?" + encodeURIString;
                }
                Request.open(object.method, object.url);
                Request.send();
            } else {
                console.log("The AJAX Method must be either 'POST' or 'GET'");
                return false;
            }
        } else if(typeof object.url == 'undefined' || object.url.length === 0){
            console.log("The AJAX URL cannot be empty or undefined.");
            return false;
        } else if(typeof object.method == 'undefined' || object.method.length === 0){
            console.log("The AJAX Method cannot be empty or undefined.");
            return false;
        } else {
            console.log("The AJAX Method must be either 'POST' or 'GET'");
            return false;
        }
        Request.onload = function(){
            if(Request.status === 200){
                if(typeof object.success == "function"){
                    object.success(Request.responseText);
                } else {
                    console.log("The XMLHttpRequest succeeded, but no success function was supplied to the ajax() function.");
                }
            } else {
                if(typeof object.fail == "function"){
                    object.fail(Request.statusText);
                } else {
                    console.log("The XMLHttpRequest failed, but no fail function was supplied to the ajax() function.");
                }
            }
        } // onload func
    }
}
Example:


JavaScript:
ajax({
    method: "POST",
    url: "sendmsg.php",
    data: {
        message: 'hi',
        userid: 5
    },
    success: function(data){
        console.log(data);
    },
    fail: function(data){
        alert(data);
    }
});
 

Malcolm

Administrator
Administrator
Jan 2, 2018
988
268
75
Canada
codeforum.org
That's awesome, @Ghost! Really appreciate you sharing this! Not too familiar with those yet, but definitely think it will help when I start using JavaScript - jQuery and Ajax.
 

Ghost

Active Coder
Moderator
Apr 19, 2019
317
142
43
That's awesome, @Ghost! Really appreciate you sharing this! Not too familiar with those yet, but definitely think it will help when I start using JavaScript - jQuery and Ajax.
Yeah, of course!
You should definitely try your hand at some core JS, or if it is too annoying then give jQuery a try because it simplifies a lot of things. As you can see, the actual function I wrote has a lot of lines, but I can use the function easily. jQuery is the same, but they do this for almost everything. Core JS requires many lines of code that jQuery can simplify down to 3-10 lines. So, I highly recommend it for a starting point. However, learning core JS has the huge benefit of teaching you what's actually going on. jQuery does a lot behind the scenes, as does my function here, so if you just use it without learning the mechanics it can be tough to fix things or alter the way something works if anything breaks.
 

joe

New Coder
Aug 21, 2019
19
7
3
Thats a really nice piece of code :)

It would be cool to extend the ajax function and make it accept an option called 'statusCode' (similar to jQuery) so that users can define different functions for different status codes received as response.

For example:

JavaScript:
ajax({
    method: "POST",
    url: "sendmsg.php",
    data: {
        message: 'hi',
        userid: 5
    },
    statusCode: {
        201: function(){
            console.log('New record added into database!');
        },
        403: function(){
            console.log('Access forbidden!');
        }
    }
});
 

Ghost

Active Coder
Moderator
Apr 19, 2019
317
142
43
Thats a really nice piece of code :)

It would be cool to extend the ajax function and make it accept an option called 'statusCode' (similar to jQuery) so that users can define different functions for different status codes received as response.

For example:

JavaScript:
ajax({
    method: "POST",
    url: "sendmsg.php",
    data: {
        message: 'hi',
        userid: 5
    },
    statusCode: {
        201: function(){
            console.log('New record added into database!');
        },
        403: function(){
            console.log('Access forbidden!');
        }
    }
});
Sure, that's a great idea.
I need to revisit this code to lower the # of if statements in the beginning, support status codes like you mentioned, and also support file upload Ajax.