Checking Recaptcha still sends a message if false - javascript

There was a problem connecting Google Recaptcha v2. Or rather with the form. The check works fine, the error message displays, but, the message is still sent.
How can I fix this?
This is a form of feedback:
$(document).ready(function() {
$("#fast-call_submit").bind("click", function(e) {
e.preventDefault();
var form = $('#feedback_form');
var fields = form.serialize();
$.ajax({
url: form.attr('action') + '.json',
type: 'post',
data: fields,
dataType: 'json',
complete: function() {},
success: function(response) {
var v = grecaptcha.getResponse();
if (v.length == 0) {
$('.w-form-re-fail').show();
return false;
} else {
if (response.status == 'ok') {
$('.w-form-done').show();
$('.w-form-fail').hide();
form.hide();
} else {
$('.w-form-fail').show();
}
$('.w-form-re-fail').hide();
return true;
}
}
});
});
});

Related

Load CHAT Messages not working as expected

This my code for send realtime message.
After send message, it is not display unless i refresh the page.
I want this chat box message to show the new message entered.
This is to show the user List In the left side of the page:
$(".user-w").click(function() {
var user_id = $(this).attr("id");
// alert(user_id);
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/getMessageByLists/')?>",
data: {
'user_id': user_id
},
datatype: 'html',
success: function(data) {
$("#loadMessages").html(data);
}
}); });
This is Send function:
$("#sendMessage").click(function(e)
{e.preventDefault();// alert("test");
var msg = $("#message_text").val();
var touser = $("#touser").val();
//var reservation_id = $("#reservation_id").val();
if (!msg || msg.length == 0) {
alert("enter a message");
} else {
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/addMessage')?>",
// data:{'msg' : msg, 'touser' : touser, 'reservation_id' : reservation_id},
data: {
'msg': msg,
'touser': touser
},
datatype: 'text',
// Page.Server.ScriptTimeout = 300;
success: function(data) {
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
} else {
alert("noo eroor chat message");
}
},
});
//return false;
} }); // End Send Function
if I am not wrong then, their might be an element with class as "user-w", also that element have "id" attribute too. So you can just execute following line, after sending the message to user.
$(".user-w[id='"+ touser +"']").trigger("click");
above line needs to placed in "success" method, like as below:
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
$(".user-w[id='"+ touser +"']").trigger("click");
} else {
alert("noo eroor chat message");
}

Cordova unable to post data to server using ajax

I am developing a Phonegap Cordova application and I want to POST data to server using AJAX but am not able to, am getting an error.
My example code is:
<script>
$(document).ready(function()
{
$('#frm').submit(function()
{
var username = $('#textinput').val();
var username = $.trim(username);
var password = $('#passwordinput').val();
var password = $.trim(password);
{
alert('Please enter username');
return false;
}
else if(password =='')
{
alert('Please enter password');
return false;
}
else
{
var user = $('[name=username]').val();
var pass = $('[name=password]').val();
$.ajax({
type: 'POST',
url: 'http://eqfree***p.com/log_sb.php',
rossDomain: true,
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data: { username:'user', password:'pass'},
dataType: 'json',
success: function(data){
alert(data.success);
alert('success');
},
error: function(){
alert('error!');
}
});
return false;
}
});
});
</script>
try this one
<script>
$(document).ready(function()
{
$('#frm').submit(function()
{
var username = $('#textinput').val();
var username = $.trim(username);
var password = $('#passwordinput').val();
var password = $.trim(password);
else if(username =='')//check condition
{
alert('Please enter username');
return false;
}
else if(password =='')
{
alert('Please enter password');
return false;
}
else
{
//no need to re initialize
//var user = $('[name=username]').val();
//var pass = $('[name=password]').val();
$.ajax({
type: 'POST',
url: 'http://eqfree***p.com/log_sb.php',
crossDomain: true,
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data: { 'username':username, 'password':password},
dataType: 'json',
success: function(data){
alert(data.success);
alert('success');
},
error: function(){
alert('error!');
}
});
return false;
}
});
});
</script>

Submit form after successful ajax call using jQuery in asp.net mvc 5

I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:
Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.
Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.
The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.
I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.
When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!
The Submit button is defined as follows:
<div class="form-group">
<div>
<input type="button" id="btnApply" value="Apply" class="btn btn-primary" />
</div>
</div>
My JavaScript code is defined as follows:
$('#AppllicationForm').submit(function () {
if (!$(this).attr('validated')) {
if ($(this).valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
$('#ApplicationForm').attr('validated', true);
$('#ApplicationForm').attr('action', '/ApplicationForm/Index')
.submit();
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
}
}
return false;
});
The above is using a regular button but I've also tried to define its type as Submit but to no avail.
I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!
The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values
I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.
I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.
Any help would be greatly appreciated.
Try it out :
$('#btnApply').click(function (e) {
alert('submit');
e.preventDefault();
var form = $('form'); // change selector your form
if (!form.attr('validated')) {
if (form.valid()) {
$.ajax({
type: "POST",
data: form.serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
console.log('response received.');
if (response != null && response.success) {
console.log('No validation errors detected.');
form.attr('validated', true);
form.attr('action', '/ApplicationForm/Index')
.submit();
} else if (response != null && !response.success) {
console.log('Validation errors detected.');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
},
error: function (response) {
console.log(response);
$('validationSummary').hide();
}
});
}
}
});
Please try it out:
$('#btnApply').on('click', function (e) {
e.preventDefault();
var form = $( "#AppllicationForm" );
if (!form.attr('validated')) {
if (form.valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
form.attr('validated', true);
form.submit();
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
}
}
return false;
});
Your form action attribute will be '/ApplicationForm/Index'. When you click on the button, you make the validation and if everything is OK, then submit the form.
Please check below solution :
$('#btnApply').on('click', function (event) {
if ($('form').valid()) {
event.preventDefault();
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
$('#ApplicationForm').attr('validated', true);
$('form').submit(); // Here form will be submmited to Index action.
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
});
And decorate your ValidateForm method with [HttpPost] attribute.
I thought I'd share my solution as I ended up hiring a freelancer to have a look at it as I was under time constraint and could not afford to spend any more time on this.
How did it fix it? He added a second ajax call from within the first one. The annoying (and costly!) part is that I did try this but I had one important missing line i.e. var formValidated = $('#AppllicationForm').serialize();.
After these changes were made, I just had to rejig some of my logic regarding which div should be displayed and/or hidden but bar that it was pretty standard stuff.
Here's the final code that worked as expected:
$('#AppllicationForm').submit(function () {
if ($(this).valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
if (response != null && response.success) {
var formValidated = $('#AppllicationForm').serialize();
$.ajax({
url: '/ApplicationForm/Index',
data: formValidated,
type: 'POST',
success: function (result) {
$('#mainDiv').hide();
$('#Congrats').show();
}
});
return true;
}
else if (response != null && !response.success) {
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
return false;
}
});
}
return false;
});
Hope this helps others.

Ajax call function on success return false not working

I am running an ajax request, then once I get the result back I choose if it should be continued or if the form should not submit. I am checking if the email exists.
Issue is I moved the return false out of the success: as it was not working there and now in a seperate function it is not working either. I get the alert("FALSE"); but the form still submits which is no good as I want an error pop up to happen.
$.ajax({
type: "POST",
url: "/ajax/checkdata.php",
data: "email="+email,
success: function(data){
var returned = true;
if (data == "Email Exists") {
returned = false;
} else {
}
emailModal(returned);
}
})
function emailModal(result){
if (result) {
alert("TRUE");
} else {
alert("FALSE");
return false;
}
}
You'd have to always prevent the form from submitting, and then in the check for the email figure out wether to show an error or submit the form using the native submit handler
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/ajax/checkdata.php",
data: {email : email},
context: this
}).done(function(data) {
if (data == "Email Exists") {
alert(data);
} else {
this.submit();
}
});
});

Jquery autocomplete and enter key pressed

I have a jQuery autocomplete which reads from a database.
Everything works well, but when I press enter I need to go the database and check if the entered text exists in the table so I can select it - else I will alert invalid input.
My Attempt
I implemented the source and select method and also implemented the onkeypress method of the textbox. I am getting the result I need but even after I press enter the autocomplete is still searching for the values from the database.
How do I stop this because it is slowing my page.
Code:
$("#<%=txtSearch_Doc.ClientID%>").autocomplete({
delay:1000,
source: function (request, response) {
var m_Subtype = $("#<%=hdn_Subtype_Doc.ClientID%>").val();
var m_ConSocStr = $("#<%=hdn_ConSocStr_Doc.ClientID%>").val();
var jsonObjects = { "prefixText": request.term, "m_Subtype": m_Subtype, "m_ConSocStr": m_ConSocStr };
var jsonString = JSON.stringify(jsonObjects);
$.ajax({
url: '<%=ResolveUrl("AutoCompleteForFile.asmx/AutoSelectDoc")%>',
data: jsonString,
dataType: "json",
delay: 0,
autoFocus: true,
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('|')[0],//show key
val: item.split('|')[1], //documentnumber
}
}))
}
,
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
},
failure: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
}
});
},
//begin select event
select: function (e, i) {
$("#<%=hdn_Number_Doc.ClientID%>").val(i.item.val);
$("#<%=txtSearch_Doc.ClientID%>").val(i.item.val.trim());
if (i.item.val == "") {
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
$("#<%=txtSearch_Doc.ClientID%>").val("");
}
return false;
},
//end select event
minLength: 1,
autoFocus: false //IF TRUE IT WILL SELECT THE FIRST ROW BY DEFAULT, IF FALSE IT WILL NOT SELECT THE FIRST ROW
})
//end autocomplete
//key press event to handle enter pressed added by chahid on 12-jan-2016
.keypress(function (e) {
$("#<%=hdn_key_pressed.ClientID%>").val(e.keyCode);
if (e.keyCode == 13) {
e.preventDefault();
var x = $("#<%=txtSearch_Doc.ClientID%>").val();
var m_Subtype = $("#<%=hdn_Subtype_Doc.ClientID%>").val();
var m_ConSocStr = $("#<%=hdn_ConSocStr_Doc.ClientID%>").val();
var jsonObjects = { "prefixText": x, "m_Subtype": m_Subtype, "m_ConSocStr": m_ConSocStr };
var jsonString = JSON.stringify(jsonObjects);
$("#<%=hdn_is_alert.ClientID%>").val("1");
$.ajax({
url: '<%=ResolveUrl("AutoCompleteForFile.asmx/CheckForDocExistance")%>',
data: jsonString,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (dat) {
var json = JSON.stringify(dat);
obj = JSON.parse(json);
if (obj.d == "2") { // if it is empty
$("#<%=txtSearch_Doc.ClientID%>").val("");
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
}
else {
if (obj.d.split('|')[0] == "1") {
$("#<%=txtSearch_Doc.ClientID%>").val(obj.d.split('|')[1].trim());
$("#<%=hdn_Number_Doc.ClientID%>").val(obj.d.split('|')[1]);
return false;
} else {
alert("Invalid input");
$("#<%=txtSearch_Doc.ClientID%>").val("");
$("#<%=txtSearch_Doc.ClientID%>").focus();
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
}
}
},
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
},
failure: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
}
});
$("#<%=txtSearch_Doc.ClientID%>").autocomplete('close');
}
})
OK I manage to found a solution : I added the search event to the autocomplete where I am checking the keypresscode and returning false when it is the enter key:
search: function (event, ui) {
var key = $("#<%=hdn_key_pressed.ClientID%>").val();
if (key == 13)
return false;
else
return true;
},

Categories