recaptcha responded, but Ajax not getting it - javascript

So I'm having some trouble with my code. It seems that when I get the reCAPTCHA response it loads when I alert the variable, but AJAX isn't wanting to get it.
var url="";
if (DEPOSIT) {
url = "/get_inv?" + opts;
} else {
var g = grecaptcha.getResponse();
url = "/get_bank_safe?g-recaptcha-response=" + g;
}
alert(url);
$.ajax({
"url": url,
success: function(data) {
try {
alert(data);
data = JSON.parse(data);
Yes I've gotten a valid response from the URL variable itself, but when announcing the AJAX variable 'data', nothing is persevered. Therefore JSON cannot parse 'data'.
It even states that "url" : url.
So I'm not sure how to go about this. If there is any solution please alert me of so.
Thanks! ~LTn | mrgreen33gamer

Related

Pass function reference to a separate Javascript file for callback

I have created a common Javascript file for all my ajax calls. I am trying to use this as a common way to keep track of all ajax calls. Below is the code for the same.
function doAjax(doAjax_params) {
var url = doAjax_params['url'];
var requestType = doAjax_params['requestType'];
var contentType = doAjax_params['contentType'];
var dataType = doAjax_params['dataType'];
var data = doAjax_params['data'];
var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
var successCallbackFunction = doAjax_params['successCallbackFunction'];
var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
var errorCallBackFunction = doAjax_params['errorCallBackFunction'];
//Make the ajax call
$.ajax({
url: getBaseURL() + url,
crossDomain: true,
type: requestType,
contentType: contentType,
dataType: dataType,
data: data,
success: function (data, textStatus, jqXHR) {
console.log(typeof successCallbackFunction);
debugger
//if (typeof successCallbackFunction === "function") {
successCallbackFunction(data);
//}
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof errorCallBackFunction === "function") {
errorCallBackFunction(errorThrown);
}
}
});
}
This code takes a list of parameters and creates an ajax request based on the parameteres. This code is saved in a file APIHandler.js.
I am trying to call this function from multiple files. An example call is below.
function RedirectToDashboard() {
var params = $.extend({}, doAjax_params_default);
params['url'] = `profile/5`;
params['successCallbackFunction'] = `testsuccess`
doAjax(params);
}
function testsuccess() {
alert("success");
}
When I run this function, I am able to make the call successfully. The only issue comes with the reference to callback function. console.log(typeof successCallbackFunction); returns string instead of function.
I thought maybe order of JS made a difference. I am loading APIHandler.js and then the page specific js. And this ajax call happens at button click, so both JS files are loaded before the ajax call is made.
Other than that, I think maybe I am sending the parameters wrong. That might be causing JS to consider function name as string. But I checked most of the google suggestions on how to pass function, and it seems it needs just the name.
Is there anything else that I might be missing here?
Damn it. I just figured out why it was causing the error. I used quotes when assigning the callback function. Right after posting the question, I realised what was wrong.
params['successCallbackFunction'] = 'testsuccess'
is supposed to be changed to
params['successCallbackFunction'] = testsuccess

Add data to JQuery Form

First of I admit that I am really bad at js and just got started. I have this snippet in the repository:
function sendReport() {
$.post($('#reportForm').attr('action') + '/post', $("#reportForm").serialize()).done(function() {
reportManager.run();
});
}
And I want to add data to it. I want the webservice that is receiving the post to receive an additional key/value-pair. I tried something like
var data = $('#reportForm').serializeArray();
data.push({name: 'stuff', value: 'blaha'});
$.post(data, $("#reportForm").serialize()).done(function() {
reportManager.run();
});
Didn't work at all and I would really appreciate any help with this.
EDIT:
Tried doing the suggestion below, didn't work. Tried this just to verify that the new parameter didn't ruin anything:
//data to post
var data = $('#reportForm').serializeArray();
//url to post
var url = $('#reportForm').attr('action') + '/post';
//options required for jQuery.post
var options = { "data":data, "url": url };
$.post(options).done(function() {
reportManager.run();
});
That doesn't work. I'm getting an error like this on the server:
noHandlerFound No mapping found for HTTP request with URI [/[object Object]]
I am considering that something else in the code might be using some implicit behaviour, but I find it strange that trying the code above(without even adding new data) can break the current working behaviour.
You are not providing uri parameter for post method, you should use something similar to:
//data to post
var data = $('#reportForm').serializeArray();
data.push({name: 'stuff', value: 'blaha'});
//url to post
var url = $('#reportForm').attr('action') + '/post';
//options required for jQuery.post
var options = { "data":data, "url": url };
$.post(options).done(function() {
reportManager.run();
});

Empty Array AJAX

So I have searched around a bit in hopes of finding a solution to my problem, but have had no luck.
I am basically trying to pass data into the ajax function, but when it passes it to my php file it only returns an empty array (Yes there are a few topics on this, couldn't find any to fit my needs) , here is the console output: Array ()
Its odd because just before the ajax function I log the data, and it prints out each section with no problems.The posting URL is accurate, works fine straight from my form. I have tried to use response instead of data passed through the function, but no luck their either.
Thanks in advance!
Here is the JS file
$(document).ready(function() {
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = [];
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data); /////THIS LINE HERE ACTUALLY PRINTS DATA
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
return false;
});
});
And here is my PHP
<?php //removed the issets and other checkers for ease of readability
print_r($_POST);
?>
UPDATE: I have tried to add method:"POST" to my ajax function and it still seems to be printing out blank arrays... Maybe I should convert everything to GET?
jQuery ajax() uses GET as default method. You need to mention method: POST for POST requests.
method (default: 'GET')
$.ajax({
url: url,
method: "POST",
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
Or you can also use post().
EUREKA!!! Wow, the mistake was much simpler than I thought, figured it out solo! Thank you everyone for the tips! Finally got it
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {}; // THIS NEEDS TO BE CHANGED TO BRACKETS!!

requested json parse failed ,there was an error parsing the json document

var objectData ={
"emailAdress" : document.getElementById('emailAddress').value ,
"password": document.getElementById('password').value }
var objectDataString = JSON.stringify(objectData);
alert(objectDataString);
var url = "url";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert('connected..');
}
};
xmlhttp.open("POST",url,true);
xmlhttp.send(objectDataString);
$.ajax({
type: "POST",
URL:"login.php",
contentType:"application/json",
CrossDomain:true,
data: JSON.stringify(objectData),
dataType: 'json',
success: function (data) {
alert("success");
var ret = jQuery.parseJSON(data);
alert(ret);
I have login form which contains userid and password.i have to convert that user entered info into json and send it to the server.but getting json parsed error .unable to find the error.please tell me where i m doing wrong..?i m trying from so many hours but unable to find .
Ignoring the XHR code, and just looking at the ajax call:
There's no CrossDomain option. There's a crossDomain option, though. (JavaScript is case-sensitive.) You probably don't want that option at all, though, with the URL you're giving.
You're telling jQuery that the data coming back is JSON. That means jQuery will parse it for you before giving you the data argument to your success function. You don't need (or want) to call JSON.parse on it, that's already been done for you. data will be parsed data.

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources