XMLHttpRequest to jQuery Ajax - javascript

I have this code and I want it using jQuery Ajax.
var input = document.getElementsByTagName("input")[0], file, target, i, len;
input.addEventListener("change", function(e) {
target = e.target.files;
for (i = 0, len = target.length; i < len; i += 1) {
file = target[i];
}
var fd = new FormData();
fd.append('image', file);
console.log(fd);
var xhttp = new XMLHttpRequest();
xhttp.open('POST', "https://api.imgur.com/3/image", true);
xhttp.setRequestHeader('Authorization', 'Client-ID xxxxxxxxxxxxxxx');
xhttp.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 300) {
var response = '';
try {
response = JSON.parse(this.responseText);
} catch (err) {
response = this.responseText;
}
console.log(response);
} else {
throw new Error(this.status + " - " + this.statusText);
}
}
};
xhttp.send(fd);
xhttp = null;
});
I already tried it make myself but it did not work.
Code I have tried:
$.ajax({
url: "https://api.imgur.com/3/image",
method: "POST",
headers: {
'Authorization':'Client-ID xxxxxxxxxxxxxxx'
},
data: fd,
success: function(response) {
console.log(response);
}
});
But logs error:
Uncaught TypeError: Illegal invocation
It worked if I delete data: fd, but data is required.

$.ajax({
url: 'https://api.imgur.com/3/image',
method: 'POST',
data: fd,
processData: false,
headers: { 'Authorization': 'Client-ID xxxxxxxxxxxxxxx' },
success: function(data){
//do your parsing here
}
});

Related

ASP.NET Core 2.2 AntiForgeryToken with JSON.Stringify

I have this controller on my server that has a ValidateAntiForgeryToken attribute
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetHistory([FromBody] ChatMessageGetHistoryViewModel Input)
{
var userName = HttpContext.User.Claims.Where(c => c.Type == "UserName").Select(c => c.Value).SingleOrDefault();
var history = chatMessageData.GetAllBySessionId(Input.SessionId, userName);
var output = JsonConvert.SerializeObject(history);
return Ok(output);
}
I have tried this method but so far I keep getting the error code 400. I have tried including the antiforgery token as part of the form data but that also doesn't work.
<script>
$(document).ready(function () {
var token = $('input[name="__RequestVerificationToken"]', $('#__AjaxAntiForgeryForm')).val();
var SessionId = document.getElementById("Id").value;
var form_data = {
"SessionId": SessionId,
__RequestVerificationToken: token,
};
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
if (output[i].Mine == true) {
p.setAttribute("class", "Sender Me");
q.setAttribute("class", "Message");
} else {
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
}
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
return false;
});
</script>
You have to pass the RequestVerificationToken as header with ajax request as follows:
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
headers: { 'RequestVerificationToken': token }, // here have to set the token
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
if (output[i].Mine == true) {
p.setAttribute("class", "Sender Me");
q.setAttribute("class", "Message");
} else {
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
}
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
For AJAX requests, you need to set the token in the request headers: the RequestVerificationToken request header, specifically, by default.
$.ajax({
...
headers: {
'RequestVerificationToken': token
}
});

AJAX not uploading images to backend service

Working on a requirement to upload images to AWS instance. UI and service is separated and connects via REST. Service is in nodejs. from UI we are making a ajax call to backend service to upload the images to AWS.
The problem:
When I upload the images via POSTMAN request, I can see that response as uploaded with files properly uploaded in AWS.
Whereas when I upload images via AJAX call, I get no response in browser, and also the images are not uploaded in aws.
Below is the piece of code in ajax:
var formData = new FormData();
formData.append('image', $('#tx_file_programa')[0]);
$.ajax({
method: 'POST',
type: "POST",
url: 'http://10.0.0.95:9999/photo/1',
contentType: false,
processData: false,
async: false,
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token );
},
data: formData,
success: function (data) {
console.log('response from server is : ', data);
}
//dataType: 'json'
});
This is the backend service.
server.post('/photo/:count', function (req, res) {
if (req.getContentType() == 'multipart/form-data') {
var form = new formidable.IncomingForm(),
files = [], fields = [];
var result = [];
var noOfFiles = req.params.count;
var count = 0;
console.log('noOfFiles', noOfFiles);
form.on('field', function(field, value) {
fields.push([field, value]);
console.log(fields);
})
form.on('progress', function(bytesReceived, bytesExpected) {
console.log('err');
});
form.on('error', function(err) {
console.log('err',err);
});
form.on('aborted', function() {
console.log('aborted', arguments);
});
new Promise(function(resolve, reject) {
var result = [];
form.onPart = function (part) {
var data = null;
const params = {
Bucket: 'xxxxx',
Key: uuidv4() + part.filename,
ACL: 'public-read'
};
var upload = s3Stream.upload(params);
upload.on('error', function (error) {
console.log('errr', error);
});
upload.on('part', function (details) {
console.log('part', details);
});
upload.on('uploaded', function (details) {
let extension = details.Location.split('.');
if(['JPG', 'PNG'].indexOf(extension[extension.length - 1].toUpperCase()) > -1) {
var ext = extension[extension.length - 1];
count++;
result.push(details.Location);
if(count == noOfFiles) {
resolve(result);
}
}
});
part.pipe(upload);
}
}).then(function(result){
console.log('end', result);
res.writeHead(200, {'content-type': 'text/plain'});
res.end('received files:\n\n ' + util.inspect(result));
})
form.parse(req, function (err, fields, files) {
})
return;
} else {
BadRequestResponse(res, "Invalid request type!");
}
})
#user3336194, Can you check with this, this is working thins
var appIconFormData = null
$(":file").change(function () {
var file = this.files[0], name = file.name, size = file.size, type = file.type;
var imageType = new Array("image/png", "image/jpeg", "image/gif", "image/bmp");
if (jQuery.inArray(type, imageType) == -1) {
return false;
} else {
appIconFormData = new FormData();
appIconFormData.append('appimage', $('input[type=file]')[0].files[0]);
}
});
$.ajax({
url: 'your/api/destination/url',
type: 'POST',
data: appIconFormData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data)
},
error: function (e) {
}
});
I think the way you are sending formdata is not correct.
Try these 2 ways:
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);

saving encrypted object as file - cryptojs

I am using cryptojs to encrypt and decrypt a file. I also have a web service to upload the encrypted files to a server. I can upload and save the ecnrypted object as a file on the server, but when I decrypt it, the file does not open correctly. My concern is if I am saving the ecnrypted object correctly or not.
Tutorial that I followed initially: http://tutorialzine.com/2013/11/javascript-file-encrypter/
encryt method:
function encrypt() {
var folderPath = "C:\\User\\test\\javascript-file-encrypter\\";
selectedFiles = document.getElementById("MainContent_file1");
var sfile = selectedFiles.files[0];
var read = new FileReader();
read.onload = function (e) {
var encrypted = CryptoJS.AES.encrypt(read.result, '123456');
var ct2 = encrypted.toString();
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
},
data: { 'folderPath': folderPath, 'uploadData': ct2, 'fileName': sfile.name + '.encrypted' },
success: function (response) {
console.log(response);
debugger;
},
error: function (xhr, textStatus, error) {
debugger;
console.log(xhr.statusText);
}
});
}
read.readAsDataURL(sfile);
}
decrypt method:
function decrypt() {
var sfiles = document.getElementById("MainContent_file1");
var sfile = sfiles.files[0];
var freader = new FileReader();
freader.onload = function (e) {
var decrypted = CryptoJS.AES.decrypt(freader.result, '123456');
var dct = decrypted.toString(CryptoJS.enc.Latin1);
//var dct2 = decrypted.toString();
//console.log(dct);
//console.log(dct2);
debugger;
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
},
data: { 'folderPath': folderPath, 'uploadData': dct, 'fileName': sfile.name.replace('.encrypted', '') },
success: function (response) {
console.log(response);
debugger;
},
error: function (xhr, textStatus, error) {
debugger;
console.log(xhr.statusText);
}
});
};
freader.readAsText(sfile);
}
webservice method:
[WebMethod]
public bool FileUpload(string folderPath, string uploadData, string fileName)
{
bool returnValue = false;
try
{
File.WriteAllText(folderPath + fileName, uploadData);
returnValue = true;
}
catch (Exception ex)
{
returnValue = false;
}
return returnValue;
}

Cannot append data to Js FormData

First of all sorry for my English I am trying to send an ajax request. I am using FormData. But when I append data then console.log that format it says no properties. FormData constructor accepts form as a parameter if i am not wrong. Here I used that argument, but also when i use formdata.append(key, value) this is not working also
Here is my code (No Jquery used $.ajax is my self written library).
onValidated: function(form){
var formData = new FormData(form);
console.log(formData);
$.ajax({
url: '/comment/send',
type: 'POST',
contentType: 'application/json',
dataContent: formData,
start: function()
{
$preloader.show();
},
success: function(response)
{
$preloader.hide();
},
error: function(response)
{
return false;
}
});
}
And here is my $.ajax function
window.$.ajax = function(settings)
{
var request;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
request.open(settings.type, settings.url, true);
request.setRequestHeader('Content-Type', settings.contentType);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
settings.success(JSON.parse(request.responseText));
}
};
request.onerror = function() {
settings.error();
}
console.log(settings.dataContent);
// Used for preloader or something else
settings.start();
if (settings.type == 'POST')
{
request.send(settings.dataContent);
}
else if(settings.type == 'GET')
{
request.send();
}
else
{
return false;
}
}

nodejs xhr POST

I am using nodejs and trying to make a POST command to a server. I am also using node-xmlHttpRequest (driverdan's module). I am having issues with the content-type and get the error:
{
"response":{
"errorCode":"UNKNOWN_ERROR","message":"Content type
'text/plain;charset=UTF-8' not supported","detail":"Content type
'text/plain;charset=UTF-8' not supported"
},"version":"1.0"
}
I need the content-type to be JSON, not text. I have tested the code with GET and it works fine.
Here is my code:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
var sys = require('util');
var json_text2 = { "username": "admin","password": "-----" };
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
//- var xmlHTTP = new XMLHttpRequest();
xhr.onreadystatechange = function() {
sys.puts("State: " + this.readyState);
if (this.readyState === 4) {
sys.puts("Complete.\nBody length: " + this.responseText.length);
sys.puts("Body:\n" + this.responseText);
}
};
xhr.open("POST",apic_url,true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Accept","application/json");
xhr.responseType = 'JSON';
xhr.send(JSON.stringify(json_text2));
app.locals.apic_nd = xhr.responseText;
Any ideas?
Thanks to jfriend00 I got it working (not sure how to upvote his comment. But here is the code I used:
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
var request = require('request');
var options = {
url: 'https://'+apicem_ip+'/api/v1/ticket',
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: '{ "username": "admin", "password": "----"}'
};
function callback(error, response, body) {
console.log("callback function");
if (!error) {
var info = (JSON.parse(body));
console.log(info);
console.log("status 200");
}
else {
console.log(JSON.parse(body));
}
}
request.post(options, callback);

Categories

Resources