My ajax is
<script>
jQuery(function ($) {
var size = $('#ddlsize').val();
var color = $('#ddlcolor').val();
$('#addtocart').click(function () {
$.ajax({
url: '#Url.Action("AddTocart", "ShoppingCart")',
data: {
id: '#Model.ProductId',
size: size,
color: color,
},
dataType: "html",
type: 'POST',
success: function (data) {
alert("Da them vao gio hang");
},
error: function () {
alert("Co loi xay ra vui long thu lai");
}
});
});
});
</script>
And in Controller
public ActionResult AddTocart(int id, string size, string color)
{
Product productitem = dbcon.Products.Where(p => p.ProductId == id).SingleOrDefault();
var cart = ShoppingCart.Getcart(this.HttpContext);
cart.AddtoCart(productitem, size, color);
return RedirectToAction("Index");
}
Some time when i click in button add to cart,i see the error but it has been do an action and add to the cart.i didn't how it add product to cart when error
Related
Good day, I am trying to manual ajax this
Add to cart
What this does is, It will add to the cart the one-time purchase option from the woocommerce subscription. I am trying to ajax it so it won't refresh the page when you click on it.
I found an idea how to manually ajax it by using these lines of codes. Reference here
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function(response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
The codes above work and it does ajax however, it displays the monthly subscription, not the one-time purchase. It should display the one-time purchase because of the &convert_to_sub_55337=0 which means the one-time subscription option is selected.
Also, I am getting an error after clicking the button on the console log
Uncaught TypeError: $button is undefined
I am a newbie to handling ajax so I am unsure about the issue
Thank you in advance!!
you can try this code i hope it will helped.
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
jQuery('.testing').removeClass('added').addClass('loading');
},
complete: function(response) {
jQuery('.testing').addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
I want to display update content after posting data by jquery ajax. I tried it but not display data.
here is my code...
jquery ajax
$(document).ready(function () {
$('#paid').click(function () {
var pid = $('#pid').val();
var amt = $('#amt').val();
var payType = $('#payType').val();
$.ajax({
type: "POST",
url: "/Reception/Registration/AddPaidBalance",
data: { PatientId: pid, PaidAmt: amt, PaymentType: payType },
success: function (data) {
}
});
});
})
controller
[HttpPost]
public async Task<IActionResult> AddPaidBalance(PatientBilling patientBilling)
{
if (ModelState.IsValid)
{
_db.PatientBilling.Add(patientBilling);
await _db.SaveChangesAsync();
//return RedirectToAction("Details", "Registration", new { area = "Reception", id = patientBilling.PatientId });
//return RedirectToAction("Details", "Registration", new { patientBilling.PatientId});
}
return View();
}
help me out from this issue.
Based on your code, you make ajax request to post data of PatientBilling to action method. To display new-added PatientBilling information on Details page after the request completes successfully, you can do redirection in success callback function, like below.
<script>
$(document).ready(function () {
$('#paid').click(function () {
var pid = 1;//$('#pid').val();
var amt = "amt";//$('#amt').val();
var payType = "type1";//$('#payType').val();
$.ajax({
type: "POST",
url: "/Reception/Registration/AddPaidBalance",
data: { PatientId: pid, PaidAmt: amt, PaymentType: payType },
success: function (data) {
window.location.href = "#Url.Action("Details", "Registration", new { Area = "Reception"})" + "?patientId=" + pid;
}
});
});
})
</script>
Details action
public IActionResult Details(int patientId)
{
// code logic here
// get details of PatientBilling based on received patientId
// ...
return View(model);
}
I have a large dataset from a stored procedure that I want to display in pages on an ASP.NET webpage. I can't make demands of the DBAs, so asking them to support pagination on their end isn't possible. The data is currently being displayed in a widget that's being populate by an ajax call to an action in my controller. I want the user to be able to change the page and page size without the stored procedure firing again, but I don't know how to pass the data/model from the getData call to the paginateData call.
Ajax:
require(["jquery", "ajax"], function ($, ajax) {
getData: function () {
ajax.html({
url: Router.action("Widgets", "GetData"),
interval: 3000,
maxAttempts: 20,
cache: false,
success: function (response) {
$('#view-dataList', $context).replaceWith(response);
}
});
}
paginateData: function () {
ajax.html({
url: Router.action("Widgets", "PaginateData", {pageNumber: pageNumber, pageSize: pageSize, data: ??????}),
interval: 3000,
maxAttempts: 20,
cache: false,
success: function (response) {
$('#view-dataList', $context).replaceWith(response);
}
});
}
}
Widgets Controller:
[Route("GetData")]
public ActionResult GetData()
{
var model = new DataModel();
var service = new SqlService();
var customerID = Identity.Current.OptaviaID.ToString();
model.RecentActivities = service.LoadData();
return PartialView(model);
}
[Route("PaginateData")]
public ActionResult PaginateData(int pageNumber, int pageSize, IList<Data> data)
{
var model = new DataModel();
var page = model.page.Skip((pageNumber - 1) * pageSize).Take(pageSize);
model.Data = page;
return PartialView(model);
}
What is a good way to design this?
I ended up changing the return values of GetData and PaginateData in the controller to return the model in json to be stored in the javascript withing the ajax success function and added a new method DisplayData to return the unserialized PartialView. I changed PaginateData and DisplayData to HttpPost calls accepting the model that we stored in javascript.
Javascript (notice that getdata, paginate, and display are tethered together via success):
require(["jquery", "ajax"], function ($, ajax) {
var currentData = null;
var currentPage = null;
var actions = {
getData: function () {
ajax.html({
url: Router.action("Widgets", "GetData"),
interval: 3000,
maxAttempts: 20,
cache: false,
success: function (response) {
currentData = response;
actions.paginateData();
}
});
},
paginateData: function () {
ajax.html({
url: Router.action("Widgets", "DisplayData"),
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
interval: 3000,
maxAttempts: 20,
cache: false,
data: JSON.stringify({ data: currentData, startIndex: 0, pageSize: 10 }),
success: function (response) {
currentPage = response,
actions.displayData();
}
});
},
displayData: function () {
ajax.html({
url: Router.action("Widgets", "PaginateData"),
type: 'POST',
contentType: 'application/json; charset=utf-8',
interval: 3000,
maxAttempts: 20,
cache: false,
data: JSON.stringify(currentPage),
success: function (response) {
$('#view-dataList', $context).replaceWith(response);
}
});
}
}
}
Controller:
[Route("GetData")]
public ActionResult GetData()
{
var model = new DataModel();
var service = new SqlService();
var customerID = Identity.Current.OptaviaID.ToString();
model.Data = service.LoadData();
Content(JsonConvert.SerializeObject(model), "application/json");
}
[HttpPost]
[Route("PaginateData")]
public ActionResult PaginateData(DataModel data, int pageNumber, int pageSize)
{
data.Data = data.Data.Skip((pageNumber - 1) * pageSize).Take(pageSize);
Content(JsonConvert.SerializeObject(data), "application/json");
}
[HttpPost]
[Route("DisplayData")]
public ActionResult DisplayData(DataModel data)
{
return PartialView(data);
}
Now in my javascript I can call getData on page load to get the data, get the default page and count, and display it, but I can also call paginateData when the user changes the page or changes the page size to get the new page and display it without querying the database again which answers this question.
I'have page with a slide with some images. what I need now is to add a new image to the slide on carousel without a postback. the code I have is this
flex slider
$(window).load(function() {
$('.flexslider').flexslider({
animation: "slide",
controlsContainer: ".flex-container",
start: function(slider) {
$('.total-slides').text(slider.count);
},
after: function(slider) {
$('.current-slide').text(slider.currentSlide);
}
});
ajax code
$.ajax({
url: '#Url.Action("LoadCarrusel","picture",new { #id = #Model.Propertyid })',
type: 'GET',
dataType: 'json',
success: function (data) {
var flexslider = document.getElementById("flexslider");
// process the data coming back
$.each(data, function (index, item) {
var link = "../../Content/Uploaded-img/" + item;
var imag = document.createElement("img");
imag.setAttribute("src", link);
var newpicture = document.createElement("li");
var newpictureItem = document.createTextNode(imag);
newpicture.appendChild(imag);
flexslider.appendChild(newpicture);
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
and the controller which pass the data json is
public ActionResult LoadCarrusel(long id)
{
var routes = from s in db.Picture
where s.IdProp == id
select s.Location;
return Json(routes, JsonRequestBehavior.AllowGet);
}
I have built a jquery dialog to show a partial view for entering data.
I have built the action link:
#Html.ActionLink("Add New Service Provider", "PartialNewCust", "Customer", null, new { #class = "addServiceProviderLink" })
I have the controller action:
public ActionResult PartialNewCust()
{
return PartialView();
}
And the div / jQuery code:
<div id="AddServiceProvDialog" title="Add Service Provider"></div>
<script type="text/javascript">
var linkObj;
$(function () {
$(".addServiceProviderLink").button();
$('#AddServiceProvDialog').dialog(
{
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons:
{
"Add": function () {
$("#addProviderForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".addServiceProviderLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#AddServiceProvDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#addProviderForm");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
return false;
});
});
});
The partial view renders fine but opens a new page and does not come up as a modal dialog.
What am I doing wrong.
On a side note: my autocomplete code is also not working by my jQuery datetime picker is...
$(document).ready(function()
{
$(".date").datepicker();
}
);
$(document).ready(function () {
$("#CustByName").autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
}
});
},
minLength: 3
});
});
My guess is that you misplaced the return false statement in the button's click handler, thus the default behavior is not prevented as you expect, and the link is simply followed:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
dialogDiv.html(data);
...
dialogDiv.dialog('open');
// this return statement should be in the "click" handler,
// not in success callback of the .get() method !
return false;
});
});
Your code should then be:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
...
});
// return here to prevent default click behavior
return false;
});