I am getting the invisible recaptcha done, but I am having a problem implementing it, the code in the developers page in google show it should be like this
<button
class="g-recaptcha"
data-sitekey="6Lee9CEUAA....."
data-callback="YourOnSubmitFn">
Submit
</button>
But the button on my page is currently includes knockout js data binding which I use to call the login function which sends the ajax call to the back end, but if I use the googles given code, I am not sure how to call the functions in my knockout js file.
Here is the old codes.
<button type="submit" class="btn btnlogin" data-bind="disable: (loggedIn() == 'true'), click: callLoginFunction">
SIGN IN
</button>
And here is the knockout js function.
self.callLoginFunction= function () {
self.getRecaptchaCode();
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/login/loginUsingAjax/' + auth,
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({
email : self.eMail(),
password : self.passWord(),
recaptcha : self.recaptchaCode()
})
})
.done(function(returnmsg) {
return window.location.href = BASEURL + 'index.php/main/index';
})
.fail(function(jqXHR, textStatus, errorThrown) {
self.loggedIn('failed');
grecaptcha.reset();
})
.always(function(data){
self.passWord(null);
});
};
So I would like to know how can I call this function using the new codes given by google, I tried removing data-callback and adding data-bind but dint work so need help.
The comment by Jose Luis was headed down the right path! And George Dimitriadis was thinking the right way, if you combine what they suggest you have a solution.
By following that link you learn that you can easily set up a jquery function to call a knockout function. Then you could set your button up to send that Jquery function as the callback function, which will just call your knockout function, which will send the grecaptcha response as part of its ajax request.
So in your head tag perhaps create a jquery function like this:
<script>
function loginCB() {
yourViewModel.callLoginFunction();
}
</script>
yourViewModel would be what you named your instance of your view model, for example:
<script>
yourViewModel = new login_vm();
ko.applyBindings(yourViewModel, $("#login")[0]);
</script>
Now create your button like google suggests sending that new Jquery function as the callback function:
<button
class="g-recaptcha"
data-sitekey="6Lee9CEUAA....."
data-callback="loginCB">
Submit
</button>
I had success getting the recaptcha response code by using grecaptcha.getResponse(), so I would alter your knockout callLoginFunction like this:
self.callLoginFunction= function () {
response = grecaptcha.getResponse()
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/login/loginUsingAjax/' + auth,
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({
email : self.eMail(),
password : self.passWord(),
recaptcha : response
})
})
.done(function(returnmsg) {
return window.location.href = BASEURL + 'index.php/main/index';
})
.fail(function(jqXHR, textStatus, errorThrown) {
self.loggedIn('failed');
grecaptcha.reset();
})
.always(function(data){
self.passWord(null);
});
};
The way you were getting the response code to send with your ajax request might have been fine, I just couldn't see how you did it.
I assume you were asking how to set up the client side of the recaptcha, so I will assume you know what to do with that response code you are sending with your ajax request on your server.
Related
I have 2 html files belong to two different controllers
This is belong to Index action of SignupController
Index.html
<div class="signup-small-font pull-right">Forgot password?</div>
When click at this link , it will go to that url and make a request to get the view of the ResetPassword Action of AccountController and get the resetPAssword.html
Now what i want is before making that request , i need to append a custom header in the request for the server side .
I was using ajax javascript :
function appendHeader(urlCulture){
$.ajax({
type: 'GET',
url: urlCulture,
headers: {
"Culture": 'zh'
},
})
}
What should i do in the index.html anchor link to call this function before requesting for the resetPassword.html
Like what I want is when I click at it , it will navigate to Account/Resetpassword and use the response getting from javascript file to render instead of a normal response
In your html file
<div class="signup-small-font pull-right"><a onclick="appendHeader(urlCulture)" href="#">Forgot password?</a></div>
In your js
function appendHeader(urlCulture){
$.ajax({
type: 'GET',
url: urlCulture,
headers: {
"Culture": 'zh'
},
success: function(res) {
window.location = 'Account/ResetPassword';
}
})
}
Give it a try. Im not quite sure if this is what you want to do.
you are using routes, you need to get the url from the javascript function
there is an example of that here:
Get local href value from anchor (a) tag
you could make something similar:
<div class="signup-small-font pull-right"><a onclick="return appendCustomHeader(this);" href="/Account/ResetPassword">Forgot password?</a></div>
in your js function like the previous reply you could make something like this:
function appendCustomHeader(element){
var url = element.href; // to get full url
$.ajax({
type: 'GET',
url: url,
headers: {
"CustomHeader": 'YourCustomHeader'
},
success: function(res) {
// here you make anything else with your response
}
})
return false;
}
I've not tested it, I hope it works for you.
it seems you can disable href redirecttion returning false,
see this:
How can I disable HREF if onclick is executed?
Let's say I make a Dictionary app, where I check if some word exists or not. I have a text input and a button:
<input type="text" id="word">
<input type="button" id="button">
I'd like the server to respond with either 1 (valid word) or 0 (invalid word).
In my jQuery script, I send an AJAX request:
$("#button").click(function () {
$.ajax({
url: "check.php?word=" + $("#word").val(),
method: 'GET',
success: function (isValid, textStatus, xhr) {
// Can I read the URL from the xhr to know which word was the request for?
}
});
});
The problem is, when the response comes back, I no longer know which word is it for. I know I could attach the word to the server's response, but I'm very curious if it can be done other way.
I'm pretty sure I can just attach this piece of information to the raw XHR and then read it in success callback, but my question is: does XHR in success callback contain infromation about request's URL and data?
You can modify the jQuery xhr object in beforeSend with anything you want then access it in success or then() or done() callbacks
$.ajax({
url: 'http://httpbin.org/get',
data:{foo:'bar'},
beforeSend:function(jQxhr){
jQxhr.something='another thing';
},
success:function(res,statusText,jQxhr){
console.log('"Something" in success() ', jQxhr.something)
}
}).then(function(res,statusText,jQxhr){
console.log('"Something" in then() ', jQxhr.something)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is what I would do:
$("#button").click(function () {
var word = $("#word").val();
$.ajax({
url: "check.php?word=" + word,
method: 'GET',
success: function (data) {
alert(word);
}
});
});
EDIT: Removed from Robo Robok comment, in which he is correct.
Im trying to submit a form like this way:
<form id="myForm" action="http://example.com/somefile" method="POST">
...
...
...
<input type="submit" id="sendForm" value="send">
</form>
the action link its a webservice developed by another developer, so, when i submit the form, the webservice replies me with an URL (http://www.example.com/thanks), what i wanna do is to avoid this webservice reply, and in place, change the url of the redirect, is this possible?
Ive tried too do it with:
<script>
$("#sendForm").click(function () {
if (form_check_validation()) {
$("#myForm").submit();
window.location.replace("http://stackoverflow.com");
} else {
return false;
// event.preventDefault();
}
});
</script>
But its not working.
Thanks
NOTE: The webservice is in another server, so im having issues with cross-domain origin.
https://api.jquery.com/event.preventdefault/ Google is your friend, bud...........
Assuming this service allows cross origin and you don't want / need to move to a different page, why not use ajax?
You can simply create and ajax call using $.ajax.
see http://api.jquery.com/jquery.ajax/
Example:
$.ajax({
url : "POST_URL",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
// Handle server response
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle error
}
});
You can do it with Ajax. I also recommend that you bind a submit event listener to the form so that the submission works correctly also when pressing Enter.
$("#myForm").submit(function (event) {
if (form_check_validation()) {
form_submit(this);
} else {
// ...
}
event.preventDefault();
});
function form_submit (form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize()
});
}
That's my script on my view.
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
data: {i: 100036},
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
</script>
That's my action on my controller.
public JsonResult VerificarPatrocinador(int i)
{
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var consulta = db.Tabela_Participante.Where(p => p.ID_Participante == i);
return Json(consulta.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
I'm a newbie in Ajax/Jquery, when I exclude the parameter it is ok, however, when I try to put the data: {i: 100036} in my script and the parameter in my action. It doesn't work. Why is it happening?
The controller is going fine. The parameter even passes, but I can't return this result in my View.
Thank you.
use [HttpPost] attribute on your controller method
[HttpPost]
public JsonResult VerificarPatrocinador(int i)
{
//Write Your Code
}
and change the ajax type attribute from "GET" to "POST" and use JSON.stringify. Also check the url carefully. your ajax should look like this
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: JSON.stringify({i: 100036}),
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
Hope it will help you
I think that #StephenMuecke may be on to something, because I was able to reproduce the (intended) logic with a new project.
The first thing to determine is where the code is going wrong: the server or the client.
Try using the Visual Studio debugger, and placing a breakpoint in VerificarPatrocinador. Then run the client code to see if the breakpoint is hit. When this succeeds, this means the problem is on the client end.
From there use the web browser's debugger in order to determine what is happening. Use the .fail function on the return result from .ajax in order to determine if there was a failure in the HTTP call. Here is some sample code that you can use to analyze the failure:
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
For more information check out http://api.jquery.com/jquery.ajax/
Change following code when ajax success
$.each(data, function (index, item) {
$("#NomePatr").val(item.Nome);
});
because when you are getting data as object of array, array or collection you can iterate using this syntax and then you can pass to var,dom...and so on where you want to display or take.
jQuery.each() means $(selector).each() you can use for dom element like below syntax: for example
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$("li").each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
Using GET is working fine but if it is not secure because data is visible to user when it submit as query string.
while post have
Key points about data submitted using HttpPost
POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users
so I hope you understand and change ajax type:'GET' to 'POST' if you want.
$.each() and $(selector).each()
Change this line
url: 'Ficha/VerificarPatrocinador'
to:
url: '/Ficha/VerificarPatrocinador'
Because when you use this url "Ficha/VerificarPatrocinador", it will call the API from url: current url + Ficha/VerificarPatrocinador,so it isn't correct url.
I'm relatively new to web app development, javascript and MVC so please bear with me.
I want to use the Jquery.Ajax command to post my Model to my controller.
My View:
#model MVC_Interface_May21.Models.DataValuesViewModel
...
<form method="post" id="testForm">
<input type="submit" class="subButton" value="Add New.." />
</form>
...
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
$(document).ready(function () {
$('#testForm').submit(function (e) {
e.preventDefault();
#{var val = Json.Encode(Model);}
var check = '#Html.Raw(val)';
$.ajax({
url: 'Results/AddNew',
type: 'POST',
//data: JSON.stringify(check),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
}
...
</script>
I haven't included the code for my Model or Controller because I don't believe they are a part of the problem. Currently, my code simply posts back to the same page. As far as I can tell the ajax command is not being executed. The debugger doesn't help me in tracing the behavior, and I am assuming that the form is simply doing it's post submit and ignoring my function.
Any help is much appreciated, and I'm sorry if this has been answered in the past. I developed my code by looking at other solutions, but I can't identify what's making mine dysfunctional.
You have to read more about it MVC, im not even sure what you are trying to do serializing the Razor Model like that, but that is what you are getting from the server, not your HTML Form with whatever the user input is.
You can use this js function to submit a form with Ajax.
$(function () {
$('#myForm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
And use the Create Form and imput helpers/
#Html.BeginFor
#Html.EditorFor