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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tommy B.
  • 3,591
  • 14
  • 61
  • 105
  • 2
    I see no real reason why these two libraries wouldn't work. – Pekka Aug 12 '10 at 18:46
  • possible duplicate of [How to make an ajax call without jquery?](http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery) – parvus Nov 27 '13 at 10:00
  • I even use microajax in my large scale website, but might will shift to jquery http://static.lastdates.com/package/microajax/test.html – Atul Gupta Sep 13 '14 at 03:35
  • 1
    I just discovered superagent.. looks like a compact, popular alternative to jQuery.ajax... http://visionmedia.github.io/superagent/ – Keeth Feb 13 '15 at 19:04
  • https://github.com/nicematt/url-request –  Sep 05 '16 at 11:26

6 Answers6

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

Ryan Kinal
  • 17,414
  • 6
  • 46
  • 63
  • Oh but now what I forgot was: it should be cross-domain :O – Tommy B. Aug 12 '10 at 19:23
  • Ooh, that's a rough one. [researches] – Ryan Kinal Aug 12 '10 at 19:24
  • 3
    @Tom I'd say that's worth a question of its own. – Pekka Aug 12 '10 at 19:28
  • Updated with an untested answer :-D – Ryan Kinal Aug 12 '10 at 19:38
  • @Ryan nice work, and even more minimalistic than a normal Ajax call :) – Pekka Aug 12 '10 at 19:47
  • I think you have to do both, actually. Since the JSON object isn't assigned to any variable, there's no good way to reference it. It sucks, but that's the price you pay for subverting the system ;-) – Ryan Kinal Aug 12 '10 at 19:55
  • i think the ie way should be Msxml2.XMLHTTP no microsooft.XMLHTTP something like: function createXMLHttpRequest() { try { return new XMLHttpRequest(); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){} alert("XMLHttpRequest not supported"); return null; } – Shimon Doodkin Feb 03 '13 at 11:29
  • The last technique (adding a ` – Ben Regenspan Jul 10 '13 at 02:04
  • Correction to the above: IE8 and IE9 do need something extra to make CORS work -- https://gist.github.com/eriwen/2794392 looks like a nice function that incorporates what's needed. – Ben Regenspan Jul 10 '13 at 03:04
  • 1
    For future reference, [xdomain](https://github.com/jpillora/xdomain) is a very good option for cross-domain scripting. – Ryan Kinal May 22 '14 at 22:03
  • Check https://github.com/nicematt/url-request? –  Sep 05 '16 at 11:27
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

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
msaspence
  • 1,424
  • 2
  • 14
  • 25
  • This is very good suggestion. Who would downvote it and why? Go SE!. – Phil Nov 16 '13 at 19:32
  • 2
    Thanks @phil, a disgruntled lover maybe – msaspence Jan 17 '14 at 16:39
  • 2
    http://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. – Keeth Feb 13 '15 at 19:02
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)  });
Shimon Doodkin
  • 4,310
  • 34
  • 37
3

So...tiny...

var obj = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : (XMLHttpRequest && new XMLHttpRequest()) || null;
Rion
  • 47
  • 1
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.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
agaase
  • 1,562
  • 1
  • 15
  • 24
-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.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088