27

I'm looking for a very small (one liner) Ajax JavaScript library to add on the first line of a small script to make some requests.

I already tried:

But they do not work at all. Alternatives?

5

6 Answers 6

32

Here you go, pretty simple:

function createXHR()
{
    var xhr;
    if (window.ActiveXObject)
    {
        try
        {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e)
        {
            alert(e.message);
            xhr = null;
        }
    }
    else
    {
        xhr = new XMLHttpRequest();
    }

    return xhr;
}

Documentation is here

Example:

var xhr = createXHR();
xhr.onreadystatechange = function()
{
    if (xhr.readyState === 4)
    {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'test.txt', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send()

Update:

In order to do cross-domain scripting, you'll either have to call out to a local server-side proxy (which reads and echo's the remote data), or, if your remote service returns JSON, use this method:

var s = document.createElement('script')
s.src = 'remotewebservice.json';
document.body.appendChild(s);

Since JSON is essentially a JavaScript object or array, this is a valid source. You theoretically should then be able to call the remote service directly. I haven't tested this, but it seems to be an accepted practice:

Reference: Calling Cross Domain Web Services in AJAX

Sign up to request clarification or add additional context in comments.

11 Comments

Oh but now what I forgot was: it should be cross-domain :O
Ooh, that's a rough one. [researches]
@Tom I'd say that's worth a question of its own.
Updated with an untested answer :-D
For future reference, xdomain is a very good option for cross-domain scripting.
|
20

You can build your own version of jQuery that only includes the AJAX modules.

https://github.com/jquery/jquery#how-to-build-your-own-jquery
https://github.com/jquery/jquery#modules

3 Comments

This is very good suggestion. Who would downvote it and why? Go SE!.
Thanks @phil, a disgruntled lover maybe
projects.jga.me/jquery-builder suggests that even an ajax-only jQuery 2.1.1 is 18kb gzipped and minified (full jQuery is 28kb). Just wanted to mention this as I was surprised it wasn't smaller.
3

So...tiny...

var obj = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : (XMLHttpRequest && new XMLHttpRequest()) || null;

1 Comment

Much ajax. Such wow.
3

Here is my version with async callback in node.js style

https://gist.github.com/4706967

// tinyxhr by Shimon Doodkin - licanse: public doamin - https://gist.github.com/4706967
//
// tinyxhr("site.com/ajaxaction",function (err,data,xhr){ if (err) console.log("goterr ",err,'status='+xhr.status); console.log(data)  });
// tinyxhr("site.com/ajaxaction",function (err,data,xhr){ if (err) console.log("goterr ",err,'status='+xhr.status); console.log(data)  },'POST','value1=1&value2=2');
// tinyxhr("site.com/ajaxaction.json",function (err,data,xhr){ if (err) console.log("goterr ",err,'status='+xhr.status); console.log(data); console.log(JSON.parse(data))  },'POST',JSON.stringify({value:1}),'application/javascript'); 
// cb - function (err,data,XMLHttpRequestObject){ if (err) throw err;   }
// 

function tinyxhr(url,cb,method,post,contenttype)
{
 var requestTimeout,xhr;
 try{ xhr = new XMLHttpRequest(); }catch(e){
 try{ xhr = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e){
  if(console)console.log("tinyxhr: XMLHttpRequest not supported");
  return null;
 }
 }
 requestTimeout = setTimeout(function() {xhr.abort(); cb(new Error("tinyxhr: aborted by a timeout"), "",xhr); }, 5000);
 xhr.onreadystatechange = function()
 {
  if (xhr.readyState != 4) return;
  clearTimeout(requestTimeout);
  cb(xhr.status != 200?new Error("tinyxhr: server respnse status is "+xhr.status):false, xhr.responseText,xhr);
 }
 xhr.open(method?method.toUpperCase():"GET", url, true);

 //xhr.withCredentials = true;

 if(!post)
  xhr.send();
 else
 {
  xhr.setRequestHeader('Content-type', contenttype?contenttype:'application/x-www-form-urlencoded');
  xhr.send(post)
 }
}

tinyxhr("/test",function (err,data,xhr){ if (err) console.log("goterr ",err); console.log(data)  });

Comments

0

You can probably use omee. Its a single file containing many frequently used javascript functions like ajax request.

https://github.com/agaase/omee/blob/master/src/omee.js

to raise an ajax request you just call omee.raiseAjaxRequest

with arguments

params- parameters list e.g param1=param1value&param2=param2value

url - url to hit the server

func- function name which is to be called back

connType - GET/POST.

Comments

-2

Well...... jQuery is probably bigger than what you want, but it's arguably still a very good option. It's well documented, well supported, and if you use the CDN link

http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

it is even very likely to be present and cached on the client's machine already.

5 Comments

@Radu cheers, that URL was what I meant.
Thanks but I only wanted a little snippet. I use jQuery for all my javascript-related work but for this time I needed something very small.
@Tom then @Ryan's approach should be perfect - it's as small as it'll get.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.