Loop thru form to fill json object for post - javascript

I have a shopping cart and want to post it to my login window so I can proceed to checkout after authentication. But before this can be achieved, I am using a webservice call on shoppingcart window load, so I can get a hash of my cart items and secure the communication between us. How can I serialize all my cart items in the data object so I can send it to my webserver?
This is what I am trying so far, but it isn't working...
$(document).ready(function () {
getCartHashCode();
});
function getCartHashCode() {
var url = 'home/GetHashRequest';
var data = new Array();
//put all items from the cart on the data object
for (i = 1; i <= $('.product-name').length; i++) {
//setting up json parameter names
var CART_NAME = 'CART_'+i+'_NAME';
var CART_PRICE = 'CART_'+i+'_PRICE';
var obj = { CART_NAME: $('input[name=Cart['+i+'].Name').val(),
CART_PRICE: $('input[name=Cart['+i+'].Price').val() }
data.push(obj);
}
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (hash) {
alert("It worked! Hash = " + hash.toString());
}
});
EDIT
Follow up after ferrants' comment: I took it off, and really did go to the server! Thanks
The problem is how do I get the items I posted on the server side?
I have a item domain class defined as this:
public class Item
{
public string Name { get; set; }
public int UnitPrice { get; set; }
}
and my controller action is this:
public string GetHashRequest(List<Item> cart)
{
GetSecureHashPOCORequest hashRequest = new GetSecureHashPOCORequest();
}

Related

fetching an Object from Action Item and displaying on View without Page refresh Using Ajax and Javascript

public class vendorData
{
public int VCode { get; set; }
public string currency { get; set; }
}
[HttpGet]
public IActionResult OnGetVendorCode(string VendorName)
{
var VendorMaster = _context.VendorMaster.ToList();
var VendorCodes = from O in VendorMaster where O.CompanyID == Company && O.VendorName == VendorName select O.VendorCode;
var currency= from O in VendorMaster where O.CompanyID == Company && O.VendorName == VendorName select O.Currency;
vendorData vendorData = new vendorData();
vendorData.VCode = VendorCodes.FirstOrDefault();
vendorData.currency = currency.FirstOrDefault();
return new JsonResult(vendorData);
}
function GetPOVendorCode(ID) {
$.ajax(
{
data: { VendorName: ID },
url: '/Purchase/POGenerals/Create/?handler=VendorCode',
type: 'GET',
success: function (data) {
const myJSON = JSON.stringify(data);
alert(myJSON.VCode);
}
});
}
How can I access each object item through my Ajax call? and save it in a variable so that I could use that on my page? Is there any other better way? I am using ASP razor pages and trying to update other text boxes of the purchase order when I select the vendor name
The response data is the correct object so that no need use JSON.stringify(data);.
Also the response data is camel case format.
In summary, just use data.vCode to get the value.

passing an array from ajax call to controller, array empty in controller

Can anyone suggest what I need to change here?
I'm getting classes from elements that contain the class 'changed', the classes I get contain id's that I want to pass to the controller method.
When I look in the network tab I can see the data I want in the payload, it looks like this:
{"list":["GroupId-1","SubGroupId-2","changed"]}
but when I put a breakpoint on the controller the list is null.
This is the class I'm expecting in the controller method:
public class MemberGroups
{
public string GroupId { get; set; }
public string SubGrouId { get; set; }
public string Status { get; set; }
}
javascript for the save
function Savechanges() {
var spans = document.getElementsByClassName("changed");
var list = [];
$.each(spans,
function (key, value) {
$.each(value.classList,
function (key, value) {
list.push(value);
});
});
var dataToPost = JSON.stringify({ list: list });
$.ajax({
url: "/umbraco/Api/OrganisationMemberGroupsDashboardApi/UpdateMemberToGroup",
data: JSON.stringify({ list }),
type: "POST",
contentType: "application/json; charset=utf-8", // specify the content type
})
.done(function (data) {
});
}
controller
public string UpdateMemberToGroup( List<MemberGroups> list)
{
// save records
}
The spans are created dynamically and added to a treeview. When they are dragged and dropped all classes are removed then the 'changed' class is added along with the id classes so I only pass the ones I need to to the controller
var s = document.createElement('span');
s.classList.add('node-facility');
s.classList.add('ui-droppable');
s.classList.add('GroupId-' + value.GroupId);
s.classList.add('SubGroupId-0');
s.id=('GroupId-' + value.GroupId);
s.appendChild(document.createTextNode(value.GroupName));
This variant was tested using postman body json -
["GroupId-1","SubGroupId-2","changed"]
Change your ajax data to this:
data: list,
and your controller action:
public string UpdateMemberToGroup([FromBody] []string list)
{
var memberGroups = new MemberGroups
{
GroupId =list[0],
SubGrouId =list[1],
Status =list[2]
};
// save records
}
This variant was tested in postman using
{"GroupId":"GroupId-1","SubGroupId": "SubGroupId-2", "Status":"changed"}
you can put the code in javascript:
var data={GroupId:list[0],SubGroupId:list[1], Status:list[2]}
......
....
data:data,
.....
your controler action in this case:
public string UpdateMemberToGroup([FromBody] MemberGroups memberGroups)
{
// save records
}
And I don't know what version MVC you use , but for some versions instead of [FromBody] better to use [FromForm] or don't use anything at all.

.net Core Using razor function in Javascript

Hi i got to use c# code in js. My js and .cshtml page are separeted . I wrote a function in .cshtml page and gotta call it in .js file.
In Js file
DataList.forEach(function (item) {
...
var users = GetUsers(item.AssignedUsers);
It goes here
Index.cshtml
<script>
function GetUsers(userIdList) {
//it logs it, i can get theese values from here
console.log("userIdList");
console.log(userIdList);
#{ // but in here it says userIdList does not exist in current content
//also tryed this.userIdList
var users = userIdList.Split(",");
foreach (var item in users)
{
var user = _Manager.FindByIdAsync(item.UserId).Result;
}
}
}
</script>
You can pass list from ajax to controller action,and action return a list you want.
Here is a demo:
<button onclick="sendData()">
send
</button>
<script>
function sendData() {
//here is a sample list
var list = [];
var user1 = {};
user1.Id = 1;
user1.Name = "u1";
list.push(user1);
var user2 = {};
user2.Id = 2;
user2.Name = "u2";
list.push(user2);
$.ajax({
type: "POST",
url: '#Url.Action("SendData", "Test")',
contentType: "application/json",
data: JSON.stringify(list),
}).done(function (data) {
console.log(data);
//the data is you want
});
}
</script>
action:
public List<User> SendData([FromBody]List<User> list) {
//you can do something and return a list you want here
return list;
}
User:
public class User {
public int Id { get; set; }
public string Name { get; set; }
}
result:

Ajax success function not receive data

Below is webmethod of my web form which is returning a List of data and it works fine:
[WebMethod]
public static List<SalesInvoiceFinalCalculationEntity> salesInvoiceFinalCalculaiton(string InvoiceNo)
{
List<SalesInvoiceFinalCalculationEntity> list = new List<SalesInvoiceFinalCalculationEntity>();
list = SalesInvoiceManager1.salesInvoiceFinalCalculaiton(InvoiceNo);
return list;
}
But in below Ajax function, I can't retrieve the data. When I bind data to textbox in ajax success function, it displays Undefined text in Html textBox.
function salesInvoiceFinalCalculaiton() {
var InvoiceNo = $("#txt_InvoiceNo").val();
$.ajax({
async: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/AjaxRequestToServer.aspx/salesInvoiceFinalCalculaiton", //URI
data: "{InvoiceNo:'" + InvoiceNo + "'}",
dataType: "json",
success: function (data) {
document.getElementById("txtinvoicevalue").value=(data.totalprice);
document.getElementById("txtTotalDiscount").value = data.discountamt;
document.getElementById("txtTotalTaxableValue").value = data.taxableamt;
document.getElementById("txtTotalCGST").value = data.cgstamt;
document.getElementById("txtTotalSGST").value = data.sgstamt;
document.getElementById("txtGrandTotal").value = data.grandtotal;
},
error: function (xhr) {
if (xhr.statusText == "Invalid Request") {
sessionStorage.clear();
}
}
});
}
Here is Data Layer and the stored procedure:
public static List<SalesInvoiceFinalCalculationEntity> salesInvoiceFinalCalculaiton(string InvoiceNo)
{
try
{
List<SalesInvoiceFinalCalculationEntity> SalesInvoiceFinalCalculation = new List<SalesInvoiceFinalCalculationEntity>();
DataSet ds = SqlHelper.ExecuteDataset(Util.ConnectionString, CommandType.StoredProcedure, "sp_salesInvoiceFinalCalculaiton",
new SqlParameter("#InvoiceNo", InvoiceNo));
foreach (DataRow dr in ds.Tables[0].Rows)
{
SalesInvoiceFinalCalculationEntity list = new SalesInvoiceFinalCalculationEntity(dr);
SalesInvoiceFinalCalculation.Add(list);
}
return SalesInvoiceFinalCalculation;
}
catch (Exception ex)
{
throw ex;
}
}
And this is my entity Class:
public class SalesInvoiceFinalCalculationEntity
{
public int InvoiceNo { get; set; }
float totalprice { get; set; }
float discountamt { get; set; }
float taxableamt { get; set; }
float cgstamt { get; set; }
float sgstamt { get; set; }
float grandtotal { get; set; }
public SalesInvoiceFinalCalculationEntity() { }
public SalesInvoiceFinalCalculationEntity(DataRow dr)
{
InvoiceNo = Convert.ToInt32(dr["InvoiceNo"]);
totalprice = float.Parse(dr["totalprice"].ToString());
discountamt = float.Parse(dr["discountamt"].ToString());
taxableamt = float.Parse(dr["taxableamt"].ToString());
cgstamt = float.Parse(dr["cgstamt"].ToString());
sgstamt = float.Parse(dr["sgstamt"].ToString());
grandtotal = float.Parse(dr["grandtotal"].ToString());
}
}
why is data is not received in success function!
First of all, using async: false it is a bad practice because it's freeze your window during to your request. Don't use it.
The issue is that you have to return a json object from your server-side method in order to receive response in success callback function of your ajax method.
[WebMethod]
public static string salesInvoiceFinalCalculaiton(string InvoiceNo)
{
List<SalesInvoiceFinalCalculationEntity> list = new List<SalesInvoiceFinalCalculationEntity>();
list = SalesInvoiceManager1.salesInvoiceFinalCalculaiton(InvoiceNo);
return JsonConvert.SerializeObject(list);
}
Web requests work with json format.
Finally resolved it. I forgot to mentioned
Public
in
SalesInvoiceFinalCalculationEntity
entity all variables and document.getElementById("txtinvoicevalue").value=(data.d[0].totalprice); this should be instead of
document.getElementById("txtinvoicevalue").value=(data.totalprice);
I think the problem is, that you're trying to send a Java Class to your JavaScript file. You can only send simple data types numbers, letters. As I understand, you're trying to access the member variables of SalesInvoiceFinalCalculationEntity.
If that's the case, you need to send it as a JSON object and get the data like this and then parse it.
The idea behind AJAX is to make the experience for the user better by not freezing the website using asynchronous requests. By calling the AJAX call with
async: false
removes the idea behind AJAX. You could then simply make a normal call to the server.
Use this:
https://www.newtonsoft.com/json
Serialize your list and return it as a string.
Then, in your javascript:
success: function (data) {
data = JSON.parse(data);
document.getElementById("txtinvoicevalue").value=(data.totalprice);
document.getElementById("txtTotalDiscount").value = data.discountamt;
document.getElementById("txtTotalTaxableValue").value = data.taxableamt;
document.getElementById("txtTotalCGST").value = data.cgstamt;
document.getElementById("txtTotalSGST").value = data.sgstamt;
document.getElementById("txtGrandTotal").value = data.grandtotal;
},
Try
success: function (data.d) rather than success: function (data). If I recall when using webmethods the return object is within data.d and not simply data.
Also, despite what other answers say. When using the [webmethod] attribute and jquery ajax, you do not have to convert your response object to json. It will do so automatically.

Reading from localStorage, passing it to the server through JSON and creating a session from it in MVC3

Roughly what I am trying to implement is a login system for a website that allows for the usage of a guests account, storing their data in localStorage. If they click on the button to log in as a guest, it will attempt to read through localStorage for any previous data that might exist before passing it off to the server so it can create a session and rely on that session for returning a view based on that data. This likely isn't the most efficient way of handling it but if the users log in with an account instead of as a gust, it will retrieve information from a database so it has to work in conjunction with that.
Just to establish what is happening server-side, it's something akin to iGoogle where a list of URLs are supplied by the user and it will return a webpage containing a scrollable wall of iFrames of those URLs. If they're logged in with an actual ccount, their data is stored in the database as well as the session and if they're logged in as a guest, their data is stored locally as well as the session. This could again probably be optimized to allow for less reliance on the session variable server-side but I'm focusing on getting it working first and then I can optimize it.
View: (Contains some debugging code still)
<div id="LocalStorageStatus"></div>
<script type="text/javascript">
var isGuest = false;
if (Modernizr.localstorage) {
$('#LocalStorageStatus').html('<button type="input" onclick="guest()" id="guest">Log in as guest</button>');
function guest() {
localStorage["Guest"] = true;
var URLarray = new Array();
if(localStorage["URL"] != "0")
{
for(var i = 0; i < localStorage["URL"]; i++)
URLarray[i] = localStorage["URL" + i];
}
var data = {
ID : 'local',
URL: localStorage["URL"],
URLList : URLarray,
Template: localStorage["Template"]};
$.ajax({
url: '#Url.Action("Guest","Login")',
data: JSON.stringify(data),
success: function () { alert("YOU ARE A GUEST!") },
error: function () { alert("YOU ARE NOT A GUEST!") },
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json'
});
}
}
else {
$('#LocalStorageStatus').html('Guest log-in requires an HTML5-compatible browser.');
}
</script>
Model:
public class GuestUser
{
public string ID { get; set; }
public int URL { get; set; }
public List<string> URLList { get; set; }
public int Template { get; set; }
}
Controller: (For a temporary view that will establish the session before redirecting them to the area for logged-in users)
[HttpPost]
public ActionResult Guest(GuestUser guest)
{
Session.SetDataInSession("ID", guest.ID);
return RedirectToAction("../Frames");
}
Right now, it seems to be creating and passing the JSON object just fine, though it does return a failure despite setting the session ID, but I don't want to proceed from here until I know that the JSON object is being built as I want it to be. Will this work with how I've implemented it and have I committed any major coding atrocities in the process?
As an alternative to this, I would like using a class object that stores the ID, an arraylist of URLs and an integer but I'm unsure of the complexity this might add to due to handling an object rather than easily definable variables.

Categories

Resources