How to send data to a server using AJAX? - javascript

We know how to get data from a server using ajax's GET method but can we also send data to a server using ajax? If so, how do we do it?
Also, can you show how to do it without jquery?

var xhr = null;
if (typeof XMLHttpRequest != "undefined") {
xhr = new XMLHttpRequest();
} else if (ActiveXObject) {
var aVersions = [
"Msxml2.XMLHttp.5.0",
"Msxml2.XMLHttp.4.0",
"Msxml2.XMLHttp.3.0",
"Msxml2.XMLHttp",
"Microsoft.XMLHttp"
];
for (var i = 0; i < aVersions.length; i++) {
try {
xhr = new ActiveXObject(aVersions[i]);
break;
} catch (error) {
console.log(error);
}
}
}
if(xhr) {
xhr.open('POST', 'your server url', true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if(xhr.status === 200) {
console.log(xhr.responseText);
}
}
}
xhr.send();
} else {
console.log('cannot create xhr!');
}

Related

How to convert jquery ajax to native javascript?

here is my ajaxHandler i want to convert this to native javascript i.e
using XMLHttpRequest but i am unable to understand how to convert.`
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
Paper.giffyLoading.style.display = 'block';
if (!attributes.nopopup) {
if (attributes.loadmsg) {
Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
attributes.loadmsg = null;
}
}
$.ajax(attributes);
}
}
i have try to convert the above code like this
XMLRequestDefaultHandler = function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'index.php/request', true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {
} else {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
}
};
xmlHttp.send(null);
}
I extracted ajax function of Jquery, to work without jquery.
And replace $.ajax(attributes); to ajax(attributes);
JQuery's ajax function, without JQuery :
function ajax(option) { // $.ajax(...) without jquery.
if (typeof(option.url) == "undefined") {
try {
option.url = location.href;
} catch(e) {
var ajaxLocation;
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
option.url = ajaxLocation.href;
}
}
if (typeof(option.type) == "undefined") {
option.type = "GET";
}
if (typeof(option.data) == "undefined") {
option.data = null;
} else {
var data = "";
for (var x in option.data) {
if (data != "") {
data += "&";
}
data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
};
option.data = data;
}
if (typeof(option.statusCode) == "undefined") { // 4
option.statusCode = {};
}
if (typeof(option.beforeSend) == "undefined") { // 1
option.beforeSend = function () {};
}
if (typeof(option.success) == "undefined") { // 4 et sans erreur
option.success = function () {};
}
if (typeof(option.error) == "undefined") { // 4 et avec erreur
option.error = function () {};
}
if (typeof(option.complete) == "undefined") { // 4
option.complete = function () {};
}
typeof(option.statusCode["404"]);
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
else { xhr = new XMLHttpRequest(); }
} else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }
xhr.onreadystatechange = function() {
if (xhr.readyState == 1) {
option.beforeSend();
}
if (xhr.readyState == 4) {
option.complete(xhr, xhr.status);
if (xhr.status == 200 || xhr.status == 0) {
option.success(xhr.responseText);
} else {
option.error(xhr.status);
if (typeof(option.statusCode[xhr.status]) != "undefined") {
option.statusCode[xhr.status]();
}
}
}
};
if (option.type == "POST") {
xhr.open(option.type, option.url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(option.data);
} else {
xhr.open(option.type, option.url+option.data, true);
xhr.send(null);
}
}

undefined type when i turned my code to Object Javascript AJAX

i don't understand why i get TypeError (this.req is undefined) on line :
if (this.req.readyState === 4) {
function RequestCORS(url) {
this.url = "http://crossorigin.me/" + url;
this.req = new XMLHttpRequest();
}
RequestCORS.prototype.send = function () {
this.req.open("GET", this.url);
this.req.onreadystatechange = function() {
if (this.req.readyState === 4) {
if (this.req.status === 200) {
console.log(this.req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
this.req.send();
};
function main() {
var url = "http://www.01net.com/rss/mediaplayer/replay/";
var requete = new RequestCORS(url);
requete.send();
}
window.addEventListener("load", main);
Thanks for reading.
this.req is undefined because you're making an asynchronous request and by the time your onreadystatechange fires this doesn't refer to your RequestCORS instance anymore.
You could declare a local variable that remains in scope inside the onreadystatechange function.
var req = this.req;
this.req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
console.log(req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
or use bind
this.req.onreadystatechange = function() {
if (this.req.readyState === 4) {
if (this.req.status === 200) {
console.log(this.req.responseText);
} else {
console.log("error request");
//handleError
}
}
}.bind(this);
or get rid of this.req entirely
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
console.log(req.responseText);
} else {
console.log("error request");
//handleError
}
}
};

correct usage of sinon's fake XMLHttpRequest

I am creating XMLHttpRequest javascript module to get JSON data from server. Here is the code:
(function() {
var makeRequest = function(url,callback,opt) {
var xhr;
if (XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (ActiveXObject) { // IE
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!xhr) {
callback.call(this,
'Giving up :( Cannot create an XMLHTTP instance',
null);
return false;
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var data = xhr.responseText;
if(opt && !opt.raw) {
try {
data = JSON.parse(data);
} catch (e) {
callback.call(this, e,null);
return;
}
}
callback.call(this,null,data);
} else {
callback.call(this,
'There was a problem with the request.',
null);
}
}
};
var params = '';
if (opt && opt.params && typeof(opt.params) == 'object') {
for( var key in opt.params) {
params += encodeURIComponent(opt.params[key]);
}
}
var method = opt && opt.method ? opt.method : 'GET';
if (method == 'GET') {
url = params.length > 0 ? url+'?'+params : url;
xhr.open('GET', url);
xhr.send();
} else if (method == 'POST') {
var data = opt && opt.data ? opt.data : params;
xhr.open('POST', url);
xhr.send(JSON.stringify(data));
}
return xhr;
}
if(typeof module !== 'undefined' && module.exports) {
module.exports = makeRequest;
}
if(typeof window!== 'undefined') {
window.getJSONData = makeRequest;
}
})();
Now I am writing the test case for this on nodejs with Mocha and Sinon. Using Sinon's fakeXMLHttpRequest to test the module and test code is here:
var expect = require('chai').expect,
getJSON = require('../'),
sinon = require('sinon');
describe('get-json-data test the request', function() {
beforeEach(function() {
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
});
afterEach(function() {
this.xhr.restore();
});
it('get json data', function() {
var callback = sinon.spy();
getJSON('/some/json', callback);
expect(this.requests.length).to.equal(1);
this.requests[0].respond(200,
{"Content-Type": "application/json"},
'{"id": 1, "name": "foo"}');
sinon.assert.calledWith(callback, {"id": 1, "name": "foo"});
});
});
On running the test I get error:
ReferenceError: XMLHttpRequest is not defined
And it seems correct as there is no XMLHttpRequest class/function in nodejs. But is Sinon's fakeXMLHttpRequest not supposed to do that. I thought in Sinon's setUp (Mocha's beforeEach) we are replacing the native XMLHttpRequest with fakeXMLHttpRequest.
Please suggest what I am doing wrong? Or what would be the correct way to test my module at nodejs?
Because you are running this outside of a browser environment there is no XMLHttpRequest object. Since your are mocking it with Sinon what you can do is declare a fake global function in your beforeEach call.
global.XMLHttpRequest = sinon.useFakeXMLHttpRequest();
I did this for overriding XMLHttpRequest (see my question and answer here):
var FakeXMLHTTPRequests = require('fakexmlhttprequest')
var requests = []
XMLHttpRequest = function() {
var r = new FakeXMLHTTPRequests(arguments)
requests.push(r)
return r
}

AJAX request in IE (all versions)

http://kiwilocals.com.au/dev/
Hello, here is the ajax requests on a category in the middle of the page under the banner. Work everywhere, in addition to all versions of IE.
I checked the developer's tools, a query gives the correct structure, but nothing on the loading icon does not appear after loading. In what may be the reason? Thank you.
function scat(th) {
wait_loading('sub_lst');
if (request = create_request()) {
request.open("GET", "get_subcat.php?id=" + th + "&site=1", true);
request.onreadystatechange = function () {
//alert(request);
if (this.status == 200) {
if (this.readyState == 4) {
var doc3 = document.getElementById('sub_lst');
//alert(doc3);
doc3.innerHTML = this.responseText;
if (!scroll_start) {
$('.sub_scroll').jScrollPane({
animateScroll: true
});
$('.hidden_control').show();
scroll_start = true;
}
}
}
}
request.send(null);
}
}
function create_request() {
var request = false;
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
try {
request = new XMLHttpRequest();
} catch (e3) {
request = false;
}
}
}
if (!request) {
alert("Невозможно выполнить Ajax запрос.");
return false;
} else return request;
}
function wait_loading(el_id) {
document.getElementById(el_id).innerHTML = "<center><img style=\"padding-top: 60px;\" width=\"64\" height=\"64\" src=\"images/loading.gif\"></center>";
}
The problem is with your use of 'this' in the readstatechange event.
Give this a shot.
if(request = create_request()) {
request.open("GET", "get_subcat.php?id="+th+"&site=1", true);
request.onreadystatechange = function() {
if(request.status == 200) {
if( request.readyState == 4 ) {
var doc3 = document.getElementById('sub_lst');
doc3.innerHTML=request.responseText;
if(!scroll_start) {
$('.sub_scroll').jScrollPane({animateScroll: true});
$('.hidden_control').show();
scroll_start=true;
}
}
}
}
request.send(null);
}
But one question... you use jQuery throughout your code, except for this. Why not use:
$('#sub_lst').load("get_subcat.php?id="+th+"&site=1", function(){
if(!scroll_start) {
$('.sub_scroll').jScrollPane({animateScroll: true});
$('.hidden_control').show();
scroll_start=true;
}
});

Run one ajax after another one

I'm working on the project where I (sadly) cannot use jQuery. And I need to do something which is simple in jQuery but I cannot do it in pure JavaScript. So, I need to run one ajax request using a response form another one. In jQuery it will look like:
$.get("date.php", "", function(data) {
var date=data;
$("#date").load("doku.php?id="+date.replace(" ", "_")+" #to_display", function() {
$(document.createElement("strong")).html(""+date+":").prependTo($(this));
});
});
And this is my code in pure JS which isn't working:
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(ObiektXMLHttp)
{
ObiektXMLHttp.open("GET", "date.php");
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
var date = ObiektXMLHttp.responseText;
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
}
}
}
ObiektXMLHttp.send(null);
}
What am I doing worng?
You forgot to call ObiektXMLHttp.send(null); on second case:
//....
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function() {
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
};
//Here
ObiektXMLHttp.send(null);
How about something like this (naive prototype):
// xhr object def
var xhr = {
obj: function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
throw new Error("can't init xhr object");
},
get: function(url, fn) {
var xhr = this.obj();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
fn(xhr.responseText);
}
};
xhr.open("GET", url);
xhr.send(null);
}
};
// implementation
xhr.get("date.php", function(data){
xhr.get("doku.php?id=" + data.replace(" ", "_"), function(data){
alert(data);
});
});
It's not clear what you got wrong (can you tell us?), but I'd suggest to rely on some helper function like this:
function xhrGet(url, callback) {
if (window.XMLHttpRequest)
var xhr = new XMLHttpRequest();
else if (window.ActiveXObject)
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
if (!xhr) return;
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (typeof callback === "function") callback(xhr);
};
xhr.send(null);
return xhr;
}
So all you have to do is to use this function:
xhrGet("date.php", function(x1) {
xhrGet("doku.php?id=" + date.replace(" ", "_"), function(x2) {
// do stuff
// x1 and x2 are respectively the XHR object of the two requests
});
});

Categories