How to get value from textfield to variables - javascript

Im using Mvc in C#.net and extjs. My question is
how to get value from textfield then set it to a variable and send email to multiple recipient.
This is my code for sending an email, and i want to get the values from the Extjs textfield id and set the id to a variable in sending. Then i want to send email to multiple recipient.
{
xtype: 'toolbar',
flex: 1,
dock: 'bottom',
ui: 'footer',
layout: {
pack: 'end',
type: 'hbox'
},
items: [{
xtype: 'button',
text: 'Send Email',
itemId: 'sen',
//iconCls: 'cancel'
handler: function() {
var rec = Ext.getCmp("activityGrid").getSelectionModel().selected()[0]
Ext.Ajax.request({
url: '/tblt_UAT_hr/generatePreview',
method: 'POST',
params: {
// id: Ext.get("Uath_Id").getValue(),
desc: rec.get("pc_desc"),
uat_date: rec.get("UAT_date"),
pcno: rec.get("pc_no"),
name: rec.get("name"),
stkid: rec.get("Stkhid")
},
success: function(resp) {
var result = Ext.decode(resp.responseText);
if (result.success) {
Ext.Ajax.request({
url: '/tblt_UAT_hr/SendEmailsTo',
method: 'POST',
params: {
from: null,
to: Ext.getCmp('to').getValue(),
subject: Ext.getCmp('subject').getValue(),
body: Ext.getCmp('bod').getValue(),
file: result.file
},
success: function(resp) {},
failure: function() {}
});
} else
mask.hide();
},
failure: function() {
mask.hide();
}
});
}
}, {
xtype: 'button',
text: 'Cancel',
itemId: 'can',
//iconCls: 'save'
}]
}]
public JsonResult SendEmailsTo(string from, string to, string subject, string body, string file) {
if (file != "" && file != null) {
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
smtpServer.Credentials = new System.Net.NetworkCredential("ga.ojt.sunga#gmail.com", "1993doris");
smtpServer.Port = 587; // Gmail works on this port
string newfile = Server.MapPath("~/Content/pdf") + "\\" + file;
Attachment attachment = new Attachment(newfile);
mail.From = new MailAddress("ga.ojt.sunga#gmail.com");
//mail.To.Add(emailAdd);
foreach(var address in to.Split(new [] {
";"
}, StringSplitOptions.RemoveEmptyEntries)) {
mail.To.Add(address);
}
mail.Subject = subject;
mail.Body = body;
mail.Attachments.Add(attachment);
smtpServer.EnableSsl = true;
smtpServer.Send(e);
// return Content("email sent", "text/plain");
}
return Json(new {
success = true, msg = "success"
}, JsonRequestBehavior.AllowGet);
}

Find the text field, with ComponentQuery or otherwise, call getValue on it and add it to params of a request call. Pseudo code:
var field = Ext.ComponentQuery.query('#fieldItemId')[0];
params:{
yourField:field.getValue();
}

Related

Ext js 7 modern, form.submit vs ajax.request

I have a Ext.form.Panel with multiple textareafield and fileinput like this
// https://requestbin.com/r/en0ej96odon2sm/1n6r1tb49KK6eObGMPHlYa1hh4C
Ext.create({
xtype: 'formpanel',
renderTo: document.body,
buttons: {
submit: 'onSubmit',
},
controller: {
onSubmit: function () {
var form = this.getView();
form.submit({
method: 'POST',
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
},
onSubmitTest: function () {
var form = this.getView();
Ext.Ajax.request({
url: 'https://en0ej96odon2sm.x.pipedream.net/test2',
method: 'POST',
params: {
data: form.getValues(),
},
success: function () {}
});
},
},
items: [{
xtype: 'textareafield',
name: 'testfield',
label: 'testfield',
value: 'test\nasd',
}, {
xtype: 'filefield',
label: 'Upload Test',
name: 'basedata-test',
}, {
xtype: 'button',
text: 'Ajax.request(), linebreaks but no files',
handler: 'onSubmitTest',
}]
});
Post Results:
https://requestbin.com/r/en0ej96odon2sm/1n6mtu8QtyreaisCAmV3csO724Q
Fiddle:
https://fiddle.sencha.com/#view/editor&fiddle/3b9j
So, cause i need fileinput/multipart, I have to use form.submit({}).
But when I do so, I don't get the linebreaks on Server side in my $_POST Var.
When I do a ajax.request({}) everything looks good, but $_FILES are missing, so this is not really an option. (but this is documented).
I also tried adding jsonSubmit to the form (then I get no $_POST at all).
When I add enableSubmissionForm: false I get the newline, but after submit the form disappears (and I don't know why).
Is there a solution for this or am I doing something wrong?
You can use the following override. Hope it will not make the framework unstable ;)
// https://requestbin.com/r/en0ej96odon2sm/1n6r1tb49KK6eObGMPHlYa1hh4C
// Override
Ext.define('overrides.form.Panel', {
override: 'Ext.form.Panel',
privates: {
createSubmissionForm: function (form, values) {
var fields = this.getFields(),
name, input, field, fileTrigger, inputDom;
if (form.nodeType === 1) {
form = form.cloneNode(false);
for (name in values) {
input = document.createElement('textarea');
input.setAttribute('type', 'string');
input.setAttribute('name', name);
input.innerHTML = values[name];
form.appendChild(input);
}
}
for (name in fields) {
if (fields.hasOwnProperty(name)) {
field = fields[name];
if (field.isFile) {
// The <input type="file"> of a FileField is its "file" trigger button.
fileTrigger = field.getTriggers().file;
inputDom = fileTrigger && fileTrigger.getComponent().buttonElement.dom;
if (inputDom) {
if (!form.$fileswap) {
form.$fileswap = [];
}
input = inputDom.cloneNode(true);
inputDom.parentNode.insertBefore(input, inputDom.nextSibling);
form.appendChild(inputDom);
form.$fileswap.push({
original: inputDom,
placeholder: input
});
}
} else if (field.isPassword) {
if (field.getInputType() !== 'password') {
field.setRevealed(false);
}
}
}
}
return form;
}
}
});
Ext.create({
xtype: 'formpanel',
renderTo: document.body,
buttons: {
submit: 'onSubmit',
},
controller: {
onSubmit: function () {
var form = this.getView();
form.submit({
method: 'POST',
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
},
onSubmitTest: function () {
var form = this.getView();
Ext.Ajax.request({
url: 'https://en0ej96odon2sm.x.pipedream.net/test2',
method: 'POST',
params: {
data: form.getValues(),
},
success: function () {}
});
},
},
items: [{
xtype: 'textareafield',
name: 'testfield',
label: 'testfield',
value: 'test\nasd',
}, {
xtype: 'filefield',
label: 'Upload Test',
name: 'basedata-test',
}, {
xtype: 'button',
text: 'Ajax.request(), linebreaks but no files',
handler: 'onSubmitTest',
}]
});
Not ideal, but you also can do this:
form.submit({
method: 'POST',
//just like the ajax
params: {
data: form.getValues(),
},
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
Here is a simple workaround for using Ajax.request instead of form.submit
I needed that because I have to set an Authorization header, which can't be done with IFRAME used by the framework
So preventing Ext.data.request.Ajax from setting Content-Type header seems to do the job.
multipart/form-data will be automatically set.
Warning : neither options.headers nor defaultHeaders should already have the 'Content-Type' header
Ext.define('Override.data.request.Ajax', {
override: 'Ext.data.request.Ajax',
setupHeaders: function(xhr, options, data, params) {
if (data instanceof FormData) {
if (Ext.apply({}, options.headers || {}, this.defaultHeaders).hasOwnProperty('Content-Type')) {
console.warn('The Content-Type header must not be set before request if you need to use FormData with this override');
}
/* prevent Ext.data.request.Ajax from setting Content-Type header */
return this.callParent([xhr, options, null, null]);
} else {
return this.callParent(arguments);
}
}
});
And call Ajax.request with a FormData as rawData
var formData = new FormData();
var files = myView.down('filefield').getFiles();
if (files.length > 0) {
formData.append('file', files[0], files[0].name);
}
Ext.Ajax.request({
url: 'your_url',
rawData: formData,
success: function(response) {
// handle success
},
failure: function(response) {
// handle failure
}
});

Sencha ExtJs button - password Recovery email not working

This displays a confirmation message, but when I hit yes, it gives this error:
HTTP Status 415 -
description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
{
xtype: 'button',
id: 'passwordRecoveryButton',
text: 'Reset Password',
style: 'border-color: red',
listeners: {
click: function(button, event){
var form = Ext.getCmp('gmiUserDetailsPanel').getForm();
var currentRecord = form.getRecord();
var emailId = currentRecord.get('emailId');
Ext.Msg.show({
title:'Password Recovery',
msg: 'Are you sure you want to send a password recovery email to ' + emailId +'?',
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION,
fn: function(btn) {
if (btn === 'yes') {
Ext.Ajax.request({
url: 'admin/passwordRecovery.htm',
jsonData : emailId,
method: 'POST',
success: function(response){
Ext.Msg.show({
msg: 'Email successfully sent to ' + emailId +'.',
})
},
failure: function(response){
Ext.Msg.show({
modal : true,
title : 'Unable to send email!',
msg : 'Unable to send email to : '+emailId+', please contact support team.',
icon : Ext.Msg.ERROR,
buttons: Ext.Msg.OK
});
}
});
}
}
});
}
}
},
},
I am attempting to pass the information of the current record (or just the email) and this is in the java controller:
#RequestMapping(value = "/passwordRecovery", method = RequestMethod.POST)
#Secured("ADMIN")
public
#ResponseBody
UserOperationResponse PasswordRecoveryEmail(Model model, HttpServletRequest request, #RequestBody UserOperationRequest userOperationRequest) throws UnsupportedEncodingException, MessagingException {
UserOperationResponse userOperationResponse = new UserOperationResponse();
[...]

Error Loading the following Javascript

Could someone please tell me what's wrong with the following code. I'm guessing it has something to do with missing brackets for the Javascript, but I can't put my finger on it. We're using Full Calendar + Mandrill
Thanks a lot!
$(window).load(function() {
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
jQuery(function($) {
$("#contact_form").submit(function() {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello "+name+ ", You have signed "+modal+ " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});
});
});
});
}); //]]>
First your code should have proper indentation,
You have some errors in the closing of braces and like so for eg: you have an extra closing brace in ajax call and few others, which I have corrected and pasted.
$(window).load(function() {
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
)}
jQuery(function($) {
$("#contact_form").submit(function() {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello "+name+ ", You have signed "+modal+ " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});
});
});
Please check now.
This is what you expect ?
$(window).load(function () {
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function (event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
});
});
});
jQuery(function ($) {
$("#contact_form").submit(function () {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello " + name + ", You have signed " + modal + " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
})
.done(function (response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function (response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});

ExtJS REST client can't get JSON data from the RESTful Services [duplicate]

I implement simple RESTful Service. These are Rest request url and the response json data.
http://localhost:8080/RESTfulTestWeb/rest/services/getJson/aupres
{"id":"aupres","passwd":"aaa","age":45,"name":"joseph"}
The problem is ExtJS Store object client can not handle the above json data. These are ExtJS client codes
Ext.define('extjs.model.Member', {
extend: 'Ext.data.Model',
fields : [{
name : 'id',
type : 'string'
}, {
name : 'passwd',
type : 'string'
}, {
name : 'age',
type : 'int'
}, {
name : 'name',
type : 'string'
}]
});
Ext.onReady(function () {
var members = Ext.create('Ext.data.Store', {
model : 'extjs.model.Member',
//autoLoad : true,
proxy: {
type: 'rest',
url : 'http://localhost:8080/RESTfulTestWeb/rest/services/getJson/aupres',
reader: {
type: 'json',
root: 'id',
},
writer: {
type: 'json'
},
listeners: {
exception: function(proxy, response, operation){
Ext.MessageBox.show({
title: 'REMOTE EXCEPTION',
msg: operation.getError(),
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
})
}
}
},
listeners: {
load: function(members, operation, success) {
if(success) {
alert('response : ' + members.model.length)
} else {
alert('it failed')
}
}
}
})
var onButtonClick = function() {
members.load()
}
The respose is shown like below
"response : 0"
It seems my ExtJS codes fail to contain the json data.
The rest proxy reader in ExtJs 5 and up looks for a rootProperty: instead of root:.
HI You can overwrite toString() method of your class . then you can get exact.
Like you want data on ["id":"aupres","passwd":"aaa","age":45,"name":"joseph"}]
or some other format

MVC JsonResult not working with chrome?

i want jquery to take a JsonResult from my MVC controller but it does'nt receive any data!
If I put the output into a textfile and enter its link its working so I think my jQuery is fine.
Then I was testing with other browsers like chrome and I saw NOTHING. The requested page was just emtpy.. no errors. Also IE seems to have problems receiving my string.. only firefox displays the string but why?
public JsonResult jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
}
r.Close();
return Json(requests);
}
I found out that also if I want to return the JSON as string its not working!
Its working with a string in all browsers now.. but jQuery is still not loading anything
var url = "http://../jsonLastRequests";
var source =
{
datatype: "json",
datafields: [
{ name: 'ID' },
{ name: 'SiteID' },
{ name: 'Lat' },
{ name: 'CreationTime' },
{ name: 'City' },
],
id: 'id',
url: url
};
var dataAdapter = new $.jqx.dataAdapter(source, {
downloadComplete: function (data, status, xhr) { },
loadComplete: function (data) { },
loadError: function (xhr, status, error) { }
});
I fixed my problem by adding:
access-control-allow-origin:*
public HtmlString jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
} r.Close();
System.Web.Script.Serialization.JavaScriptSerializer jSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return new HtmlString(jSerializer.Serialize(requests ));}
I have done same approch like this
$.ajax({
type: 'POST',
url: '/home/GetSurvey',
data: {
XmlPath: $("#xmlpath").val()
},
dataType: 'json',
success: function (jsonData) {
jsonStringQuestionaire = jsonData;
LoadSurvey();
},
error: function () {
alert('Error loading ' + id);
}
});
questionaireJsonList = eval(jsonStringQuestionaire);

Categories

Resources