Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Custom ajax() function - Replacing jQuery

Ghost

Platinum Coder
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);
    }
});
 
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.
 
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.
 
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:

[CODE lang="javascript" highlight="8-15"]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!');
}
}
});[/CODE]
 
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:

[CODE lang="javascript" highlight="8-15"]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!');
}
}
});[/CODE]
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.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom