I wanted to use AJAX delete request without using jquery is it possible to do that my json object at localhost:8000 looks like this :
{
"Students":[{"Name":"Kaushal","Roll_No":30,"Percentage":94.5},
{"Name":"Rohit","Roll_No":31,"Percentage":93.5},
{"Name":"Kumar","Roll_No":32,"Percentage":45.5}]}
I want to have a delete button which can delete a single record.Code would be appreciated.
function loadDoc(){
var table2="<tr><th>Name</th><th>Roll_No</th><th>Percentage</th></tr>"
var url2="http://localhost:8000/Students"
var xhttp2=new XMLHttpRequest();
xhttp2.onreadystatechange = function(){
if(xhttp2.readyState === 4 && xhttp2.status === 200){
var jsonArr = JSON.parse(xhttp2.responseText);
for(i in jsonArr){
table2 += "<tr><td>"+jsonArr[i].Name +
"</td><td> "+jsonArr[i].Roll_No+
"</td><td>"+jsonArr[i].Percentage+"</td><tr>"
}
document.getElementById("mytable").innerHTML = table2;
}
}
xhttp2.open('GET',url2,true);
xhttp2.send();
table,th,td{
border:1px solid black;
border-collapse: collapse;
}
<button onclick="loadDoc()" >Get Data</button>
<br>
<br>
<table id="mytable">
</table>
This should work:
function request() {
this.http = new XMLHttpRequest();
}
request.prototype.delete = function(url, callback) {
this.http.open("DELETE", url, true);
var self = this;
this.http.onload = function() {
if (self.http.status === 200) {
callback(null, "Record Deleted");
} else {
callback("Error: " + self.http.status);
}
};
this.http.send();
};
Another example (maybe clearer):
deleteRecord('https://jsonplaceholder.typicode.com/posts/1');
function deleteRecord(url) {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url);
xhr.send();
xhr.onload = function() {
if (xhr.status != 200) {
console.log('ERROR');
} else {
console.log('DELETED!');
}
};
xhr.onerror = function() {
console.log('NO CONNECTION');
};
}
You can use JS Fetch API to get this done,
const url = 'https://www.example.com/route';
const deleteFetch = async (url) => (
const response = await fetch(url, {
method: ‘DELETE’
});
const myJson = await response.json(); // converting to json
return myJson ;
}
Related
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!');
}
How to use promises (ES6) and .then method in order to this code will work?
getGif: function (searchingText, callback) {
var url = GIPHY_API_URL + '/v1/gifs/random?api_key=' + GIPHY_PUB_KEY + '&tag=' + searchingText;
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText).data;
var gif = {
url: data.fixed_width_downsampled_url,
sourceUrl: data.url
};
callback(gif);
}
};
xhr.send();
},
Using Promise-Based XHR your code looks like:
getGif = function (searchingText) {
return new Promise((resolve, reject)=>{
var url = GIPHY_API_URL + '/v1/gifs/random?api_key=' + GIPHY_PUB_KEY + '&tag=' + searchingText;
var xhr = new XMLHttpRequest();
// Setup our listener to process compeleted requests
xhr.onreadystatechange = function () {
// Only run if the request is complete
if (xhr.readyState !== 4) return;
// Process the response
if (xhr.status >= 200 && xhr.status < 300) {
// If successful
var data = JSON.parse(xhr.responseText).data;
var gif = {
url: data.fixed_width_downsampled_url,
sourceUrl: data.url
};
resolve(gif);
} else {
// If failed
reject({
status: request.status,
statusText: request.statusText
});
}
};
xhr.open('GET', url);
xhr.send();
});
}
Need to invoke method depends on signature of function.
getGif(searchText).then((response)=>{
console.log(response);
}, (error)=> {
console.log(error);
})
I have following code, which highlights (fadein/out) the replied comment (its a div element).
I show only 10 last comments on the page
If the comment is found, then I highlight it (working fine), otherwise I load all comments and then try to highlight necessary one. But after loadAllComments function in the else clause the hide() method is not working - I wonder why.
function showReply(reply){
var p = getElement(reply);
if (p) {
$("#" + reply).animate({
opacity: 0.5
}, 200, function () {
});
setTimeout(function () {
$("#" + reply).animate({
opacity: 1
}, 200, function () {
});
}, 1000);
}
else{
loadAllComments(); //load all elements. working fine
$("#"+reply).hide(); //nothing happens. :-(
}
function loadAllComments() {
deleteComments();
$('.show-more-button').hide();
var xhr = new XMLHttpRequest();
xhr.open('GET', api_url + 'video_comments/?video=' + video_id, true);
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert(xhr.responseText);
}
else {
var comments = JSON.parse(xhr.responseText);
for (var i = comments.results.length - 1 ; i >= 0 ; i--){
$('.comment-content-box').append(showComment(comments.results[i]));
}
}
}
};
xhr.send();
}
function deleteComments(){
var comments_count = $('.comment-content-box').children('div').length;
for (var i=0; i < comments_count; i++){
$('.comment-render-box').remove();
}
}
function showComment(comment) {
return "<div>" // example, there is plenty of code, but it's just a return function
}
You're performing an XHR which is asynchronous. Supply a callback function to loadAllComments to be executed after your XHR completes:
function loadAllComments(callback) {
deleteComments();
$('.show-more-button').hide();
var xhr = new XMLHttpRequest();
xhr.open('GET', api_url + 'video_comments/?video=' + video_id, true);
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert(xhr.responseText);
}
else {
var comments = JSON.parse(xhr.responseText);
for (var i = comments.results.length - 1 ; i >= 0 ; i--){
$('.comment-content-box').append(showComment(comments.results[i]));
}
// xhr is complete and comments are now in DOM
callback();
}
}
};
xhr.send();
}
...
// usage
loadAllComments(function() {
$('#' + reply).hide();
});
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
}
I'm curious as to why this isn't working, here's the code:
function Ajax(sUrl, fCallback) {
var url = sUrl || '';
var callback = fCallback || function () {};
var xmlhttp = (function () {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (err) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
} else {
return null;
}
}());
this.setUrl = function (newUrl) {
url = newUrl;
};
this.setCallback = function (func) {
callback = func;
};
this.request = function (method, data) {
if (xmlhttp === null) { return false; }
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
callback(xmlhttp.status, xmlhttp.responseXML, xmlhttp.responseText);
}
};
data = data || '';
data = encodeURIComponent(data);
if ((/post/i).test(method)) {
xmlhttp.open('POST', url);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
} else {
var uri = data === '' ? url : url + '?' + data;
xmlhttp.open('GET', uri);
xmlhttp.send();
}
return true;
};
return this;
}
var ajax = new Ajax(''); // sets the url, not necessary for this demonstration
var changed = false;
function change() {
changed = true;
}
function foo() {
ajax.setCallback(change);
ajax.request();
alert(changed);
}
foo();
There is a fiddle here: http://jsfiddle.net/dTqKG/
I feel like the change function would create a closure that would indeed change the changed variable. Does anyone know what's going on?
The ajax.request(); will return before change() is called. That is the async nature of the AJAX calls, and the reason why you need the callback as opposed to just getting return value from send() method.
Other than that there might be some other issues in the code. I question why wouldn't you use one of the many AJAX frameworks readily available instead of writing your own.