Google Recaptcha Ajax response strange checking order - javascript

I am making my registration page for my service. I need to check either Google's Recaptcha successfully verified or not. I decided to use an jquery.ajax.
I have created a function "checkCaptcha()" which sets isCAPT (if captcha valid or not) either true (FLD_VALID) or not (FLD_EMPTY):
function checkCaptcha() {
alert("1");
var captcha_response_text = grecaptcha.getResponse();
var request = $.ajax({
url: "ajax/registrationA.php",
type: "post",
data: { captcha: true, captcha_response: captcha_response_text }
});
request.done(function (response, textStatus, jqXHR) {
alert("2");
if(response) {
isCAPT = FLD_VALID;
}
else {
isCAPT = FLD_EMPTY;
}
});
}
I have to say that "registrationA.php" works fine. No problems there.
After this function, I am checking my submit button handling "onclick" event:
apply_button.onclick = function () {
checkCaptcha();
alert("3");
//alert("Капча " + isCAPT + " Логин " + isLOGIN + " Почта " + isMAIL + " Пароль " + isPASS + " Соответствие " + isPAS2);
return false;
};
You can see three "alert(...)" operators. The problem is that when I press submit button (apply_button) I get three alerts: 1, 3, 2. How can I fix this problem. I need to wait until "requiest.done" executes and only than go to "alert("3")". It is essential because now this function checks fields before checking captcha state which leads to an error because in this case isCAPT equals false.
Please help me with this problem. Maybe there is a better way to check if captcha verified or not (maybe there is a function like "grecaptcha.isVerified").

You need to check deferred.promise() method to work with asynchronous data. Check JQ documentation for that. In a few words it does exactly what you need. It allows to wait until the 2nd asynchronous request is finished and starts the 3d function.

Related

when to use callbacks in ajax calls

why use the first method and the call to it. (call back functions). and why not use the last one? http://pastebin.ca/2683261
one method is using success: success line 8 . and the caller of that method actually puts up the method on success (line 16)
someone told me that the last method wont do anything since the reply from server (success/failure) would come later. and I need to use the callbacks like the first method
*I did remember that I got an issue with traditional one. I just cant remember what it was. I think some thing that I didnt got the response when it was intended to. Some one told me that you wont get the response right away as its async. you need call backs. he was correct. But I dont remember the use case
*
with success:success (callback at method call)
function ajaxEditBox(box, boxType, boxTitle, boxDescription, success, error){
var boxId = box.attr('id').split("-")[1];
alert("box id to be sent to edit by ajax call: "+boxId +" type:"+boxType+" title:"+boxTitle+" desc"+boxDescription);
$.ajax({
url: "${pageContext.request.contextPath}/box/edit/"+boxId+"/"+boxType+"/"+boxTitle+"/"+boxDescription,
cache: false,
success: success,
error: error
});
}
callback at method call
ajaxEditBox(window.box, boxType, boxTitle, boxDescription, function(){
alert("boo");
$(window.box).removeClass("box-vertical");
$(window.box).removeClass("box-horizontal");
$(window.box).addClass("box-"+boxType);
$(window.box).find(".box-title-text").first().html(boxTitle);
//description change/edit is pending.
},
function(){
alert("ooh");
});
traditional ajax
function ajaxCreateBox(parent){
$.ajax({
url: "${pageContext.request.contextPath}/box/create/"+parentType+"/"+parentId+"/"+boxType+"/"+boxTitle+"/"+boxDescription,
cache: false,
//data:'firstName=' + $("#firstName").val() + "&lastName=" + $("#lastName").val() + "&email=" + $("#email").val(),
success: function(response){
$('#result').html(fetchedBoxId+" "+fetchedBoxType+" "+fetchedBoxTitle+" "+fetchedBoxDescription);
// createBoxInDom();
$("#"+parentElementId+" > ."+parentType+"-body").append(
'<div id="boxid-'+fetchedBoxId+'" class="box box-'+fetchedBoxType+'" >'+
' <div class="box-title" title="'+fetchedBoxDescription+'">'+
...
..
..
..
some logic
...
..
' <div class="box-body">'+
' </div> '+
'</div>');
},
error: function(){
alert('Error while request..');
}

Ajax post working but not callback message in Android browser

im implementing sign up with ajax on my site its working perfectly on desktop but causing problem in Android Browser The problem is after i click on signup button in android browser it post data to database but do not replace the html message.And alert native code error.
function postdata(){
var chkfrm = checkdata();
if(chkfrm == 0){
var url = '<?php echo base_url();?>index.php/Signup/signin';
$.ajax({
type: "POST",
url: url,
data: $("#formI").serialize(), // serializes the form's elements.
beforeSend:function(){
$("#signupdiv").html('<h1>Loadinng...........</h1>');
},
success:function(data)
{
$("#signupdiv").html(data);
},
error:function () {
alert(console.log);
}
});
e.preventDefault();
}
else {
$("#msgjava").html('<p>We need a little bit information from you.Please fill it.</p>');
return false;
}
You can't do e.preventDefault(); where you are because e is not passed into this function (thus it is undefined). This will cause an error and stop JS execution.
In what you posted, you are also missing a closing brace at the end of the postdata() function.
Your alert says "native code" because that's what this line of code:
alert(console.log)
will do. console.log is a native function so alerting a native function won't do anything useful. You need to make that alert a lot more useful. To see in more detail what error is coming back from the ajax function, change your error handler to something like this:
error: function(jqXHR, textStatus, errorThrown) {
alert("status = " + textStatus + ", errorThrown = " + errorThrown);
}
And, then see what it says.

Show popup/alert if account has related entity records

I have created a custom entity called Alert. I have associated this with the out of the box Account entity.
What I want to do now is to customise the Account form so that when a user opens it, it checks if the current account has any active alerts. If it does, it should show a message informing them of this (a javascript alert?) and then navigate to the alerts view for the account.
I've done some basic javascript in CRM but I'm not sure how to query related entities.
Note Active alert is defined by the Display From and Display Until dates in the Alert being active dates (Display From <= Today AND Display Until >= Today).
Update
Thanks for pointing me in the direction of oData. I now have the following function which is looking up the account set but expanding the relationship with the alerts. I'm trying to figure out how to check if there are any alerts, currently my code always triggers the javascript alert.
function CheckForAlerts(accountId)
{
var odataSelect = "http://mscrmdev/Test/xrmservices/2011/OrganizationData.svc/AccountSet?$expand=new_account_new_alert_Account&$filter=AccountNumber eq '" + accountId + "'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest)
{
// Use only one of these two methods
// Use for a selection that may return multiple entities
ProcessReturnedEntities(data.d.results);
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
});
}
function ProcessReturnedEntities(ManyEntities)
{
var oneEntity = ManyEntities[0];
if (oneEntity != null)
{
alert('There are active alerts associated with this account.');
}
}
The best way to do this will be via an oData query from the javascript. The CRM 2011 SDK comes with some helper functions for oData calls like this. You will want to use the 'retrieveMultiple' method which will allow you to retrieve all 'alerts' with a lookup to the 'account' in question.
First add the 'RESTJQueryEditor.js' file from the SDK to your form and then you can add your own custom script to perform the retrieve. I then suggest creating the message which you wish to show the user in the callback success function, something like the following:-
retrieveMultiple('nameOfYourAlertEntitySet', '?$filter=myAccountLookupName eq ' + accountId, function(alerts){
if(alerts.length > 0)
{
var message = '';
for(var index = 0; index<alerts.length; index++)
{
message += 'alert: ' + alerts[index].name;
}
alert('Found associated alerts: ' + message);
}
else
{
alert('No associated alerts found for this account');
}
},
function(){
// Log an exception
});
You will want to make the alert message a little nicer of course and adjust your attribute names accordingly, but this is the flavour of what you want to do I believe. Additionally, you can add any further criteria on the alert entity in the filter by use of the 'and' keyword.
Let me know if you have any issues.

Post Forms Using Javascript URL

I'm trying to submit a form to a website not my own (salesforce.com with their web-to-lead function) and I'm doing it through a javascript modal window.
Basically once all the entries are tested and made sure there are no errors, I use this:
if(error_count == 0) {
$.ajax({
type: "POST",
url: "[salesforce url]",
data: "first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&firm=" + firm + "&[salesforceid]=" + AUM + "&[salesforceid]=" + custodian + "&[salesforceid]=" + custodian_other,
error: function() {
$('.error').hide();
$('#sendError').slideDown('slow');
},
success: function () {
$('.error').hide();
$('.success').slideDown('slow');
$('form#callToAction').fadeOut('slow');
}
});
}
If tested the form without using javascript and the url works, so I'm thinking maybe the way javascript handles the url is the issue?
The issue: the data is not getting successfully submitted to Salesforce. Again, regular HTML form works, javascript doesn't. So I've identified it as a javascript issue.
You cannot make a XHR cross domain request unless the receiving server has allowed it and the browser supports CORS. You can however do a blind submit like this which will assume success:
var $form = $("<form>", {
method: "POST",
action: "[salesforce url]",
target: "my-iframe"
}).appendTo("body");
var $iframe = $("<iframe>", {
name: "my-iframe"
}).bind( "load", function () {
$('.error').hide();
$('.success').slideDown('slow');
$('form#callToAction').fadeOut('slow');
$iframe.remove();
$form.remove();
}).appendTo("body");
$.each(("first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&firm=" + firm + "&[salesforceid]=" + AUM + "&[salesforceid]=" + custodian + "&[salesforceid]=" + custodian_other).split("&")), function (index, value) {
var pair = value.split("=");
$form.append("<input>", {
type: "hidden",
name: pair[0],
value: pair[1]
});
});
$form.submit();
+1 for Jim Jose. This sort of thing could be interpreted as an XSS attack against the user, so most likely the browser will not allow it.
You could check out your browser's error logs, see if there's any security errors when you try to run your script. If that doesn't do anything, try to install a tool like Firebug and see if it can pinpoint the problem.
You could also improve your error handling by trying a different sort of method signature for the error function, like this:
error: function(jqXHR, textStatus, errorThrown) {...}
This way you can check what sort of error is being thrown from the Ajax call.

call another ajax function recursively from ajax success

I have a web page that is used to request the reports. When the user clicks a button, I am calling a function that will make a ajax request to process the reports. Once the request is made, I am using setInterval function to check the status of the report (whether is completed or not) every 1 second. Some how, the function inside setInterval() is not called at all.
Following is the javascript code that I have
var GLFiles_JSObject = {
url: "<%= Request.ApplicationPath %>/AjaxRequest.aspx",
apppath: '<%= Request.ApplicationPath %>',
btnRefreshId: '<%= btnRefresh.ClientID %>',
ajaxFunctionName: 'GLBuilder_ReprocessFiles',
reportstatusFuncName: 'GLBuilder_GetReportStatus',
reportid: 0,
ajaxError: function(XMLHttpRequest, textStatus, errorThrown){
alert(XMLHttpRequest.statusText);
},
ajaxSuccess: function(msg) {
if (msg === '') {
setInterval(function(){
this.reportstatus();
}, 1000);
}
},
reportstatusSuccess : function(msg) {
if (msg === '1') {
clearInterval();
}
},
reportstatus : function() {
var keys = new Array('reportid');
var values = new Array(reportid);
//ajax call
WebServicePost(true, this.url, this.reportstatusFuncName, keys, values, this.ajaxError, this.reportstatusSuccess);
}
};
//this will be called when button is clicked.
function reprocessGLFiles(reportid, btnid) {
//disable the button
//$('#' + btnid).attr("disabled", true);
GLFiles_JSObject.reportid = reportid;
var keys = new Array('reportid');
var values = new Array(GLFiles_JSObject.reportid);
// make an ajax request to process the files
WebServicePost(true, GLFiles_JSObject.url, GLFiles_JSObject.ajaxFunctionName, keys, values, GLFiles_JSObject.ajaxError, GLFiles_JSObject.ajaxSuccess);
return false;
}
The reason it is not being called is probably because you using the this var which means something else. If you change this.reportstatus(); to GLFiles_JSObject.reportstatus() will probably fix your problem.
On a different note, I think you are misunderstanding something here. Why do you need to call a timer method for this to check status. OnSuccess is called when the method the ajax request is finished. So you don't need to call setTimeout.

Categories