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.
Related
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>
I'm trying to create a view where my customer can update his personal info (like First Name, Last Name, email, ect) using Liquid/JS, but I have failed epicly.
The nearest point that I have reached is this post where they use a form and some AJAX to update but I'm getting code 500. This is the code that I'm using (based on that).
<form action="/a/custmeta" method="POST" id="custmeta">
<input type="text" name="customer[id]" value="{{ customer.id }}" />
<input type="text" name="customer[first_name]" value="{{ customer.first_name }}" placeholder="namespace1.key1" />
<input type="text" name="customer[last_name]" value="{{ customer.last_name }}" placeholder="namespace2.key2" />
<input type="submit" />
</form>
<script>
$('form#custmeta').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
data: $(this).serialize(),
url: '/admin/customers/#{{ customer.id }}.json',
success: function (data) {
var formValid = (data.status === 'OK');
if (formValid) {
var msgs = '';
for (var i=0;i<data.messages.length;i++) {
msgs += '-- ' + data.messages[i] + '\n';
}
if (msgs > '') {
alert('SUCCESS WITH MESSAGES:\n\n' + msgs);
}
else {
alert('SUCCESS!');
}
}
else {
alert('Status: ' + data.status + '\nMessage: ' + data.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('AJAX or Server 500 error occurred');
}
});
return false;
});
</script>
found this other post where you could do it using the API but dont know how to use it.
Any help?
For destination text field, based on the input, the auto suggestion will be displayed as checkboxes. I can select one or more values and my requirement is to get these selected values on the controller side, Once I click on the search button. How can I achieve this for dynamic checkboxes, please provide any suggestions.
jquery:
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
HTML:
<form method="post" id="searchForm" action="someAction/showStatistics" id="ems">
<label>Destination</label>
<input type="text" id="destinationName" name="destinationName" value="${someForm.destinationName}" class="field" />
<div class="dest"></div>
<input type="submit" class="button" value="search" />
</form>
Try this
$(document).ready(function () {
var dynamicCheckbox = [];
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
};
});
}
});
$('.button').on('click', function (event) {
event.preventDefault();
$('.dest input:checked').each(function() {
dynamicCheckbox.push($(this).attr('name'));
});
console.log(dynamicCheckbox);
});
});
Here in dynamicCheckbox you will get the names of the checked checkboxes.
Hope that's what you need!
The following code is my original code. In the code, I tried to post value of an input for each checkbox which is checked.
<tbody class="myFormSaldo">
<tr>
<td> <input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$ref.'" onchange="enableList(this);" class="chb_group" /> </td>
<td> <input name="items['.$i.']" type="text" readonly value="'.$obj->items.'" /> </td>
<td> <input name="size['.$i.']" type="text" readonly value="'.$obj->size.'Kg" /> </td>
<td> <input name="quantity['.$i.']" type="text" readonly value="'.$obj->myquantity.'" /> </td>
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_size=$_POST['size'][$i];
The code above is working fine. It post the value of each inputs for each checkbox which were checked. For example; if there were three checkedbox which were checked and the form was submited, then it would post three arrays (3 loop) of : $product_name,$product_size,etc..
What I want now is to use Ajax. Like this:
var product_name= document.getElementById('product_name').value;
var product_size = document.getElementById('product_size').value;
$.ajax(
{
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: product_name='+product_name+'&product_size ='+product_size ,
cache: false,
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
But it doesn't count or find the checkbox
So my question now is how to do the same as the php do with foreach($_POST['checkbox'] as $i) in ajax?
I am just a beginner in all of these things.
Thank you for any help.
You are using your product_name as a string, not as a variable:
Try this:
data: 'product_name='+product_name+'&product_size='+product_size,
Or, as Ghost sad in comments, use formdata.
var dataString = $('form').serialize();
and later, in the ajax:
data: dataString,
...
Try this...
<script>
$.ajax({
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: "{'product_name':" + product_name + ", 'product_size':" + product_size+ "}",
cache: false,
dataType: "html"
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
</script>
Try this
Ajax is simplified check here
var data = $('form').serialize();
$.post( "../actions/selectReferenceOrder.php", { name: data}).done(function( data ) {
alert( "Data Loaded: " + data );
});
OR
$.post( "../actions/selectReferenceOrder.php", { product_name: product_name, product_size : product_size }).done(function( data ) {
alert( "Data Loaded: " + data );
});
I have a table showing a list of 'sightings' in my case and each specific column can be updated as the value are displayed in field, etc. Each individual row has an update button on it where I would like to click when I have finished updating that particular row. This is my forEach loop displaying all the entries:
<c:forEach var="mySightings" items="${mySightings}">
<tr>
<td><input name="id" class="data sighting_id" disabled value="${mySightings.id}"/></td>
<td><input name="total_pests" type="number" value="${mySightings.total_pests}"/></td>
<td><input name="date" type="date" value="${mySightings.date}"/></td>
<td><input name="username" disabled value="${mySightings.username}"/></td>
<td><textarea name="information">${mySightings.information}</textarea></td>
<td>
<button class="update_sighting btn btn-success">Update</button>
</td>
<td>
<button class="delete_sighting btn btn-danger" value="${mySightings.id}">Delete</button>
</td>
</tr>
</c:forEach>
This is my Ajax function, which I think is definitely wrong:
$(".update_sighting").click(function(){
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/updateSighting",
data: $(this).serialize(),
success: function(response) {
$("#alert").show();
alert("Submitted");
$(".errormsg").hide();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
Do I need to change something to my ajax code? I dont know what I should do next?
And my Controller which handles the request:
#RequestMapping(value = "/updateSighting", method = RequestMethod.POST)
public #ResponseBody String updateUser(Sighting sighting, Model model) {
sightingsService.updateSighting(sighting);
List<Sighting> sightings = sightingsService.getAllSightings();
model.addAttribute("sightings", sightings);
return "allSightings";
}
Please help, Thanks
The issue is with serialising the data. You are calling it on the button element instead of a form, but even then that would serialise the entire form, not just the row which was clicked on. So you need to build the object to serialise manually:
$(".update_sighting").click(function(){
var $row = $(this).closest('tr');
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/updateSighting",
data: {
id: $('input[name="id"]', $row).val(),
total_pests: $('input[name="total_pests"]', $row).val(),
date: $('input[name="date"]', $row).val(),
username: $('input[name="username"]', $row).val(),
information: $('input[name="information"]', $row).val()
},
success: function(response) {
$("#alert").show();
alert("Submitted");
$(".errormsg").hide();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});