I want to update item based on button click and send data to database using ajax and javascript button when i click on buttons of other rows only last row gets updated not the desired row.
here's my markup and ajax call:
#foreach (var item in Model)
{
<tr>
<td>
<div id="modelquantiy-#item.Id">
#Html.DisplayFor(modelItem => item.Quantity)
<script>
var value = 0;
function add() {
if (value >= 5) {
alert("No More Than Five Items");
} else {
postData = { 'number': 1, 'id': #item.Id };
$.ajax({
url: '#Url.Action("Quantity", "Home")',
contentType: "application/json;charset=utf-8",
type: 'POST',
dataType: 'json',
data: JSON.stringify(postData),
success: function (data) {
$("#modelquantiy-#item.Id").html(data.result);
},
//if it breaks, you want to be able to press F12 to see why
error: function (data) {
window.console.log(data);
}
});
}
}
</script>
</div>
</td>
<td>
<input type="button" id="Add" name="Add" value="+" onclick="add();" />
<input type="button" id="Subtract" name="Subtract" value="-" onclick="subtract();" />
</td>
</tr>
}
and here's my backend code i have written in C#
public ActionResult Quantity(int number, int id)
{
Qty Quantity = db.Qties.FirstOrDefault(q => q.Id == id);
if (Quantity != null)
{
Quantity.Quantity = Quantity.Quantity + number;
db.SaveChanges();
}
return Json(new { result = Quantity.Quantity }, JsonRequestBehavior.AllowGet);
}
You should add script outsite the foreach, and use onclick to pass the params.
#foreach (var item in Model)
{
<tr>
<td>
<div id="modelquantiy-#item.Id">
#Html.DisplayFor(modelItem => item.Quantity)
</div>
</td>
<td>
<input type="button" id="Add" name="Add" value="+" onclick="add(#item.Id);" />
<input type="button" id="Subtract" name="Subtract" value="-" onclick="subtract();" />
</td>
</tr>
}
<script>
var value = 0;
function add(val) {
if (value >= 5) {
alert("No More Than Five Items");
} else {
postData = { 'number': 1, 'id': val };
$.ajax({
url: '#Url.Action("Quantity", "Home")',
contentType: "application/json;charset=utf-8",
type: 'POST',
dataType: 'json',
data: JSON.stringify(postData),
success: function (data) {
$("#modelquantiy-"+val).html(data.result);
},
//if it breaks, you want to be able to press F12 to see why
error: function (data) {
window.console.log(data);
}
});
}
}
</script>
The problem is add function is re-declared in each loop, so only the last declared add function will be working on clicking every button, this last declared function add will be having the statement $("#modelquantiy-#item.Id").html(data.result); which will change HTML of the last row (div) only, javascript can have only one function with the same name add if you declare a function with the same name again it will replace the old one.
The solution is to declare a function add only once, that is to put the script outside and add and extra parameter which denotes to which row the ajax result should be added.
#foreach (var item in Model)
{
<tr>
<td>
<div id="modelquantiy-#item.Id">
#Html.DisplayFor(modelItem => item.Quantity)
</div>
</td>
<td>
<input type="button" id="Add" name="Add" value="+" onclick="add(#item.id);" />
<input type="button" id="Subtract" name="Subtract" value="-" onclick="subtract();" />
</td>
</tr>
}
<script>
var value = 0;
function add(itemID) {
if (value >= 5) {
alert("No More Than Five Items");
} else {
postData = { 'number': 1, 'id': itemID };
$.ajax({
url: '#Url.Action("Quantity", "Home")',
contentType: "application/json;charset=utf-8",
type: 'POST',
dataType: 'json',
data: JSON.stringify(postData),
success: function (data) {
$("#modelquantiy-"+itemID).html(data.result);
},
//if it breaks, you want to be able to press F12 to see why
error: function (data) {
window.console.log(data);
}
});
}
}
</script>
Related
I have a view model called "RequestGoodsBrandViewModel" and it's the combination of two models (Request and RequestGoodsBrand), I want to post a list of objects "RequestGoodsBrand" of view model " RequestGoodsBrandViewModel " from view to controller.
public class RequestGoodsBrandViewModel
{
public Request request{ get; set; }//single object of this
public List<RequestGoodsBrand> requestGoodsBrand { get; set; }//List of object of this
}
my view
<tbody>
<tr v-for="(data, index) in goods">
<td width="20%">
<select id="goodsDDL" class="form-control">
<option v-for="options in goodsList" :value="options.id">{{options.name}}</option>
</select>
</td>
<td width="20%">
<input type="number" v-model="data.quantity" id="quantityTxt" class="form-control" />
</td>
<td width="20%">
<select id="brandDDL" class="form-control">
<option v-for="options in brands" :value="options.id">{{options.name}}</option>
</select>
</td>
<td width="7%">
<a v-on:click="addRow(index)" class="btn"><i class="fa fa-plus-circle" style="color:darkgreen"></i></a>
<a v-on:click="removeRow(index)" class="btn"><i class="fa fa-minus-circle" style="color:red"></i></a>
</td>
</tr>
<tr>
<td colspan="4">
<label>توضیحات</label>
<textarea id="descTxt" class="form-control"></textarea>
</td>
</tr>
</tbody>
View looks like this and table is dynamic,by pressing plus button new row will be added
public IActionResult AddRequestedGoods(RequestGoodsBrandViewModel model)// only RequestGoodsBrand of RequestGoodsBrandViewModel must be a list
{
}
Edit:
I post my ViewModel to the controller using ajax call
var requestGoodsBrand = {}
var request = {
NeedDate: $('#needDate').val(),
Description: $('#descTxt').val(),
}
var table= document.getElementById('goodsTbl')
for (var i = 1; i < table.rows.length - 1; i++) {
requestGoodsBrand[i] = {
GoodsId:(table.rows[i].cells[0].children[0].value),
Quantity:(table.rows[i].cells[1].children[0].value),
BrandId:(table.rows[i].cells[2].children[0].value)
}
}
var model = {
"request": request,
"requestGoodsBrand": requestGoodsBrand,
}
console.log(model)
var data = JSON.stringify(model)
$.ajax({
type: "POST",
async: true,
url: '/GoodsRequest/AddRequestedGoods',
data: model,
//contentType: "application/json; charset=utf-8",
//dataType: "html",
success: function (data) {
}
});
the first object receives data but the second object which is a list, return null
Any solution?
i wrote a demo code for the same please on Jquery try it :
Jquery
function () {
var requestGoodsBrand = [];
var request = {
NeedDate: 'demo1',
Description: 'demo2',
}
$('table tr').each(function () {
var entity = {
GoodsId: $($(this).find('td:eq(0) input')).val(),
Quantity: $($(this).find('td:eq(1) input')).val(),
BrandId: $($(this).find('td:eq(2) input')).val()
};
requestGoodsBrand.push(entity);
})
$.post('/Home/AddRequestedGoods', { requestGoodsBrand: requestGoodsBrand, request: request })
.done(function (result) {
}
C#
[HttpPost]
public string AddRequestedGoods(Request request, List<RequestGoodsBrand> requestGoodsBrand)
{
return "";
}
As you can see I have a for loop with Multiple ID and I want get the value of IDs and pass them to my controller, how can I achieve this ?
<form id="UserEdit">
#for (int i = 0; i < Model.Rights.Count; i++)
{
#Html.HiddenFor(m => m.Rights[i].ID)
}
<input id="BtnEditUserJS" onclick="PostFormUserEdit();" type="submit" value="Edit">
</form>
Generated HTML:
<input id="Rights_0__ID" name="Rights[0].ID" type="hidden" value="31">
<input id="Rights_1__ID" name="Rights[1].ID" type="hidden" value="32">
JavaScript:
function PostFormUserEdit() {
$.ajax({
type: 'POST',
url: '#Url.Action("EditUser")',
dataType: 'json',
data: ,
success: function (run) {
console.log('Ok');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
Controller:
[HttpPost]
public JsonResult EditUser(int[] RightId)
{
var rights = db.Rights.Where(b => RightId.Contains(b.Id)).ToList();
//do something with rights
}
You can achieve it this way :
function PostFormUserEdit()
{
var arr = [];
$("#UserEdit input[type='hidden']").each(function (index, obj) {
arr.push(obj.val());
});
$.ajax({
type: 'POST',
url: '#Url.Action("EditUser")',
dataType: 'json',
data: arr , // or you can try data: JSON.stringify(arr)
success: function (run) {
console.log('Ok');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
I have the following code on my partial view:
#foreach (var lineItem in Model.LineItems)
{
<tr>
<td>
<img src="#Url.Action("GetImage", "ImageBlocks", new { imageID = lineItem.Product.SelfOrDefault().Image.SelfOrDefault().ImageId, Width = 75 })" alt="Thumbnail" />
</td>
<td>
<span title="#(lineItem.Description ?? "")" id="lineItemDescription">#(lineItem.Product.ReceiptName ?? "")</span><br />
<span id="lineItemSKU">#lineItem.Product.SKU</span>
</td>
<td>
<span>#((lineItem.Product.InventorySummary ?? 0).ToString())</span><br />
</td>
<td><input type="text" id="lineItemQuantity" name="lineItemQuantity" value="#lineItem.Quantity" onblur="changeCartQty(#lineItem.Product.SKU,this.value)" /></td>
#if (lineItem.Discount != null ? lineItem.Discount.DiscountCategory != DiscountCategory.ORDER : true)
{
<td>
<input type="text" id="lineItemAmount" name="lineItemAmount" value="#lineItem.AdjustedUnitPrice.Value.ToString("C")" /><br />(Adj. #(lineItem.DiscountDisplayValue))
</td>
<td>#lineItem.AdjustedTotalLinePrice.Value.ToString("C")</td>
}
else
{
<td>#lineItem.BaseUnitPrice.Value.ToString("C")</td>
<td>#lineItem.TotalLineBaseValue.ToString("C")</td>
}
<td>Remove</td>
</tr>
}
<script>
On the lineItemQuantity text input, I want to change this from onblur to an onKeyDown event to capture the "Enter" key pressed to call the changeCartQty function with the same parameters. Here is the function being called:
function changeCartQty(ProductId, Quantity) {
var userId = $('#ID').val();
$.ajax({
url: "/Orders/AddtoCart",
type: 'POST',
cache: false,
datatype: 'json',
async: false,
data: { "ProductID": ProductId, "Quantity": Quantity, "UserID": userId},
success: function (data) {
console.log("Adjusted Quantity in cart");
success(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.error("[Error in Ajax request, adjust price] Code:" + jqXHR.status + "Error: " + errorThrown + " \nText Status: " + jqXHR.resonseText);
}
})
};
This works fine and the amounts update, I just need to change this to an onChange and I am unsure how this would be done.
Thanks.
I try send from html through JScript to java two parameters:
1. nameSelectedWhisky
2. quantitySelectedWhisky
function buyFromJS() {
//
// $.getJSON("buySuccessfulWhisky",
// {
// nameSelectedWhisky:$('#nameWhiskey').val(),
// quantitySelectedWhisky:$('#numberOrderWhisky').val()
// },
// function() {
// window.location.href = "warehouseWhisky";
// } );
//}
var nameSelectedWhisky = $('#nameWhiskey').val();
var quantitySelectedWhisky = $('#numberOrderWhisky').val();
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST",
data: JSON.stringify(nameSelectedWhisky.id, quantitySelectedWhisky.id),
url: '/buySuccessfulWhisky',
success: function (msg) {
window.location.href = "warehouseWhisky";
},
error:function(){
alert("ERROR");
}
})
}
<form id="buySelectedWhiskyThroughJavaScript" method="post">
<tr th:each="buySelectedWhisky : ${buySelectedWhisky}">
<td align="center">
<img th:attr="src=${buySelectedWhisky.photo}" width="150" height="250"/>Photo</td>
<td align="center" th:text="${buySelectedWhisky.nameWhisky}">Name</td>
<td align="center" th:text="${buySelectedWhisky.describeWhisky}">Describe</td>
<td align="center" width="100">
<input type="number" style="width: 100px" min="1" th:attr="max=${buySelectedWhisky.quantityWhisky}"
placeholder="Enter quantity" name="numberOrderWhisky" id="numberOrderWhisky"/>
</td>
<td align="center" th:text="${buySelectedWhisky.price}">Price</td>
<td align="center">
<input type="hidden" name="nameWhiskey" id="nameWhiskey" th:value="${buySelectedWhisky.nameWhisky}"/>
<!--<input type="hidden" name="quantityWhiskeyInDB" id="quantityWhiskeyInDB" th:value="${buySelectedWhisky.quantityWhisky}"/>-->
<input type="button" class="buttons" onclick="buyFromJS()" name="buttonBuyWhiskey" style="width: 60px" value="Buy"/> </td>
</tr>
</form>
I add two versions JavaScript
1 Version use $.getJSON("buySuccessfulWhisky"
This version is working and java recive all parameters, BUT this version is not updating the page
window.location.href = "warehouseWhisky";
if I try to add location.reload() after "warehouseWhisky", then "buySuccessfulWhisky" is updated instead of "warehouseWhisky". Becouse if I will not update page "warehouseWhisky" I see wrong not updated information. If I'm updating the page "in the manual mode" - everything is working.
How proper update the "warehouseWhisky" page?
Next code through AJAX
Is not sending information to java
Java code to recive from JScript
#Controller
public class SuccessfulBuyWhiskey {
#RequestMapping(value = "buySuccessfulWhisky", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView view(#RequestParam("nameSelectedWhisky")String name,
#RequestParam("quantitySelectedWhisky")Integer quantityOrder) {
System.out.println("Name: = "+name);
System.out.println("Quantity: = "+quantityOrder);
function sendBuyWhiskyInJava(){
$('#buySelectedWhiskyThroughJavaScript').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/buySuccessfulWhisky',
data: {
nameSelectedWhisky: $("#nameWhiskey").val(),
quantitySelectedWhisky: $("#numberOrderWhisky").val()
},
success: function(data) {
window.location.href = "warehouseWhisky";
console.log(data)
}
})
})
}
I want to do an ajax request to update the status of an item, but for one or many selected item.
So how can I post all the selected checkbox items to process it on the handle page?
Here is some code I use., but it will only post one item to the process page.
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[78]">
</td>
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[182]">
</td>
And the javascript
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = {
item: $('input[name=item\\[\\]]').val(),
}
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
Assign the unique name to each checkbox
Put all checkboxes in a form tag (all input fields in a single form).
Use serialize() or serializeArray() for collecting data from form
store data in var formData
Code:
<form id="form-name">
<tr>
<td>
<input type="checkbox" name="item[1]">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="item[32]">
</td>
</tr>
</form>
Javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = $('#form').serializeArray();
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
},
error: function (data) {
console.log('Error:', data);
}
});
This will post an array of items to the url.
I did same thing in minor different way.
I got list of checkbox and names contain their id.
<input type="checkbox" class="bulkChecked" name="{{$value->id}}">
And Inside your event handler
var ids = [];
$(".bulkChecked:checked").each(function () {
ids.push($(this).attr("name"));
});
So at this point you have got ids of checked boxes. No you can pass 'ids' array with your ajax call