Skip to content

Instantly share code, notes, and snippets.

@Ashkanph
Last active September 1, 2018 06:56
Show Gist options
  • Save Ashkanph/494b79f16e6949b130d7db414e4b43be to your computer and use it in GitHub Desktop.
Save Ashkanph/494b79f16e6949b130d7db414e4b43be to your computer and use it in GitHub Desktop.
JQuery and pure javascript Ajax

jQuery

$.ajax('myservice/username', {
    data: {
        id: 'some-unique-id'
    }
})
.then(
    function success(name) {
        alert('User\'s name is ' + name);
    },

    function fail(data, status) {
        alert('Request failed.  Returned status of ' + status);
    }
);

Native XMLHttpRequest Object

var xhr = new XMLHttpRequest();
xhr.open('GET', 'myservice/username?id=some-unique-id');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('User\'s name is ' + xhr.responseText);
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();

jQuery

var newName = 'John Smith';
$.ajax('myservice/username?' + $.param({id: 'some-unique-id'}), {
    method: 'POST',
    data: {
        name: newName
    }
})
.then(
    function success(name) {
        if (name !== newName) {
            alert('Something went wrong.  Name is now ' + name);
        }
    },

    function fail(data, status) {
        alert('Request failed.  Returned status of ' + status);
    }
);

Native XMLHttpRequest Object

var newName = 'John Smith',
    xhr = new XMLHttpRequest();
xhr.open('POST', 'myservice/username?id=some-unique-id');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
    if (xhr.status === 200 && xhr.responseText !== newName) {
        alert('Something went wrong.  Name is now ' + xhr.responseText);
    }
    else if (xhr.status !== 200) {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send(encodeURI('name=' + newName));

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment