jQuery .ajax to Vanilla JavaScript - javascript

I am trying to convert an ajax request to vanilla JavaScript
$.ajax({
url: 'http://foo.bar/hi',
type: 'post',
data: {args: params},
success: function(data){
},
});
I have tried the following
var xhr = new XMLHttpRequest();
var data = {args: params};
xhr.open("POST", 'http://foo.bar/hi', true);
xhr.send(data);
I am connecting to an external device with a web based interface and not getting any response on the device. It is as if I never sent a request
Theoretically, the original ajax request will perform the action, however, there is a problem with the jQuery portion of my program so I am trying to convert it to vanilla javascript and bypass the jQuery

Using fetch:
function json(response) {
return response.json();
}
function handleErrors(response) {
if(!response.ok) {
throw new Error("Request failed " + response.statusText);
}
return response;
}
fetch("http://url.com/endpoint", {
method: "POST",
body: {
myKey: "my value",
another: "hihihi"
}
}).then(handleErrors).then(json).then(function(data) {
console.log(JSON.stringify(data));
}).catch(function(err){
console.log("err" + err);
})

Related

Converting XHR request to axios to request data from GraphQL server

I am requesting data from GraphQLHub via XHR:
const query = '{ reddit { subreddit(name: "movies"){ newListings(limit: 2) { title comments { body author { username commentKarma } } } } } }';
const xhr = new XMLHttpRequest();
xhr.open("get", 'https://www.graphqlhub.com/graphql?query=' + encodeURIComponent(query), true);
xhr.responseType = "json";
xhr.onload = () => console.log(xhr.response);
xhr.send();
This works. However I tried converting it into axios like so:
const query = '{ reddit { subreddit(name: "movies"){ newListings(limit: 2) { title comments { body author { username commentKarma } } } } } }';
axios({
url: "https://www.graphqlhub.com/graphql",
method: "get",
data: {
query: encodeURIComponent(query)
}
}).then((result) => {
console.log(result.data);
});
But I am getting this error:
Uncaught (in promise) Error: Request failed with status code 400
Anything wrong with the syntax?
According to the docs:
data is the data to be sent as the request body. Only applicable for request methods 'PUT', 'POST', and 'PATCH'.
Since your method for the request is GET, the data is ignored. You should use params instead. We also don't need to encode our params, since axios already does this for us.
axios({
url: "https://www.graphqlhub.com/graphql",
method: "get",
params: {
query,
}
})
It's probably better to just use POST instead though, since some servers don't allow mutations to be sent as GET requests.
axios({
url: "https://www.graphqlhub.com/graphql",
method: "get",
data: {
query,
}
})
Or, better yet, just use a client like Apollo.

How to return database data in HTTP get method

In server side,I fetch data from database
var sql = require('mssql');
app.get('/api/comments', function(request, response) {
var sqlConfig = {
// Connection string parameters.
}
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = 'select TOP 10 * from comment';
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
sql.close();
response.json(recordset);
});
});
});
Then,I fetch the data from server side by AJAX (get method)
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
success: (comments) => {
this.setState({ comments })
}
});
I get an error when I get the data by Ajax.
(Uncaught TypeError: this.state.comments.map is not a function)
It seems that the data return is undefined.Instead of fetching database,the code is work if I use static data(hard code) in server side.
I think the problem is the callback function in sql.connect() but I have no idea how to solve it.Does anyone can help?
Error:
The solution is adding dataType: 'json' to the ajax
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
dataType: 'json',
success: (comments) => {
this.setState({ comments })
}
});
}

Method being called before Promise is complete

I am attemting to add an item to a sharepoint list from an Apache Cordova application. It first prompts the user to login then it will make a HTTP Post to so the data entry.
I have the following code:
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(FormatAndUpload(authResult, data), errorCallback);
}
function FormatAndUpload(authResponse, data) {
var token = authResponse.accessToken;
var expiry = authResponse.expiresOn;
console.log("Token acquired: " + authResponse.accessToken);
console.log("Token will expire on: " + authResponse.expiresOn);
$.ajax({
url: "https://my.sharepoint.com/_api/web/lists/getbytitle('" + Test + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"Authoriztion":"Bearer " + token
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
The problem I am having is that the FormatAndUpload method is being called before acquireTokenAsync has completed, so the authResponse variable passed into the FormatAndUpload method is null.
I'm not too familiar with the promise framework in Javascript/JQuery but I was under the impression that the event should only fire on completion of the previous method.
Does anyone have any pointers in how I can correctly wait for the login to complete before attempting the POST?
what you did FormatAndUpload(authResult, data); is wrong the correct way to pass a callback is
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
so your saveToSharepoint will be like this
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
}
Thanks for the answer Newbee Dev, you were correct in that I didn't formulate the then method correctly.
For any others who see this regarding SharePoint, I actually reformatted the code for it to work as expected, so the saveToSharepoint method looks like so:
function saveToSharepoint(data) {
var AuthenticationContext = Microsoft.ADAL.AuthenticationContext;
AuthenticationContext.createAsync("https://login.microsoftonline.com/common/")
.then(function (authContext) {
authContext.acquireTokenAsync(
"https://my.sharepoint.com", // Resource URI
"4be098f8-2184-4831-9ef7-3d17dbbef6a0", // Client ID
"http://localhost:4400/services/office365/redirectTarget.html" // Redirect URI
).then(function (authResult) {
FormatAndUpload(authResult, data);
}, function (err) {
console.log(err);
});
}, function (err) {
console.log(err);
});
}
The main thing to note is creating the AuthenticationContext asynchronously and this way, the FormatAndUpload calls after the whole login process is complete. Just thought I would post this for other people who see this regarding Sharepoint and are stuck.

AJAX requests to Node.JS to update JSON file for Jquery-comments

Jeez... How about that title, terrible lol.
Well I am using jquery-comments by Viima. (http://viima.github.io/jquery-comments/)
I'm trying to use ajax commands to a Node.JS script that will update a JSON file. All of which is local, no crossing domains or anything.
Here is my Node.JS script:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.writeFile("/comments-data.json", "commentJSON", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');
Here is the Ajax post
postComment: function(commentJSON, success, error) {
$.ajax({
type: 'post',
url: 'http://127.0.0.1:8080',
data: commentJSON,
success: function(comment) {
success(comment)
},
error: error
});
},
I don't want to redirect. I just wanted to asynchronously show the new comment. Also this script will ultimately have to be able to handle video attachments as well and store the filepath inside the JSON file. But i believe, Jquery-comments just reads the file path from the JSON
Here is what the support site says for attachments
uploadAttachments: function(commentArray, success, error) {
var responses = 0;
var successfulUploads = [];
var serverResponded = function() {
responses++;
// Check if all requests have finished
if(responses == commentArray.length) {
// Case: all failed
if(successfulUploads.length == 0) {
error();
// Case: some succeeded
} else {
success(successfulUploads)
}
}
}
$(commentArray).each(function(index, commentJSON) {
// Create form data
var formData = new FormData();
$(Object.keys(commentJSON)).each(function(index, key) {
var value = commentJSON[key];
if(value) formData.append(key, value);
});
$.ajax({
url: '/api/comments/',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(commentJSON) {
successfulUploads.push(commentJSON);
serverResponded();
},
error: function(data) {
serverResponded();
},
});
});
}
});

Unable to parse headers from successful HTTP HEAD request in jquery?

I am using the following code to get file-size of a url, the debugger shows requests to be executed with HTTP STATUS CODE 200 returning all headers including 'Content-Length' however my code outputting NULL values for headers (even after the request succeeded).
function checkURL(url) {
try {
var xhr = $.ajax({
type: "HEAD",
url: url,
async: false,
success: function (data) {
result = data;
}
});
console.log('Size :' + xhr.getResponseHeader('Content-Length'));
} catch (e) {
console.log('XHR Error :' + e);
}
}
EDIT # 1
I tested the below code and it works, however not all headers are being displayed. Once again HTTP DEBUGGER shows the elusive 'Content-Length' header to be present in reply to this XHR.
function checkURL(url) {
try {
var xhr = $.ajax({
type : "HEAD",
url : url,
complete : function (XMLHttpRequest, textStatus) {
console.log(XMLHttpRequest.getAllResponseHeaders());
}
});
} catch (e) {
console.log('Check Size XHR Error :' + e);
}
}
Whats is your type HEAD ?
it must be a xml or json !

Categories