send multiple parameter using ajax and save data into database - javascript

send multiple parameter using ajax and save data into database....and in the case of packet i want value will remain unchange on form mean i don't want that my form reload so, how it is possible i'm a newbie please give your valuable suggestions
onsubmitbtn call on submit button
function onsubmitbtn(){
var packet = document.getElementById("packet").value;
var name = document.getElementById("name").value;
var number = document.getElementById("number").value;
var sub = document.getElementById("sub").value;
var zipcode = document.getElementById("zcode").value;
var city = document.getElementById("city").value;
var weight = document.getElementById("weight").value;
var data = "packet=" +packet+ "&name="+name+ "&number="+number+ "&sub="+sub+ "&zipcode="+zipcode+ "&city="+city+ "&weight="+weight;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
var response = request.responseText;
}
request.open("get", "PickUpInvertFormSubmit.jsp?"+data, true);
request.send();
}
i want to send multiple parameters in my ajax and save the value in my database. if the packet is more than one in that case i want that on submit but the value in input field will remain same
jsp code for insert data into database
String name = request.getParameter("name");
String[] splt = client.replaceAll("\\s+", "").split("\\|");
String number = request.getParameter("number");
String sub = request.getParameter("sub");
String zip = request.getParameter("zipcode");
int z = Integer.valueOf(zip);
String city = request.getParameter("city");
String pkt = request.getParameter("packet");
int p = Integer.valueOf(pcs);
String weight = request.getParameter("weight");
double w = Double.valueOf(weight);
Dbcon dbc = new Dbcon();
Connection con = dbc.ConnDb();
String query = "insert query"
+ "VALUES (?,?,?,?,?,?,?,CURRENT_DATE,CURRENT_DATE,CURRENT_TIMESTAMP)";
PreparedStatement psmt = null;
try {
psmt = con.prepareStatement(query);
psmt.setString(1, ....);
psmt.setString(2, .......);
psmt.setString(3, ........);
psmt.setInt(4, .......);
psmt.setString(5, .......);
psmt.setInt(6, ..........);
psmt.setDouble(7, .......);
psmt.executeUpdate();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
dbc.disconnect(null, null, null, psmt);
}
}
this code works perfectly when i use this code on action
onsubmit button event my form field get refreshed and no data save in database...

use this
function onsubmitbtn() {
var packet = document.getElementById("packet").value;
var name = document.getElementById("name").value;
var number = document.getElementById("number").value;
var sub = document.getElementById("sub").value;
var zipcode = document.getElementById("zcode").value;
var city = document.getElementById("city").value;
var weight = document.getElementById("weight").value;
$.ajax({
type: 'POST',
cache: false,
url: "PickUpInvertFormSubmit.jsp",
data: {
"packet": packet,
"name": name,
"number": number,
"sub": sub,
"zipcode": zipcode,
"city": city,
"weight": weight
},
success: function (data, textStatus, jqXHR) {
successMethod(data);
},
error: function (jqXHR, textStatus, errorThrown) {
errorMethod(errorThrown);
}
});
}
Your data can't be altered after submission and also can't be bookmarked.
you can also use alert("success: " + data); in success value of ajax function and same in error of the ajax method.
Using this, data is not appended to browser's URL and you don't have to modify your controller/jsp.
This method will make a call to URL in background and you can perform cleanup in the success method.
also import jQuery in head tag of your document as
<head>
<script type="text/javascript" src="jquery-3.2.1.js"></script>
</head>
You can download jQuery from here Download jQuery | jQuery
Hope this helps :)

Related

Download a file through ajax request in asp.net MVC

I am trying to download file through ajax call in asp.net
my javascript:
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var data = query.filter(filters).data;
var strAccountCodes = '';
for (var i = 0; i < data.length; i++) {
strAccountCodes += data[i].AccountCode + ",";
}
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes }
});
my action method:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
return File(output, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
code is executing without any errors but it's not downloading any file.
is that anything i am missing?
You should know that AJAX call is not intended to download CSV file directly. Therefore, you can create a byte array from MemoryStream instance and store it inside Session or TempData variable, then return 'successful' state to enable redirect on AJAX success response:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
// creates byte array from stream
TempData["Output"] = output.ToArray();
// returns successful state
return Json("Success", JsonRequestBehavior.AllowGet);
}
Second, create a controller action with GET method and pass stored byte array from Session or TempData into FileResult:
public ActionResult DownloadCSV()
{
// retrieve byte array here
var array = TempData["Output"] as byte[];
if (array != null)
{
return File(array, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
else
{
return new EmptyResult();
}
}
Finally, handle success response to include location.href which will redirect to controller returning FileResult to download CSV file:
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadCSV", "ControllerName")';
}
}
});
As an option, you could pass CSV file name as parameter from AJAX response using query string.
Related issue:
Creating a byte array from a stream

Get all json key and value from an external json file in MVC with javascript

I am creating a web app in which I have a Json file in which I have many keys with values, like the following,
{
"Login_Header_Text": "Login",
"Login_Header_Recent_Updates": "Recent Updates",
"Login_TextBox_UserName": "User Name",
"Login_TextBox_Password": "Password",
"Login_Button_Login": "Log In",
"Login_ErrorMessage_Usernamerequired": "User name required",
"Login_ErrorMessage_Passwordrequired": "Password required.",
"Login_ErrorMessage_Invalid_Credentials": "Invalid user name/password",
}
and I can retrieve the values like the following
<script>
console.log('#HttpContext.GetGlobalResourceObject("", "Login_TextBox_UserName")');
</script>
now, how can I retrieve whole json file data and print that into my console,
Like, if I have 55 Records in the json file, whole data should be printed in console.log
what is the proper way to do this?
here is how i would do it. in C# and also in javascript
assum we have this js
var json = [{Name: "test", Passowrd:"test" }]
in C# i would convert this to class
public class myjson{
public string Name { get; set;}
public string Password { get; set;}
}
then with reflection call on the property
public GetValue(this myjson o, string propertyName){
return o.GetType().GetProperty(propertyName).GetValue(o);
}
in Jsvascript i would just call this
var value = json[0][property]
I hop this could help you
hello I think this can help you, I made a small example by picking up an answer written in Ajax and writing it in the console.
Look at the function in success, I think that's what you're looking for
function formToJSON(form) {
var obj = {};
var elements = form.querySelectorAll("input, select, textarea");
for (var i = 0; i < elements.length; ++i) {
var element = elements[i];
var name = element.name;
var value = element.value;
if (name) {
obj[name] = value;
}
}
return obj;
}
function test(id, url, method) {
var data = formToJSON(document.getElementById(id));
$.ajax({
type: method,
url: url,
data: data,
success: function (output, status, xhr) {
var response = JSON.parse(xhr.responseText);//<--- here is your JSON
for (var item in response) { // and set for to print indivual
console.log(item+' '+response[item]);
}
console.log(response);
},
cache: false
});
}

AJAX values from database to html skipped

I have these employee information which display if you click on the employee box. But sometimes the value of some fields returns null even if they have a value but when I retry it will return ok. Is this some code problem? here is my code...
First I store the elements into an object
var uamnumber = $(this).find(".box-list-agents-uamnumber").text();
var agentInfo = $(this).find(".box-list-agents-info").text().split("/");
var agentElement = {
txtUam: $("#search-txt-uam-number"),
txtFirstName: $("#search-txt-first-name"),
txtMiddleName: $("#search-txt-middle-name"),
txtLastName: $("#search-txt-last-name"),
txtContactNumber: $("#search-txt-contact-number"),
txtEmailAddress: $("#search-txt-email-address"),
txtClassification: $("#search-txt-classification"),
txtAgentStatus: $("#search-txt-agent-status"),
txtReasonResignation: $("#search-txt-reason-resignation"),
txtCsp: $("#search-txt-csp-name"),
txtProgramId: $("#search-txt-program-name"),
txtSite: $("#search-txt-site-name"),
txtBirthDate: $("#search-txt-birth-date"),
txtLiveDate: $("#search-txt-live-date"),
txtEndDate: $("#search-txt-end-date"),
txtProgram: $("#search-program-name")
};
var agentParam = {
uam: uamnumber,
csp: agentInfo[0],
program: agentInfo[1]
}
Dashboard_GetAgentInfo(agentParam, agentElement);
$("#search-well-tool-access").hide();
$("#search-well-agent-info").fadeIn();
and here is the function that has been called.
function Dashboard_GetAgentInfo(agentInfo,agentElement) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Dashboard_GetAgentInfo",
data: JSON.stringify(agentInfo),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var uamdetails = response.d;
var appendItem = "";
$.each(uamdetails, function (index, Dashboard_GetAgentInfoInfo) {
var uamnumber = Dashboard_GetAgentInfoInfo.uamnumber;
var firstname = Dashboard_GetAgentInfoInfo.firstname;
var middlename = Dashboard_GetAgentInfoInfo.middlename;
var lastname = Dashboard_GetAgentInfoInfo.lastname;
var contactnumber = Dashboard_GetAgentInfoInfo.contactnumber;
var emailaddress = Dashboard_GetAgentInfoInfo.emailaddress;
var csp = Dashboard_GetAgentInfoInfo.csp;
var cspid = Dashboard_GetAgentInfoInfo.cspid;
var program = Dashboard_GetAgentInfoInfo.program;
var programid = Dashboard_GetAgentInfoInfo.programid;
var site = Dashboard_GetAgentInfoInfo.site;
var siteid = Dashboard_GetAgentInfoInfo.siteid;
var birthdate = Dashboard_GetAgentInfoInfo.birthdate;
var livedate = Dashboard_GetAgentInfoInfo.livedate;
var enddate = Dashboard_GetAgentInfoInfo.enddate;
var classification = Dashboard_GetAgentInfoInfo.classification;
var agentStatus = Dashboard_GetAgentInfoInfo.agentstatus;
var reasonResignation = Dashboard_GetAgentInfoInfo.reasonresignation;
$(agentElement.txtUam).val(uamnumber);
$(agentElement.txtFirstName).val(firstname);
$(agentElement.txtMiddleName).val(middlename);
$(agentElement.txtLastName).val(lastname);
$(agentElement.txtContactNumber).val(contactnumber);
$(agentElement.txtEmailAddress).val(emailaddress);
$(agentElement.txtClassification).val(classification);
$(agentElement.txtAgentStatus).val(agentStatus);
$(agentElement.txtReasonResignation).val(reasonResignation);
$(agentElement.txtCsp).val(cspid)
$(agentElement.txtProgramId).val(programid);
$(agentElement.txtSite).val(siteid);
$(agentElement.txtBirthDate).val(birthdate);
$(agentElement.txtLiveDate).val(livedate);
$(agentElement.txtEndDate).val(enddate);
$(agentElement.txtProgram).text(program);
NumbersOnly();
});
},
error: function (XMLhttpRequest) {
alert("error in Dashboard_GetAgentInfo");
console.log(XMLhttpRequest);
}
});
}
and this is the web service that has been called
public List<Dashboard_GetAgentInfoDetails> Dashboard_GetAgentInfo(string uam, int csp, int program) /*int CSP, int Program*/
{
DataTable table = null;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "[Dashboard_GetAgentInfo]";
cmd.Parameters.AddWithValue("#uam", uam);
cmd.Parameters.AddWithValue("#csp", csp);
cmd.Parameters.AddWithValue("#program", program);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
table = this.dbConn.ExecuteDataTable(cmd);
Dashboard_GetAgentInfo_Details.Clear();
foreach (DataRow row in table.Rows)
{
Dashboard_GetAgentInfoDetails _list = new Dashboard_GetAgentInfoDetails();
_list.uamnumber = row["UAM #"].ToString();
_list.firstname = row["First Name"].ToString();
_list.middlename = row["Middle Name"].ToString();
_list.lastname = row["Last Name"].ToString();
_list.contactnumber = row["Contact Number"].ToString();
_list.emailaddress = row["Email Address"].ToString();
_list.csp = row["CSP"].ToString();
_list.cspid = Convert.ToInt32(row["CSPID"].ToString());
_list.program = row["Program"].ToString();
_list.programid = Convert.ToInt32(row["ProgramID"].ToString());
_list.site = row["Site"].ToString();
_list.siteid = Convert.ToInt32(row["SiteID"].ToString());
_list.birthdate = row["BirthDate"].ToString();
_list.livedate = row["LiveDate"].ToString();
_list.enddate = row["EndDate"].ToString();
_list.classification = Convert.ToInt32(row["Classification"].ToString());
_list.agentstatus = row["Agent Status"].ToString();
_list.reasonresignation = row["Reason Resignation"].ToString();
Dashboard_GetAgentInfo_Details.Add(_list);
}
return Dashboard_GetAgentInfo_Details;
}
does storing elements into an object and passing it as a parameter is a good practice of coding? and what may be the cause of the select having no value even if I when I try to console.log the value and it returns ok?
I think the problem is here:
$(agentElement.txtUam).val(uamnumber);
$(agentElement.txtFirstName).val(firstname);
...
You should do:
agentElement.txtUam.val(uamnumber);
agentElement.txtFirstName.val(firstname);
...
There is no need to use jquery selector $, because agentElement.txtUam is already one, also gathering elements inside an object is a best practice because you can't pass each one as a parameter.
The perfect answer to this is add a call back function so the dropbox have a option first before adding the val. Here is the idea of adding a callback function
function Filtering_GetSite(siteElement, callback) {
if (typeof (callBack) == "function") {
callBack();
}
}
the line checking of the callback parameter is to ensure that it its a function before executing so you can call the function like this Filtering_GetSite(sample) insted of Filtering_GetSite(sample,function(){}) when omiting the callback function

NetSuite SuiteScript 1.0 email attachment

I am fairly new to NetSuite scripting and have the following issue.
I am trying to send an email from SuiteScript 1.0. The Script is linked to the AFTER SUBMIT function of Sales Orders.
My code:
function OnAfterSubmit(record) {
var fromId = -5; //Authors' Internal ID
var sbj = 'subject';
var msg = '';
//load File from netSuite Document Repository with ID of 123
var orderid = nlapiGetRecordId();
var search = nlapiSearchRecord('salesorder', orderid);
var fileObj = nlapiLoadRecord(search.getRecordType(), search.getId());
//var detail = getOrderDetail(fileObj);
//Single Attachment - Attach File ID 123
//nlapiSendEmail(fromId, 'xyz#test1.example', sbj, msg, null, null, null, fileObj);
//multiple Attachments
//build Array of file objects
var attach = [fileObj];
//pass attach array as attachment parameter
nlapiSendEmail(fromId, 'charl#email.example', sbj, msg, null, null, null, attach);
}
I am trying to send the record that has been created by the user, via email.
The record parameter doesn't seem to be what I expect. The error I receive says "invalid search". When I used record.id, the error simply said "id". I also tried record.internalId.
function OnAfterSubmit(type) {
var fromId = -5; //Authors' Internal ID
var toEmail = 'charl#email.example';
var sbj = 'subject';
var msg = '';
var newRecord = nlapiGetNewRecord();
var recordAsJSON = JSON.stringify(newRecord);
var fileObj = nlapiCreateFile('salesorder.json', 'JSON', recordAsJSON);
nlapiSendEmail(fromId, toEmail, sbj, msg, null, null, null, fileObj);
}

How to pass value from client side to server side in asp.net?

how to pass the value in below script to the server side
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
FB.api('/me', function(me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('Email').innerHTML = me.email;
document.getElementById('gender').innerHTML = me.gender;
document.getElementById('birth').innerHTML = me.birthday;
document.getElementById('firstname').innerHTML = me.first_name;
})
Javascript variables exist on the client so in order to get those values into the server you'll need to execute a request from the client.You probably want an approach called AJAX. AJAX involves Javascript making requests to the server in the background of your page. You'll set up a C# web page that expects these background requests. If you use a GET request then then place the variables in the query string of your AJAX request to your new C# page. If you want to use a POST request then you'll set parameters in the data that you post to your page.
Libraries like jQuery make this kind of thing pretty simple.
In webform2.aspx
<script type="text/javascript">
function LoadValues(me) {
{
var Email = me.email;
var Name = me.name;
var Id = me.id;
var Dob = me.birthday;
var Gender = me.gender;
alert(Email)
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
var data2Send = '{"fbemail": '+Email+', "fbname":'+Name+', "fbid":'+Id+',"fbname":'+Dob+',"fbname":'+Name+' }';
$.ajax({
type: "POST",
url: 'webform2.aspx/Testmethod',
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) {console.log(arg) //call successfull
$("#lbltxt").text(arg);
},
error: function (xhr) {
alert(xhr); //error occurred
}
});
}
</script>
In webform2.aspx.cs
[System.Web.Services.WebMethod]
public static string TestMethod(string fbid, string fbemail, string fbsex, string fbdob)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader datareader;
con = new SqlConnection(".......");
cmd = new SqlCommand("SpFacebookInfo", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FbId", fbid);
cmd.Parameters.AddWithValue("#FbEmail", fbemail);
cmd.Parameters.AddWithValue("#FbSex", fbsex);
cmd.Parameters.AddWithValue("#FbDob", fbdob);
datareader = cmd.ExecuteReader();
datareader.Close();
return fbemail;
}
}
Set the value in a hidden variable as u did and do a document.myform.submit();
to go to Page_Load and read the variables

Categories

Resources