Unique Javascript Library Focused on AJAX

Looking for a specific JavaScript library that focuses solely on AJAX functionality, such as a basic XMLHttp wrapper.

Answer №2

Though it may not resemble a conventional library, what I have here is my own creation - a "Small Simple XMLHttp Wrapper":

//params format:"bob=hi&id=1295&lol=haha"
function ajax_post(post_url,params,success_callback,fail_callback,timeout)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("POST",post_url, true);

    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    //xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState == 4 ) 
        {
            clearTimeout(xmlHttpTimeout); 
            if(xmlHttp.status == 200)
            {
                success_callback();
            }
            else 
            {
                    fail_callback();
            }
        }
    }
    xmlHttp.send(params);

    var xmlHttpTimeout=setTimeout(ajaxTimeout,timeout);
    function ajaxTimeout()
    {
       xmlHttp.abort();
       fail_callback();
    }

}

function ajax_get(url,success_callback,fail_callback,timeout)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET",url, true);

    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState == 4 ) 
        {
            clearTimeout(xmlHttpTimeout); 
            if(xmlHttp.status == 200)
            {
                success_callback(xmlHttp.responseText);
            }
            else 
            {
                    fail_callback();
            }
        }
    }
    xmlHttp.send();

    var xmlHttpTimeout=setTimeout(ajaxTimeout,timeout);
    function ajaxTimeout()
    {
       xmlHttp.abort();
       fail_callback();
    }

} 

Answer №3

During a time when my knowledge of JavaScript was limited, I created a basic JavaScript PHP wrapper that lacks AJAX methods but includes functions to interact with a PHP backend for processing tasks.

If you are seeking something similar, consider dedicating a few hours to building an AJAX library with essential helper functions.

The JavaScript Implementation:

(function() {

var
    PHPJS = window.PHPJS = window.$ = function() {
      return new PHPJS.Strings;
  };

PHPJS.Strings = PHPJS.prototype = {

    InitAJAX: function(Library, ServerString)
    {
        var ResultCache = document.body;
        var FunctionRequest;
        try {
            FunctionRequest = new XMLHttpRequest();
        } catch (e) {
            try {
                FunctionRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    FunctionRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    throw new Error("The XMLHttpRequest() object is not supported by your browser.")
                    return false;
                }
            }
        }

        FunctionRequest.onreadystatechange = function() {
            if (FunctionRequest.readyState == 4 && FunctionRequest.status == 200) {
                ResultCache.innerHTML = FunctionRequest.responseText;
                return FunctionRequest.responseText;
            }
        } 

        switch (Library) {
            case 'Arrays' :
            FunctionRequest.open("GET", "functions/arrays-lib.php" + ServerString, true);
            break;
            case 'Math' :
            FunctionRequest.open("GET", "functions/math-lib.php" + ServerString, true);
            break;
            case 'Strings' :
            FunctionRequest.open("GET", "functions/strings-lib.php" + ServerString, true);
            break;
        }
        FunctionRequest.send(null);
    },

    /* String Functions */
    addcslashes: function(str, charlist)
    {
        return this.InitAJAX('Strings','?function=addcslashes&String='+str+'&Charlist='+charlist);
    },
    addslashes: function(str)
    {
        return this.InitAJAX('Strings','?function=addslashes&String='+str);
    },
    bin2hex: function(str)
    {
        return this.InitAJAX('Strings','?function=bin2hex&String='+str);
    },
    chop: function(str,charlist)
    {
        return this.InitAJAX('Strings','?function=chop&String='+str+'&Charlist='+charlist);
    },
    chr: function(int)
    {
        return this.InitAJAX('Strings','?function=chr&Int='+int);
    },
    chunk_split: function(str, chunklen, end)
    {
        return this.InitAJAX('Strings','?function=chunk_split&String='+str+'&Chunklen='+chunklen+'&End='+end);
    },
    convert_cyr_string: function(str)
    {
        return this.InitAJAX('Strings','?function=convert_cyr_string');
    },

    /* more functions... */
}

})();

//PHPJS.bin2hex('afsdfadsafdsafdasfsaf');   

The PHP Backend:

<?php
switch($_GET['function']) {
    case 'addcslashes' :    
        $charlist = (@$_GET['Charlist']) ? ','.$_GET['Charlist'] : '';
        echo addcslashes($_GET['String'], $charlist);
    break;
    case 'addslashes' : 
        echo addslashes($_GET['String']);
    break;
    case 'bin2hex' :    
        echo bin2hex($_GET['String']);
    break;
    case 'chop' :   
        $charlist = (@$_GET['Charlist']) ? ','.$_GET['Charlist'] : '';
        echo rtrim($_GET['String'], $charlist);
    break;
    case 'chr' :
        echo chr($_GET['Int']);
    break;
    case 'chunk_split' :
        echo chunk_split($_GET['String'], @$_GET['Chunklen'], @$_GET['End']);
    break;
        /** ...etc, etc... **/
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

What is the mechanism behind the functioning of StackOverflow's notification system?

Could you explain the technique that is utilized to transmit and receive data from the client to the server? How does it manage to provide almost real-time results when new changes take place? Can anyone demonstrate the code being used for this process? ...

What is the process for including a new item in an array of objects?

const data = [ { title: 'Tasks', items: ['complete assignments', 'study for exams'], }, { title: 'Ongoing', items: ['learn new skills', 'work on projects'], }, { titl ...

Jquery refuses to conceal a particular element

I've encountered this issue before, but I'm facing a problem this time. I'm attempting to create a popup that is initially hidden. When clicked, the popup does appear, but I'm unable to close it. Additionally, when trying to change the ...

"Utilize jQuery AJAX Promises to Trigger Custom Exceptions that can be Handled by the Outer fail() Function

Imagine having a function that yields a promise. The promise returned is scrutinized by other functions to determine how to manage the .fail() condition. function refreshTimeline() { var promise = ajaxMethod1() .then (function (data) ...

Replace all instances of the same word with the word "and" using regular expressions

If we look at the sentence below: Blue shirt blue hat Can regular expressions be used to detect 2 matching words and replace the second one with and so it reads: Blue shirt and hat Now, let's tackle a more complex example. In this case, we nee ...

What is the best way to utilize delayed_job?

After reviewing the documentation, I am struggling with integrating it into my application. Currently, users input a video URL, which is converted into a link in the view. Then, I utilize the Embedly API to transform that link into an embedded video, alo ...

Run JavaScript code when the HTML file has been modified for the second time

After browsing through this online forum, I stumbled upon a helpful solution. See the code snippet below for reference. However, I encountered a problem in my case. The script in question is essentially monitoring itself. The code resides in index.html an ...

Django pretends that the user is logged in when they really aren't

I have a login feature in my Django project that uses AJAX. The ajax_login function in the view processes the POST request, authenticates the user, and returns a JsonResponse. Strangely, everything seems to be functioning correctly, but the user isn't ...

Transform your Image into Base64 and easily upload it using AJAX

Is there a way to convert an image to Base64 and send it via AJAX for processing without relying on any external library? Just using basic HTML <input type="file" id="image" accept="image/*"> Via AJAX $(document).on(&a ...

When attempting to display uploaded files using a War file in Tomcat, the files are not appearing as

When using Ajax file upload, I noticed that the newly uploaded images are not reflected in the WAR file. Only the name is being inserted into the database. This issue is present in Eclipse as well, where I have to manually refresh the project folder after ...

Apply a custom filter to ng-repeat results

Asking for advice on how to iterate over an array using ng-repeat and filter the contained objects based on a function property. Find more details in this Plunker link. Let's say we have an object like this: vm.show1 = function(){ return true; }; ...

Should Bower and Grunt Be Installed Globally or Locally?

When it comes to installing packages globally, we typically avoid it due to the possibility of working on multiple projects simultaneously that require different versions of the same libraries. However, there seems to be conflicting information regarding t ...

Obtain the inner text input value using jQuery

In my form, there is a feature that adds a new row of text inputs dynamically when a user wants to add more rows. Each new row is automatically populated with input fields that have the same id and class as the previous ones. My question is: how can I re ...

Using setInterval on a batch of freshly generated div elements

I am interested in creating a small website where I can display multiple clocks for various time zones. However, I have encountered an issue with the setInterval function. Below is the code snippet: function addClock () { $("#container").append('& ...

Writing and altering content within the <code> element in Chrome is unreliable

Utilizing a WYSIWYG Editor with contenteditable functionality allows users to input "code snippets" using a <code> element. Here is an example: <div contenteditable="true"> <p> This is a paragraph with an <code>inline s ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Transform a string into a JSON entity

Can JavaScript be used to convert a string such as this: "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000" into a JSON object like the one below: { "Product":"Bike", "2005" : $12000, "2006" : $13000, "2007" : $14 ...

Retrieving the output from a nested function within a function in a Node.js application connected to a

I'm currently working on a basic web application that interacts with a database by performing INSERT and SELECT operations on a single table. While I have utilized a function from various tutorials, I am struggling to retrieve the results from the SEL ...

What is the key element missing from my code while attempting to integrate Threejs into React?

I recently undertook the task of converting a project from vanilla Three.js to React. For reference, here is the original project: https://codepen.io/Mamboleoo/pen/rNmRqeK And here is the code I have been working on: You can view the code in CodeSandbox ...