Reputation: 143
i am clicking on a simple add to cart button to add an item to a cart , if the item is already present it gives an error item already
. all goes well , but when i click the button second time , i have to close the alert box twice , 3rd time i click , i have to close the alert box thrice and so on ... this goes on until i refresh the page , and same thing starts from scratch
jquery code :
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function()
{
alert("Item has been added to cart");
},
error:
function(xhr)
{
if (xhr.responseText=="already present")
alert("item is already present in cart");
else if(xhr.responseText=="error")
alert("item cannot be added , server error");
}
});
return false;
//e.preventDefault();
});
});
}
servlet code :
if(n.equals("addtocart"))
{
String user = req.getParameter("user");
int pid = Integer.parseInt(req.getParameter("pid"));
k=o.addintocart(user,pid);
if(k==2)
{
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
pw.write("already present");
}
else if(k==0)
{
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
pw.write("error");
}
}
error or success the behavior is same for both
Upvotes: 0
Views: 1887
Reputation: 1224
You only need this
$(document).ready(function() {
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {
pid: pid,
user: user
},
success: function() {
alert("Item has been added to cart");
},
error: function(xhr) {
if (xhr.responseText == "already present")
alert("item is already present in cart");
else if (xhr.responseText == "error")
alert("item cannot be added , server error");
}
});
return false;
//e.preventDefault();
});});
No other event handlers required.
Upvotes: 1
Reputation: 7523
Simply use it after completing submit.It will off the click event.
$("#addtocart").off('click');
Upvotes: 0