When I use this code, I only manage to retrieve recaptcha_response_field. If I remove recaptcha_response_field, I retrieve recaptcha_challenge_field. However, I am unable to retrieve the two at the same time.
I only managed to send 1 data.
challengeField = $("#recaptcha_challenge_field").val();
responseField = $("#recaptcha_response_field").val();
var html = $.ajax(
{
global: false,
type: "POST",
async: false,
dataType: "html",
data: "recaptcha_response_field=" + responseField + "&recaptcha_challenge_field=" + challengeField,
url: "../ajax.recaptcha.php"
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
you wrote this line data: "recaptcha_response_field=" + responseField + "&recaptcha_challenge_field=" + challengeField, was wrong.
you can try this:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
or
data: {recaptcha_response_field : responseField , recaptcha_challenge_field :challengeField
thanks,
Chintu
Try
data: {
recaptcha_response_field: responseField,
recaptcha_challenge_field: challengeField
}
??
What do you mean that $_POST["recaptcha_response_field"] and $_POST["recaptcha_challenge_field"] are not both set "inside" ajax.recaptcha.php.
That's impossible Firebug's Net-Tab shows that the request just works fine.
Did you check your server logs (enable post data logging temporarily )
Maby something like this?
var challengeField = $("#recaptcha_challenge_field").val();
var responseField = $("#recaptcha_response_field").val();
/* Debug */ alert ("Going to send channengeField with value '" + challengeField + "', and responseField with '" + resonseField + "'");
$.post ("../ajax.recaptcha.php", {
recaptcha_response_field: responseField,
recaptcha_challenge_field: challengeField
},
function(data)
{
/* Debug */ alert ("Data Recieved: " + data);
if (data == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
});
You can try like this
data: "recaptcha_response_field=" + $("#recaptcha_challenge_field").val() + "&recaptcha_challenge_field=" + ("#recaptcha_response_field").val(),
Related
I have a code in JS like this:
$.ajax({
url: $("body").data("url") + "/Documents/CheckDoc",
data: {
docID: id
},
dataType: 'text',
}).success(function (json) {
if (json.status) {
if (json.result) { // word template format
window.open($("body").data("url") + '/Case/OpenEnforcementDocument?DocID=' + id + '&RRcode=' + RR);
}
else { //html template format
window.open($("body").data("url") + '/EnforcementPrintout/Printout?DocID=' + id + '©s=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
});
toastr.error("error");
It refers to the CheckDoc function on the server
And there it works great but when it comes back to JavaScript
It does not return to .success and does not reach the last row of the function: toastr.error
Which had to be carried out anyway
It is as if flying from this function and not returning to it again
Someone might know what the problem might be
Will help me a lot
Thank you
It's look like there is some mistake in your code, you closed your code after dataType: 'text', by }) , please try this and let us know:
$.ajax({
type: "POST",
url: $("body").data("url") + "/Documents/CheckDoc",
data: { docID: id },
contentType: "application/json; charset=utf-8",
dataType: 'text',
success: function (json) {
if (json.status) {
if (json.result) { // word template format
window.open($("body").data("url") + '/Case/OpenEnforcementDocument?DocID=' + id + '&RRcode=' + RR);
}
else { //html template format
window.open($("body").data("url") + '/EnforcementPrintout/Printout?DocID=' + id + '©s=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
},
failure: function (response) {
alert("failure");
},
error: function (xhr, ex) {
alert('error')
}
});
I've read similar questions and tried different methods, but nothing seems to work. I have a Liking system. A heart image which switches between liked (filled heart icon) and unliked (Plain bordered heart icon).
The problem is, when I click on the like/heart button, all the other records' heart icon turns to liked state. The same goes with the like count. When I like a post, all the post's like count becomes the same.
Also, I'm running an AJAX request to get the likes count. When I try to output the likes and increment/decrement if they like/unlike, the output is weird. It goes to -1 or 01 etc.
This is my main.blade.php :
<span class="activityLikes">
<input type="hidden" class="activityIdHidden" value="{{ $activity->activity_id }}">
<a class="likeBtn">
#if(Auth::user()->hasLikedActivity($activity))
<img class="likeImg likeTrue" src="IMG/icons/likeTrue.png" alt="likes">
#else
<img class="likeImg likeFalse" src="IMG/icons/like.png" alt="likes">
#endif
</a><span class="likesCount">{{ $activity->likes->count() }}</span>
</span>
This is my main.js file :
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
$('.likeImg').attr('src', 'IMG/icons/like.png');
$('.likesCount').text(likeCount - 1);
} else if(data == "liked"){
$('.likeImg').attr('src', 'IMG/icons/likeTrue.png');
$('.likesCount').text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
It is because you update every image that has the .likeImg class on the success event.
Can you try the following code ?
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
// element to update is `this` (the element that had been clicked)
var elementToUpdate = $(this).children('img');
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
elementToUpdate.attr('src', 'IMG/icons/like.png');
elementToUpdate.text(likeCount - 1);
} else if(data == "liked"){
elementToUpdate.attr('src', 'IMG/icons/likeTrue.png');
elementToUpdate.text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
You should chain your Ajax calls, and get the count after updating the "like" status, like this:
function errHandler(e) {
console.log(JSON.stringify("Exception: " + e));
}
$('.likeBtn').on('click', function(e){
var activityId = +$(this).siblings(".activityIdHidden").val(),
$img = $("img", this),
$likes = $(this).siblings(".likesCount");
e.preventDefault();
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
error: errHandler
}).then(function(data){
$img.attr('src', data === "deleted" ? 'IMG/icons/like.png' : 'IMG/icons/likeTrue.png');
return $.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
error: errHandler
});
}).then(function(data){
$likes.text(data);
});
});
I followed this awesome tutorial to get the access and refresh tokens once the user logged in with their google account, but I always this response when I call GetAccessCode():
{
"error": "invalid_request"
}
Here's my code:
var url = window.location.href;
if (url.indexOf("code=") > 0) { //Once the user signed in with Google
var code_starts = url.indexOf("code=");
var code = url.substring((code_starts + 5), url.length);
alert("Code= " + code);
GetAccessTokens(code);
} else if (url.indexOf("access_token=") > 0) { //Get the tokens, but I never get this far
var at_starts = url.indexOf("access_token=");
var exp_starts = url.indexOf("expires_in=");
var access_token = url.substring((at_starts + 13), exp_starts);
alert("AT= " + access_token);
var rt_starts = url.indexOf("refresh_token=");
var id_starts = url.indexOf("id_token=");
var refresh_token = url.substring((rt_starts + 14), id_starts);
alert("RT= " + refresh_token);
} else {
GetAccessCode(); //If user opens the page, show him the consent screen
}
function GetAccessCode() {
window.location = 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https://mywebsite.com/quickstart.html' + '&response_type=code' + '&client_id=' + clientId + '&scope=' + scopes + '&approval_prompt=force' + '&access_type=offline';
}
function GetAccessTokens(code) {
window.location = 'https://accounts.google.com/o/oauth2/token?code=' + code + '&client_id=' + clientId + '&client_secret=' + clientSecret + '&redirect_uri=https://mywebsite.com/quickstart.html' + '&grant_type=authorization_code';
}
Here I receive the invalid_request error.
I tried to get the tokens via an ajax request to not have to redirect the page again (bad UX):
var red = 'https://mywebsite.com/quickstart.html';
var options = {
url: 'https://accounts.google.com/o/oauth2/token',
type: "POST",
dataType: "json",
data: "code=code&client_id=clientId&client_secret=clientSecret&redirect_uri=red&grant_type=authorization_code",
complete: function (e) {
alert(e);
alert(e.status);
},
};
$.ajax(options);
}
I tried it with headers, too:
headers: { "Content-type": "application/x-www-form-urlencoded"},
And I tried it this way, too:
$.ajax({
url: "https://accounts.google.com/o/oauth2/token",
type: "post",
datatype:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async : true,
data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
success: function(response){
alert(response); //I never get this
var json = $.parseJSON(response);
}
})
.fail(function(err) {
alert("error" + err); //I get [Object object]
});
And a few other stuff, too.
Oh, and all the parameters have the correct value.
Any ideas?
Ps: The oauth playground shows that the corrent token url is https://www.googleapis.com/oauth2/v4/token but when I use it I get Not found in the browser.
After 3 days I did it. Thanks for the console.log tip, #Brunt!
$.ajax({
url: 'https://www.googleapis.com/oauth2/v4/token',
type: "post",
datatype:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async : true,
data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
success: function(response){
console.log("Response: " + response);
console.log("AT: " + response['access_token']);
console.log("RT: " + response['refresh_token']);
access_token = response['access_token'];
refresh_token = response['refresh_token'];
}
})
.fail(function(err) {
alert("error" + err); //[Object object]
console.log("error" + err);
});
i am trying to implement an ajax call using jquery.when i am submitting the call, it is throwing 400 Bad Request..Not sure where i am doing wrong in my ajax call..Need help in fixing this..
submitHandler:function(form){
var emailSub = $("#emailSubTxtArea").val();
var emailBody = $("#emailBodyTxtArea").val();
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
dataType: "json",
//cache:false,
contentType: "application/json; charset=utf-8",
data:JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}),
success:function(data)
{
console.log("Sending Email Notification was success.");
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t
+ m);
}
}
});
}
my Controller code:
#RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
public ModelAndView sendEmailCommunication(#RequestParam("emailSubject") String emailSubject,#RequestParam("emailMsg") String emailBody,HttpServletRequest request){
ModelAndView view = null;
StringBuffer sMsg = new StringBuffer();
StringBuffer eMsg = new StringBuffer();
boolean isAdmin = false;
try{
String loggedInUser = request.getHeader("sm_user").trim();
isAdmin = getUserAdminRights(request);
if(isAdmin){
boolean status = emailService.sendEmailCommuncation(emailSubject,emailBody);
if(status){
sMsg.append(" Sending SiteMinder Notification Email was Success.");
}
else{
eMsg.append(" Oops! Something went wrong while sending Email Notification. Pls check logs");
}
}
else{
view = new ModelAndView("redirect:/web/utilities/not_authorized");
return view;
}
}
catch(Exception ex){
ex.printStackTrace();
eMsg.append("Oops! Something went wrong while sending Email Notification. Pls check logs");
}
view = new ModelAndView("EmailCommunication");
view.addObject("isAdmin", isAdmin);
view.addObject("sMsg", sMsg.toString());
view.addObject("eMsg", eMsg.toString());
return view;
}
cheers guys...
Very Simple
submitHandler:function(form){
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
data:$(form).serializeArray(),
success:function(data)
{
console.log("Sending Email Notification was success.");
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t
+ m);
}
}
});
}
var strResponse=$.ajax({ type: "POST", url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
data: JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}), async: false,
contentType: "application/json;
charset=utf-8", dataType: "json" });
if (strResponse.readyState == 4 && strResponse.status == 200)
return ((strResponse.responseText.indexOf("d") >= 0) ? eval('(' + strResponse.responseText + ')').d : strResponse.responseText);
The script is nothing back what this could be?
Here a link to the page Test Link
$(document).ready(function() {
// Anmeldung des Namens
$("#startfrom").submit(function() {
if($("#yourname").val() == "") {
$("#response").html("Bitte gebe einen Namen an!");
} else {
name = $("#yourname").val();
$("#submit").attr("disabled", "disabled");
$("#response").html("Lade...");
$.ajax({
type: "POST",
url: "chat.php"
data: "name=" + name
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
}
return false;
});
});
The code is intended to provide an issue who was entering no name.
The problem is you missed commas at the end of these lines:
url: "chat.php"
data: "name=" + name
These both lines need , in the end. They are objects. Corrected code:
$.ajax({
type: "POST",
url: "chat.php",
data: "name=" + name,
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
The other mistake is: Change your form id: Your form id is 'startform' not 'startfrom'.
Update
Hope this above one helps you.
Works for me after putting the comma:
Your form id is 'startform' and you wrote is 'startfrom'.
So, first of all correct you id name which you wrote in jquery and then try it.
After this if you got any error then try this code :
$(document).ready(function() {
// Anmeldung des Namens
$("#startform").submit(function() {
if($("#yourname").val() == "") {
$("#response").html("Bitte gebe einen Namen an!");
} else {
var name = $("#yourname").val();
$("#submit").attr("disabled", "disabled");
$("#response").html("Lade...");
$.ajax({
type: "POST",
url: "chat.php",
data: { name: name},
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
}
return false;
});
});
I hope you will get your solution.