Success message doesn't work [duplicate] - javascript

This question already has answers here:
Ajax call is never success
(2 answers)
Closed 5 years ago.
I have a little issue,
I'm working on a contact form,
My problem is that the ajax call doesn't show a success message, it sticks
on "sending"
the call is working because it goes to the PHP page and runs the function from there, so everything works fine expect the success message.
I will really glad for assistance, thanks!
this is the JavaScript page:
var nameRegx = /^[' a-zא-ת]+(\s[' a-zא-ת]+)*$/i,
emailRegx = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})$/,
phoneRegx = /^(?:0(?!(5|7))(?:2|3|4|8|9))(?:-?\d){7}$|^(0(?=5|7)(?:-?
\d){9})$/,
td = 'p.text-danger',
sa = '#submitAnimate',
sb = '#submitBtn',
nf = '#name',
ef = '#email',
pf = '#phone',
mf = '#message';
$(sa).hide();
$('#contactForm').on('submit', function (event) {
event.preventDefault();
var isValid = true;
$(td).text('');
$(' input[type="text"], textarea').removeClass('error');
$(sb).attr('disabled', true);
$(sa).show();
var userData = {
name: $(nf).val().trim(),
email: $(ef).val().trim(),
phone: $(pf).val().trim(),
message: $(mf).val().trim()
};
if (userData.name.length < 2 || userData.name.length > 70 ||
!nameRegx.test(userData.name)) {
isValid = false;
setError(nf, 'name');
}
if (!emailRegx.test(userData.email)) {
isValid = false;
setError(ef, 'email');
}
if (!phoneRegx.test(userData.phone)) {
isValid = false;
setError(pf, 'phone');
}
if (userData.message.length < 3) {
isValid = false;
setError(mf, 'message');
}
if (!isValid) {
$(sb).attr('disabled', false);
setTimeout(function(){ $(sa).hide(); }, 500);
} else {
$.ajax({
url: "assets/contact_form/process-contact.php",
type: "POST",
dataType: "html",
data: userData,
beforeSend: function () {
$( sb ).val('Sending...');
},
success: function (response) {
if (response == true) {
successmessage = 'Data was succesfully captured';
$("#gmsg").text(successmessage);//THIS MESSAGE DOESN'T APPEAR
} else {
$( sb ).val('Can not send, please try latter');
}
}
});
}
});
$('input[type="text"], textarea').on('keyup', function () {
$(this).next().text('');
});
function setError(target, field) {
setTimeout(function () {
$(target).val('').addClass('error');
$(target).next().text('* Please enter your ' + field);
}, 500);
}

In success : function(response) the object response is not a Boolean. it is the returned response of the ajax call, it will be a string.
just remove the if(response == true) from your code.
then, it will work fine.

Related

return when duplicate html table

I have a function that can remove the duplicate in my html table.
var seen = {};
$('#tblSerial tr').each(function() {
var txt = $(this).text();
txt = txt.trim();
if (seen[txt]) {
isExist = true;
alertify.error("This serial is already on contract.");
$(this).remove();
return; //this should return
} else
seen[txt] = true;
});
But the problem now is that, below that code there's an AJAX call which always call even I return in the duplicate error.
$.ajax({
type: "GET",
url: siteURL + '#Url.Action("valcontract", "contract")',
data: data_model,
success: function (response) {
if (response.success) {
} else {
$('#serial').val("");
alertify
.error(response.responseText);
return;
}
},
error: function (response) {
alertify
.error(response.responseText);
return;
}
});
I want to block the AJAX call if there's a duplicate in my serial table.

When submitting an ajax request, how can you "put the original request on hold" temporarily until a condition is met?

I am wanting to implement a recaptcha process that captures all ajax requests before they go through - the desired process would be as follows:
User completes an action which is going to cause an ajax request of some sort.
If the user has already completed the recaptcha process, the ajax request proceeds without further delay
If the user has not completed the recaptcha process, put the ajax request "on hold" temporarily until the recaptcha process is completed, then continue the ajax request.
I have got things to a state where I intercept the call, however I don't know how to put it on hold temporarily. Here's the relevant code:
<script>
var captchaValidated = null;
var currentRequests = [];
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.url != "/ValidateCaptcha") {
if (captchaValidated == null || captchaValidated == false) {
if (captchaValidated == null){
openRecaptcha();
} else {
verifyCaptcha(); //see async question in method
}
if (!captchaValidated) {
jqXHR.abort();
} else {
//let the original request proceed now - but how?!
}
}
}
});
function verifyCaptcha() {
var grecaptcha = $("g-recaptcha-response");
var encodedResponse;
if (grecaptcha != null) {
encodedResponse = grecaptcha.val();
$.ajax({
async: false, //set to false so that the calling method completes rather than async - what do you think?
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
//parse the data - did we get back true?
captchaValidated = data;
},
error: function (raw, textStatus, errorThrown) { captchaValidated = null; alert("Validate ReCaptcha Error: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": encodedResponse })
});
}
}
function invalidateCaptcha(){
captchaValidated = null;
}
function openRecaptcha() {
grecaptcha.render('recaptcha', {
'sitekey': "thekey",
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
$("#recaptchaModal").modal('show');
}
</script>
Any suggestions of how to proceed would be appreciated, thanks in advance!
Thank you #Loading and #guest271314 for your help in pointing me in the right direction that helped me get things figured out. I've pasted how I accomplished it below - perhaps it will be of help to someone else. Of course if anyone would like to weigh in on my implementation please do.
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCaptcha&render=explicit&hl=en" async defer></script>
<script>
var captchaValidated = null;
var currentRequests = [];
var captchaPrompted = false;
var captchaReady = false;
var resetCaptcha = false;
function onloadCaptcha() {
captchaReady = true;
captcha = grecaptcha.render('recaptcha', {
'sitekey': '<yoursitekey>',
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
}
var deferredCaptcha = null;
var promiseCaptcha = null;
var captcha = null;
function openRecaptcha() {
if (!captchaReady) {
setTimeout(openRecaptcha, 50);
}
if (captchaPrompted) {
return;
}
captchaPrompted = true;
var captchaTimer = setInterval(function () {
if (captchaValidated != null) {
if (captchaValidated) {
deferredCaptcha.resolve();
} else {
deferredCaptcha.reject();
captchaValidated = null;
}
}
}, 100);
if (resetCaptcha) {
captcha.reset();
}
deferredCaptcha = $.Deferred();
promiseCaptcha = deferredCaptcha.promise();
promiseCaptcha.done(function () {
//captcha was successful
clearInterval(captchaTimer);
//process the queue if there's items to go through
if (currentRequests.length > 0) {
for (var i = 0; i < currentRequests.length; i++) {
//re-request the item
$.ajax(currentRequests[i]);
}
}
});
promiseCaptcha.fail(function () {
//captcha failed
clearInterval(captchaTimer);
currentRequests = []; //clear the queue
});
$("#recaptchaModal").modal('show');
}
function verifyCaptcha() {
resetCaptcha = true;
var response = $("#g-recaptcha-response").val();
var encodedResponse;
// confirm its validity at the server end
$.ajax({
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
captchaValidated = data;
if (!data) {
captchaPrompted = false;
}
},
error: function (raw, textStatus, errorThrown) { captchaValidated = false; captchaPrompted = false; alert("WTF Validate ReCaptcha Error?!: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": response })
});
}
function invalidateCaptcha(){
deferredCaptcha.reject();
captchaValidated = null;
resetCaptcha = true;
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (settings.url == '/ValidateCaptcha' || captchaValidated) {
// we're validating the captcha server side now or it's already been validated - let it through
} else {
if (typeof settings.nested === 'undefined'){
settings.nested = true; //this flag is to determine whether it's already in the queue
currentRequests.push(settings); //add the request to the queue to be resubmitted
//prompt them with the captcha
openRecaptcha();
}
return false; // cancel this request
}
}
});
</script>
At $.ajaxPrefilter() use .then() chained to openCaptcha to call verifyCaptcha
if (captchaValidated == null){
openRecaptcha().then(verifyCaptcha);
}
at verifyCaptcha use .is() with parameter "*" to check if an element exists in document
if (grecaptcha.is("*")) {
at openRecaptcha(), if grecaptcha.render does not return asynchronous result return jQuery promise object using .promise(); else chain to grecaptcha.render and $("#recaptchaModal").modal('show'); using $.when()
return $("#recaptchaModal").modal('show').promise()
or
return $.when(grecaptcha.render(/* parameters */)
, $("#recaptchaModal").modal('show').promise())
Something like this? (pseudo-code)
verified = false;
$('#myButton').click(function(){
if (!verified) verify_by_captcha();
if (verified){
$.ajax(function(){
type: 'post',
url: 'path/to/ajax.php',
data: your_data
})
.done(function(recd){
//ajax completed, do what you need to do next
alert(recd);
});
}
});//end myButton.click

Weird behavior under chrome and $.ajax after chrome update

I've an asp.net mvc5 application that on a loginpage does the following Ajax call
$(document).ready(function () {
var formObj = $(".login-form");
$("form input[name=username]").val("user");
$("form input[name=password]").val("password1!");
formObj.submit(function (event) {
event.preventDefault();
console.log("test");
validator = formObj.validate();
if (validator.checkForm()) {
var form = formObj.get();
var rememberMe = $("input:checkbox[name=remember]:checked").val() ? true : false;
$(form.rememberMe).val(rememberMe);
args = {
form: form,
userName: $(form.username).val(),
password: $(form.password).val(),
remember: rememberMe
}
var url = #Url.Content("~/api/auth");
func = $.ajax({
url: url,
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
#if(Request.Params.Get("redirect") != null) {
<text>
window.location = "#Request.Params.Get("redirect")";
</text>
}
else
{
<text>
window.location = "#Url.Content("~/Home")";
</text>
}
}
}
});
}
});
});
If I put this piece of code
var url = #Url.Content("~/api/auth");
it works, otherwise if I quote the url string (as it should be correct)
var url = "#Url.Content("~/api/auth")";
it hangs the browser.
This only happens under chrome as first iussue was reported with Chrome Version 43.0.2357.65 m
What is wrong?
Thanks
UPDATE #1
I've noticed that the problem is there
$.ajax({
url: "/someurl",
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
window.location = "/someotherurl/";
}
}
});
If I sue ajax it breaks...if I use $.post or $.get it works...

javascript mutually exclusive CheckBox issue

I have a radio button that displays a list of records in a telerik grid. When the radio button is checked, it displays complete and incomplete records. However, the user wants a way of displaying only complete or incomplete records. I added two mutually exclusive checkboxes. The user can either check the complete or incomplete checkbox to display the data. It works fine on my local, but it does not work well on the server. The first time, the user has to click the checkbox two or three times before it can keeps the state. In addition, if complete is checked and the user checked incomplete next, the checkmark will go back to complete. The user has to do it a second times. What I am doing wrong here?
Here is the html for the checkbox
#Html.CheckBox("complete", SessionWrapper.currentEncounter.complete, new { id = "chkComplete", onclick = "chkInCompleteOption(1);this.form.submit();" }) <strong>Complete</strong>
#Html.CheckBox("Incomplete", SessionWrapper.currentEncounter.incomple, new { id = "chkInComplete", onclick = "chkInCompleteOption(2);this.form.submit();" }) <strong>Incomplete</strong>
//Here is the javascript
var completeCheck = '#SessionWrapper.currentEncounter.complete';
var inCompleteCheck = '#SessionWrapper.currentEncounter.incomplete';
function chkInCompleteOption(e) {
if (e == 1) {
var cc = $('#chkComplete').is(':checked');
var data = { "complete": cc, "inComplete": false };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testComplete();
return true;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
else if (e == 2) {
var inc = $('#chkInComplete').is(':checked')
var data = { "complete": false, "inComplete": inc };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testInComplete();
return true;
// $('#chkComplete').removeAttr("checked", "checked");
// $('#chkInComplete').attr("checked", "checked");
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
}
function testInComplete() {
if (inCompleteCheck == true) {
inCompleteCheck = $('#chkInComplete').attr("checked", "checked");
document.getElementById('chkInComplete').checked = true;
} else {
$('#chkInComplete').removeAttr("checked");
}
}
function testComplete() {
if (inCompleteCheck == true) {
completed = $('#chkComplete').attr("checked", "checked");
document.getElementById('chkComplete').checked == true;
} else {
$('#chkComplete').removeAttr("checked");
}
}
//Setting the mutually exclusive value on the server side
public bool CompletedOption(bool complete, bool inComplete)
if (inComplete == true && complete == true)
{
return false;
}
if (complete == true)
{
SessionWrapper.currentEncounter.complete = true;
}
else if (SessionWrapper.currentEncounter.complete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.complete = true;
}
else
{
SessionWrapper.currentEncounter.complete = false;
}
if (inComplete == true)
{
SessionWrapper.currentEncounter.incomplete = true;
}
else if (SessionWrapper.currentEncounter.incomplete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.incomplete = true;
}
else
{
SessionWrapper.currentEncounter.incomplete = false;
}
return true;
}
I found the issue. The server side was being updated properly; however, the ajax was returning an error message every time it executed. The method on the server side was returning a Boolean when a string was expected. I've also set async and cache to false. I ran the application again, and it works.
//Change Method Signature from boolean to string
public string CompletedOption(bool complete, bool inComplete)
{
return "true";
}
ajax post
$.ajax({
url: url,
type: 'post',
dataType: 'text',
async: false, //Added
cache: false, //Added
data: data,
success: function (data) {
return data;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});

Is there a way to prevent submitting a form with this javascript/jquery?

I have searched the net, i´ve tried implementing "preventdefaults" and "return false" statements all over the place, but I can´t seem to find a way to prevent this form submitting and reloading the page. It only reloads when the form has been validated. I´m kind of a beginner, but I really tried hard achieving the script to validate a form (which has "post"-method and "#" as action), and make an ajax-call. It´s a school assignment and would be graceful towards any pointers you guys could give.
$(document).ready(function()
{
$("#submit").click(function()
{
var gbname = $("#gbname")[0];
var gbmessage = $("#gbmessage")[0];
formFields = [gbname, gbmessage]
var warning = false;
for (i=0; i<formFields.length; i++)
{
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "")
{
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true)
{
alert("Vänligen fyll i fälten korrekt!");
return false;
}
else
{
$.post('ajax.php', {gbname: gbname, gbmessage: gbmessage},
function(data)
{
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" +gbname+ "</p> <p class='messages'><b>Meddelande:</b>" +gbmessage+ "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
});
return false;
}
return false;
});
});
Your references to the input elements as objects and the data returned from your AJAX call were a bit muddled.
Also incorporated the suggestion of binding to the form's submit event. DEMO
$(document).ready(function () {
function clearForm(){
$('input.reset').each(function(){
$(this).val('');
});
}
$("form").on('submit', function () {
alert('submitted!');
var gbname = $("#gbname");
var gbmessage = $("#gbmessage");
formFields = [gbname[0], gbmessage[0]]
var warning = false;
for (i = 0; i < formFields.length; i++) {
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "") {
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true) {
alert("Vänligen fyll i fälten korrekt!");
return false;
} else {
var J = JSON.stringify({
"gbname": gbname.val(),
"gbmessage": gbmessage.val()
});
console.log(J);
$.ajax({
type: "POST",
url: '/echo/json/',
datatype: 'json',
data: {
json: J,
delay: 3
},
success: function (data) {
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" + data.gbname + "</p> <p class='messages'><b>Meddelande:</b>" + data.gbmessage + "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
} // end success
}); // end ajax
return false;
} // end else
return false;
});
});
I suggest using
$("form").on('submit', function (e) {
[...]
if(validationErrors) {
alert(Errormessage);
e.preventDefault();
}
[...]
instead of returning false.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
In order to get it to work, you have to use the event as a parameter of your callback function.

Categories

Resources