I am trying to post data to a form via XMLHttpRequest using the following code:
function submitForm(event) {
event.preventDefault();
var data = new FormData(form);
var request = new XMLHttpRequest();
request.onreadystatechange = function(e) {
var formattedEmails = Object.keys(request.responseText);
formattedEmails.forEach(function(email) {
messages.addMessage(email.to, email.subject, email.message);
});
};
request.open(form.method, form.action);
request.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
request.send(data);
}
When I do this, the data comes in like this
{ '------WebKitFormBoundarywGy70eJqwXdEVot5\r\nContent-Disposition: form-data; name':'"emails"\r\n\r\n Ben,Hernandez,b****#gmail.com\r\n Ann,M*****,a****#gmail.com\r\n \r\n------WebKitFormBoundarywGy70eJqwXdEVot5\r\nContent-Disposition: form-data; name="subject"\r\n\r\nhi {first}!\r\n------WebKitFormBoundarywGy70eJqwXdEVot5\r\nContent-Disposition: form-data; name="message"\r\n\r\nHello {first} {last} {email}\r\n------WebKitFormBoundarywGy70eJqwXdEVot5\r\nContent-Disposition: form-data; name="submit"\r\n\r\nPreview\r\n------WebKitFormBoundarywGy70eJqwXdEVot5--\r\n' }
Which appears to just be a ridiculously long string of data that I need to format somehow?. When I remove the above code and allow the form to just submit like regular to the form.action page. I get this back:
{ emails: 'Ben,Hernandez,b****#gmail.com\r\nAnn,M****,a***#gmail.com\r\n',
subject: 'hi {first}!',
message: 'Hello {first} {last} {email}',
submit: 'Preview' }
Which is definitely what I want. How do I extract that from the ridiculous string above or change my post request so I get something much more manageable.
Should note that backend is express on node.
Thanks!
I ended up abandoning doing the
var data = new FormData(form);
and just manually putting my params string together. If anyone knows how to do this, I am still interested in answers.
Related
I am facing an issue on sending email. Actually, I am trying to send an email with more text and many images in the body of the mail . I am using jquery and c# controller to make this work out.
The following code explains bit better:
In jquery, am using
$scope.SendEMailNew = function () {
var data = new FormData();
var ToEmail = $("#emailTo").val();
var CcEmail = $("#emailCc").val();
var Subject = $("#emailSubject").val();
var Message = document.getElementById(divID).outerHTML;
data.append("ToEmail", ToEmail);
data.append("CcEmail", CcEmail);
data.append("Subject", Subject);
data.append("Message", Message);
mailsendingIndicator();
$.ajax({
url: ApplicationUrl + 'SendEmail/MailSend',
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
hidemailsendingIndicator();
toastr.clear();
toastr.success("Mail sent successfully", opts);
},
error: function (er) {
hidemailsendingIndicator();
toastr.clear();
toastr.error("Something went wrong", opts);
}
});
In c# mvc controller, i am using
[AcceptVerbs(HttpVerbs.Post)]
public void MailSend(SendEmail MailDetails)
{
string result = string.Empty;
string from = "FromMail#gmail.com";
using (MailMessage mail = new MailMessage(from,MailDetails.ToEmail))
{
mail.Subject = MailDetails.Subject;
mail.Body = MailDetails.Message;
mail.IsBodyHtml = true;
if (!string.IsNullOrEmpty(MailDetails.CcEmail))
mail.CC.Add(MailDetails.CcEmail);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential("FromMail#gmail.com", "Password");
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
}
}
After this code, the email could be sent with embedded images to my official mail id and to my client's mail id but to gmail and to outlook mails, the embedded images not displaying.
Especially, in outlook mails, I am not getting the option to download the image itself. In gmail, i am getting the image as base 64 code. Actually, the image is stored as bytes in database and retrieved to jquery through ajax call. I am facing this issue for long time.
What will be the solution for this kind of issue? Any idea will be a great help
Thanks
I am trying to upload a file to the REST Api of Octoprint, which should be done by sending a POST request with Content-Type: multipart/form-data
(http://docs.octoprint.org/en/master/api/fileops.html#upload-file)
I am using NodeJS and two libraries, XmlHttpRequest and form-data. When trying:
var xhr = new xmlhttprequest() ;
var form = new formData() ;
form.append('exampleKey', 'exampleValue');
xhr.open("POST","octopi.local/api/local", true) ;
xhr.setRequestHeader("Content-Type","multipart/form-data") ;
xhr.send(form) ;
I get an error at the xhr.send line :
TypeError: first argument must be a string or Buffer
If I make a synchronous request by using xhr.open("POST",url,false), this error disappears.
Why is it so ? Is there a way to turn it into an asynchronous request ?
EDIT Actually, I don't really understand the documentation. I suppose that I should set the file I want to upload by using form.append("filename", filepath, "exampleName"), but I am not sure about that. The fact is that I noticed that I get the TypeError even if I try a simplified request, without sending any file.
EDIT2 This is the modified code, which returns the same error :
var XMLHttpRequest=require('xmlhttprequest').XMLHttpRequest ;
var FormData = require('form-data');
var data = new FormData();
data.append("key","value" );
var xhr = new XMLHttpRequest();
xhr.open('POST', "octopi.local/api/files/");
xhr.send(data);
After a long time working on this, I finally managed to upload a file. If you use NodeJS, don't rely on the MDN documentation: it tells what the libraries should do, not what they can actually do on the node platform. You should only focus on the docs available on GitHub.
It seems that it is not currently possible to send a form with XMLHttpRequest : I tried using JSON.stringify(form) but then wireshark tells me that the request is not a multipart/formdata request.
If you want to upload a file, you should rather use the 'request' module. The following has worked for me :
exports.unwrappeduploadToOctoprint = function(){
"use strict" ;
var form ={
file: {
value: fs.readFileSync(__dirname+'/test2.gcode'),
options: { filename: 'test2.gcode'}
}
};
var options = {
method: 'POST',
url: 'http://192.168.1.24/api/files/local',
headers: { 'x-api-key': 'E0A2518FB11B40F595FC0068192A1AB3'},
formData: form
};
var req = request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
};
Seems that you have some typos in your code. Use code snippet below instead. Replace the relevant parts according to your needs
var fileToUpload = document.getElementById('input').files[0];
var data = new FormData();
data.append("myfile", fileToUpload);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_endpoint");
xhr.send(data);
I have the followign JavaScript code:
function upload(blob) {
var xhr = new XMLHttpRequest();
var url = "test.cfm";
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("randomname",blob);
xhr.open("POST",url,true);
xhr.send(fd); }
How can I catch it on server side by ColdFusion and Save blob object to File?
Can someone please some code sample. Thx.
PS. I am pretty new in CF.
Since you are using formdata, you can access the form variable with ajax, just like you would with normal http requests.
#form.randomname#
#form['randomname']#
So you could save the content in a file with
<cfscript>
fileWrite( 'c:\myfile.txt', form.randomname );
</cfscript>
before starting let me say that I am new to dojo and this is my first project in dojo:
when I am trying to send json data from rest client (some chrome ext) it working for me,I mean to say that my spring mvc part is working, but when i am trying to send the same json from dojo code I am getting http 400 exception
my dojo code:
postCreate : function() {
this.inherited(arguments);
var form = dom.byId("contactSubmit");
on(form, "click", function(evt) {
var box0 = registry.byId("inputEmail");
var box1 = registry.byId("inputName");
var box3 = registry.byId("message");
alert("values are: " + box0.get("value"));
jsonData = {"email":"some#gmail.com","inputName":"some name","message":"some msg"};
request.post("/pool/conta", {
data: jsonData,
handleAs: "json",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
}
}).then(function(text){
alert("values are send"+text);
});
});
}
the jason data that I am sending from rest client is which is working:
{"email":"some#gmail.com","inputName":"some name","message":"some msg"}
my spring mvc method is below:
#RequestMapping(value="/conta", method = RequestMethod.POST)
public #ResponseBody Contact getShopInJSON(#RequestBody Contact contact2) {
Contact contact = new Contact();
contact.setEmail("pro#gmail.com");
contact.setInputName("pro");
contact.setMessage("msg");
System.out.println("***********************"+contact2.getEmail());
return contact;
}
pool is name of application
The json data as passed in post request requires string to be crypted with "\" so that the javascript can handle the double codes as is within string(double quoted string).
Thus, the line
jsonData = {"email":"some#gmail.com","inputName":"some name","message":"some msg"};
would work if written as below
jsonData = " {\"email\":\"some#gmail.com\",\"inputName\":\"some name\",\"message\":\"some msg\"} " ;
Its working now, I have used toJson from dojo/_base/json" utility before passing it to request.post
Our team has developed a JS HTML5 canvas based paint application. In the following code, the image data is fetched from the canvas as base 64 encoding and posted to a servlet via ajax. The data post behaves erratically. If the image is simple , as in a straight line, I get Ajax status = 200 and the image gets saved. If the image is complex, then I get a status = 400 and the data is not saved.
Why should the content of the POST create issues with posting of the data itself?
function getCode(){
var canvas = document.getElementById('imageView');
var context = canvas.getContext('2d');
// draw cloud
context.beginPath();
// save canvas image as data url
var dataURL = canvas.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
document.getElementById('canvasImg').src = dataURL;
var uri= document.getElementById('canvasImg').src;
uri = uri.replace('data:image/png;base64,','');
uri = uri.replace('=', '');
uri = uri.trim();
alert("uri is "+uri);
var ajaxobject ;
if(window.XMLHttpRequest){
ajaxobject = new XMLHttpRequest();
} else if(window.ActiveXObject){
ajaxobject = new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.ActiveXObject){
ajaxobject = new ActiveXObject("Msxml2.XMLHTTP");
}
ajaxobject.open("POST", "SaveImageServlet?image="+uri, true);
ajaxobject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxobject.onreadystatechange = function(){
if(ajaxobject.readyState==4){
alert(ajaxobject.status);
if(ajaxobject.status==200){
alert(ajaxobject.responseText);
}}
};
ajaxobject.send(null);
}
From looking at your code, the problem seems that you're passing the data in querystring instead of using the request body (as you should be doing since you're setting the POST verb).
Your uri should look like this:
SaveImageServlet
without the question mark and the parameter. The parameter should be set in the request body. Using jquery ajax your request would look like this:
$.ajax({
contentType: 'text/plain',
data: {
"image": yourBase64string
},
dataType: 'application/json', // or whatever return dataType you want
success: function(data){
// callback in case of success
},
error: function(){
// callback in case of error
},
type: 'POST',
url: '/SaveImageServlet'
});
On server side you should be reading the data from the appropriate place. For example, if you're using .Net read it like this:
Request.Form["image"]
instead of:
Request.Querystring["image"]
This should work as intended and consistently.
#Matteo, Thanks for your help and effort. However, AJAX issue never got solved. I found a way to send the base64 image data to the servlet. Just appended it to a hidden field and sent it as a regular form field.