alert() box is coming up multiple times in jquery - javascript

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

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.

Simply use it after completing submit.It will off the click event.
$("#addtocart").off('click');

Related

jQuery prevent submit of form inside of if statement

Sorry if there are some mistakes, but I am a total noob and I am also posting for the first time on StackOverflow.
I am trying to configure a submit form, that controls if the inserted PIN is right, and if so goes on with the submission. I did some online research and found out that with jQuery we can use to function event.preventDefault(), I tried to insert it inside my AJAX request but it looks like it doesn't stop the form from being saved.
The code looks like these:
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp" : otp,
"PIN" : PIN,
"action" : "verify_otp"
};
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
error : function(event) { event.preventDefault(); };
}
//if I insert "return false;" here the submit is always blocked
}
I checked on atom if the parenthesis are right and it looks like it is.
Any ideas how I should use the preventDefault()?
I also checked if the output of m_ajaxpinr.php is correct, and it is. I also tried like these but it still didn't work...
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
$("form").submit(function(event) {
if (response.type == 'success')
{
alert(response.type);
}
else if (response.type == 'error')
{
alert(response.type);
event.preventDefault();
}
});
as said in comment above ajax call is asynchronous, you need to complete cancel default action for the form or put event.preventDefault(); on the top function, then submit it in success function if it valid otp.
.val() will not return null, it return empty if no input.
$('#myForm').on('submit', verifyOTP);
function verifyOTP(e) {
e.preventDefault(); // note this
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp": otp,
"PIN": PIN,
"action": "verify_otp"
};
if (otp) { // mean not null, undefined, empty, false, 0
$.ajax({
//url: 'm_ajaxpinr.php',
url: 'https://httpbin.org/anything/test',
type: 'GET',
dataType: "json",
data: input,
success: function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
if(response.args.otp == 1234){
console.log('valid otp, continue submission')
$('#myForm').off('submit'); // remove submit event
$('#myForm').submit(); // then submit the form
}
else{
console.log('invalid pin,\nvalid pin: 1234');
}
},
error: function() {
console.log("server error, submission cancelled");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
console.log("otp maybe empty, submission cancelled");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input id="contomovimentato">
<button>submit</button>
</form>

select child at beginning of function jquery

I can't appear to select the child form of a div I have for some reason.
For the matter, I am trying to find a way that I can have a function select the child form of a div since I have it changing for a toggling function at my site.
$(document).ready(function(){
$("#soundToggle, #soundOffForm").submit(function(event){
/*var r = new XMLHttpRequest();
r.open("POST", "sessionsetter.php", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
r.send("a=1&b=2&c=3");*/
alert("post");
event.preventDefault();
$.ajax({
type: "POST",
url: "sessionsetter.php",
data: {
sound : '0',
},
success: function(data) {
//alert("Sound toggled successfully: " + data);
$('#soundToggle').load(location.href + " #soundOnForm");
},
error: function(data) {
alert("Error in processing request: " + data);
}
});
});
$("#soundToggle, #soundOnForm").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "sessionsetter.php",
data: {
sound : '1',
},
success: function(data) {
//alert("Sound toggled successfully: " + data);
$('#soundToggle').load(location.href + " #soundOffForm");
},
error: function(data) {
alert("Error in processing request: " + data);
}
});
});
});
Anyone have any suggestions on how I can make this a possibility? Thanks. When I don't select the child of a form, the handler is destroyed as I replace the form in my DOM.
The jquery binding will be lost if the Dom is reconstructed after page loads, you may want to use this:
Assumption here is #soundToggle is the div that contains form
$("#soundToggle, #soundToggle form").submit(function(event){
if($("#soundToggle form").attr('id') == "soundOnForm"){
//do on functionality
} else if($("#soundToggle form").attr('id') == "soundOffForm"){
//do off functionality
}
}

How to get error response in Ajax?

I am trying to add data to a cart(using) Ajax jQuery, now I have added a primary key constraint and I want when the constraint is violated in get the error message in jQuery:
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()
{
alert("Item already present in the cart");
}
});
return false;
});
});
}
The error function never runs, the functionality in the DB is running fine but I don't see the error message in Ajax.
Here is Java code:
public int addintocart(String user,int pid)
{
try
{
conn = obj.connect();
String sql="insert into cart(userid,product_id,quantity) values(?,?,?)";
ps1 = conn.prepareStatement(sql);
ps1.setString(1,user);
ps1.setInt(2,pid);
ps1.setInt(3,1);
ps1.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception k)
{
k.printStackTrace();
}
return x;
}
What is going wrong?
You have to send the error back as a servlet response from Java. Here is an example: How to return Java Exception info to jQuery.ajax REST call?
Also, you are missing some parameters in the ajax error function. It might be another problem. Check out http://api.jquery.com/jquery.ajax/ You should evaluate the error and present the appropriate message.
That error code wwill never work. the onerror event of AJAX only runs when connection cannot be established or URL does not exist. You have to return something from your the server indicating success or faliure.
I would do it this way.
PHP(convert this code to JAVA):
if(success){
die(1);
} else {
if(notyetincart){
die(0);
} else {
die(2);
}
}
Then Jquery coded:
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(response)
{
if(reponse==="1")
alert("Item has been added to cart");
else if(reponse==="0")
alert("Item could not be added to cart");
else alert("Item already present in the cart");
},
error:
function()
{
alert("Item could not be added to cart due to poor network connection");
}
});
return false;
});
});
}
Hope this helps

Only send post/get if form values has changed

I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...

jQuery appends # at the end of url even if I return false;

I have this code which I plastered with return false; so that it wouldn't append the # at the end of a url after it executes, but it still does that. Any idea what I am doing wrong and how/where is best to return false?
// Called right away after someone clicks on the vote up link
$('.vote_up').mouseup(function()
{
$("#loading").show();
var problem_id = $(this).attr("data-problem_id");
vote(problem_id , 1);
//Return false to prevent page navigation
return false;
});
$('.vote_down').mouseup(function()
{
$("#loading").show();
problem_id = $(this).attr("data-problem_id");
vote ( problem_id , -1 );
//Return false to prevent page navigation
return false;
});
// Global function
var vote = function(problem_id , vote)
{
var dataString = 'problem_id=' + problem_id + '&vote=' + vote;
// The person is actually logged in so lets have him vote
$.ajax({
type: "POST",
url: "/auth/check_login.php",
dataType: "json",
success: function(data)
{
$.ajax({
type: "POST",
url: "/problems/vote.php",
data: dataString,
success: function(html)
{
$("#loading").hide();
if ( html == "not_logged_in" )
{
queue.login = false;
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$("#loginpopup").dialog( {title: 'Please Login To Vote'} ); // title: 'Login Dialog'
// prevent the default action, e.g., following a link
return false;
}
else
if ( html == "already_voted" )
{
// Display a dialog box saying that the user already voted
$('<div>You already voted this way on this problem.</div>').dialog( {title: 'Already Voted'});
// show div which says un-important, hide div which says important
$("#support").hide();
$("#dont_support").show();
return false;
}
else
if ( html == "error_getting_vote" )
{
$('<div />').html('Error getting existing votes.').dialog();
}
else
{
if ( vote == -1 )
{
$("#support").show();
$("#dont_support").hide();
}
else
{
$("#support").hide();
$("#dont_support").show();
}
// Now make a call to AJAX to get the count of votes
$.ajax({
type: "POST",
url: "/problems/get_vote_count.php",
data: dataString,
success: function(html)
{
var class_name = ".votes_"+problem_id;
$(class_name).text(html);
return false;
}
});
return false;
}
},
error: function(html)
{
$("#loading").hide();
return false;
} // End of error case
}); // Closing inner AJAX call.
},
error: function(data)
{
$("#loading").hide();
$("#loginpopup").dialog( {title: 'Please Login To Vote'} );
return false;
} // End of error
}); // End of outer AJAX.
return false;
};
You should bind the event listener to the click event instead of mouseup. When mouseup is triggered, the default behaviour has already occurred, and cannot be cancelled any more.
$('.vote_down').click(function(e) {
e.preventDefault();
// Rest of code
PS. Judging by your code, you've got separate pages to vote:
AJAX request - Is logged in?
AJAX request - Vote
This model is very insecure, if the voting page does not contain some kind of authentication. Users can easily bypass the login page by creating an artificial request to the voting page.
You should merge the login, and voting page.
Change your link syntax from <a href="#"> to <a href="javascript:void(0);" /> without changing your js code.

Categories