Data received from ajax get request - javascript

I've got flask app and I'm trying to make a request from the client to backend and the other way round to validate ReCaptcha.
JS:
var onloadCallback = function() {
var captchaCallback = function(param) {
return $.get( "gettoken/" + param, function( data ) {
window.console.log(data.toString())
if (!data.success) {
window.alert("something went wrong" + data.error);
}
else {
$(".submitBtn").prop("disabled", false);
}
});
};
grecaptcha.render('html_element', {
'sitekey' : 'secret_key',
'callback' : captchaCallback
});
};
PYTHON:
#app.route('/gettoken/<g_recaptcha_response>')
def verify_recaptcha(g_recaptcha_response):
with urllib.request.urlopen('https://www.google.com/recaptcha/api/siteverify?secret=secret_key&response=' + g_recaptcha_response) as url:
data = json.loads(url.read().decode())
print(data)
return data
Data printed in python method is correct {'success': True, 'challenge_ts': '2019-11-07T11:07:22Z', 'hostname': 'localhost'}. But then data printed back in js shows: [object Object]. How should I correctly read the data return from python verify_recaptcha method?

.toString applied for an object will return [object Object]
var myObj = {};
console.log(myObj.toString());
//returns [object Object]
Try to use object attributes directly, like this:
console.log(data.success);
And just as advice: never show your API keys on public

Your code is correct. The problem is calling .toString() on an object will return that. If you want to see a log with your object try with:
window.console.log(data)
or:
window.console.log(JSON.stringify(data, null, 2))

Related

Splicing and then saving json array via ajax

I'm having trouble getting my json array to accept changes. I'm trying to remove an object from the array, and it appears to work but then when I look at the json array on the server it remains unchanged. What am I missing here?
Here is the function I'm using:
$(function() {
$("#rectangle-delete").click(function() {
var selection = $('#templateSelection > option:selected').text();
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'type': 'POST',
'contentType':"application/json",
'url': 'server/php/data/' + selection,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
var ID_clicked = $(".rectangle.selected.targeted").attr('id');
console.log('initial array is ' + json);
json.some(function(e) {
if (e.ID === ID_clicked) {
var values = json.map(function(e) { return e.ID; });
var index = json.map(function(e) { return e.ID; }).indexOf(ID_clicked);
var data = JSON.stringify(json[index]);
json.splice(index, 1);
return true; // stop the array loop
}
});
console.log('new array is ' + json);
});
});
The console shows:
initial array is [object Object],[object Object],[object Object]
and then
new array is [object Object],[object Object]
but I'm still not changing the actual json file on the server.
When you pull down the json from the server you are not getting a reference to the object on the server but you are getting a copy of the data.
So you are just modifying data on your client.
To update the object on the server you should notify the change to the server (or reverse the logic letting the server do the computation and retrieve directly the result on the client).

Json Ajax Response from Django Application

I have a Django app that the views.py sends a json data to a javascript function on my html. The problem is that I can not access the elements of the data.
I tryied to use JsonParse but not sucess, for instance when I do
var other = JSON.parse(data_doc_pers['data_doc_pers']);
document.getElementById("text_conf4").innerHTML = other['doc_nome'];
I receive the following response: [object Object]
what I am doing wrong???
Here is my code
Views.py
...
json_string = json.dumps({'type_numeric':type_numeric,'type_prop':type_prop,'name':name,'Vinculo':Vinculo,'doc_nome':doc_nome})
return JsonResponse({'data_doc_pers':json_string})
HTML
$.get('{% url "page" %}',{'var':var}, function (data_doc_pers) {
var other = JSON.parse(data_doc_pers['data_doc_pers']);
document.getElementById("text_conf4").innerHTML = other['doc_nome'];
});
Problem solvend!
The error I was doing in javscript was to use var other = JSON.parse(data_doc_pers['data_doc_pers']); the correct should be only (data_doc_pers['data_doc_pers'].

JSON Data are undefined in JavaScript after server response

I have trouble with my script in PHP which get a json array.
I use the following code:
$(function() {
$("img").click(function() {
auswahl = $( this ).attr("id");
$.get('mail_filebrowser_add2.php?datenID=' + auswahl, function(data) {
alert("Server Returned: " + data.hello);
});
return false;
});
I expect the the alert show "Server Returned: abc".
Because the value of the key "hello" from the JSON Object is "abc".
But I get only the information "Server Returned: undefined".
If I run the script where the JSON query comes from it looks fine:
{"hello":"abc"}
Any idea what i do wrong?
You can use JSON.parse to parse the data into JSON object,
var parsedObject = JSON.parse(data);
and then use parsedObject.hello

javascript: use ajax string to create object

In a javascript function, if I set:
var listnames = {
"lista": {name: "ListA"},
"listb": {name: "ListB"},
"listc": {name: "ListC"},
};
console.log(listnames);
the console shows: [object Object].
However, if I build the same text in php and retrieve it using ajax like this:
function set_listnames() {
$.ajax({
type:"POST",
url: form_handler, // a php script
data: '&action=get_listnames',
dataType: 'json'
})
.done(function (data) {
listnames = JSON.parse(data);
console.log('listnames (after parse): ' + listnames);
})
.fail(function() {
console.log ('failed');
});
the response text from the post in the console shows: "{\"lista\":{name:\"ListA\"},\"listb\":{name:\"ListB\"},\"listc\":{name:\"ListC\"}}"
and after parsing the console shows the string (same as the hardcoded values above):
{"lista":{name:"ListA"},"listb":{name:"ListB"},"listc":{name:"ListC"}}
I need the returned string to be evaluated as [object Object] in order for a plugin function I'm using to work.
How do I transform the ajax returned string into an object?
In response from server the key "name" without quotes.
Should be
{"name": "LisaA"}
You're 100% sure the first example shows [object Object]? In which browser(s) are you testing?
If you really need the parsed response to be [object Object], you can do this:
console.log( Object.prototype.toString.call( listnames ) );
But as far as wanting listnames to be an object... it already is.

JavaScript missing parametar

I am coding a block type plugin for Moodle and have this JS code that gives me problems. Since I'm not very familiar with JS and JSON I can't deduce what is the problem.
My code uses this function to add custom action to action link which issues ajax call to php file ...
This is the code:
function block_helpdesk_sendemail(e) {
e.preventDefault();
Y.log('Enetered method');
var sess = {'sesskey=':M.cfg.sesskey};
Y.log(sess);
var ioconfig = {
method: 'GET',
data: {'sesskey=':M.cfg.sesskey},
on: {
success: function (o, response) {
//OK
var data;
try {
data = Y.JSON.parse(response.responseText);
Y.log("RAW JSON DATA: " + data);
} catch (e) {
alert("JSON Parse failed!");
Y.log("JSON Parse failed!");
return;
}
if (data.result) {
alert('Result is OK!');
Y.log('Success');
}
},
failure: function (o, response) {
alert('Not OK!');
Y.log('Failure');
}
}
};
Y.io(M.cfg.wwwroot + '/blocks/helpdesk/sendmail.php', ioconfig);
}
The code pauses in debugger at return line:
Y.namespace('JSON').parse = function (obj, reviver, space) {
return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space);
};
I've put M.cfg.sesskey and data variables on watch. I can see sesskey data shown, but data variable shows like this:
data: Object
debuginfo: "Error code: missingparam"
error: "A required parameter (sesskey) was missing"
reproductionlink: "http://localhost:8888/moodle/"
stacktrace: "* line 463 of /lib/setuplib.php: moodle_exception thrown
* line 545 of /lib/moodlelib.php: call to print_error()
* line 70 of /lib/sessionlib.php: call to required_param()
* line 7 of /blocks/helpdesk/sendmail.php: call to confirm_sesskey()"
And this is what my logs show:
Enetered method
Object {sesskey=: "J5iSJS7G99"}
RAW JSON DATA: [object Object]
As #Collett89 said, the JSON definition is wrong. His tip might work, but if you need strict JSON data then code the key as string (with quotes):
var sess = {'sesskey': M.cfg.sesskey};
or
var sess = {"sesskey": M.cfg.sesskey};
See definition in Wikipedia
your declaring sesskey in a bizarre way.
try replacing data: {'sesskey=':M.cfg.sesskey},
with data: {sesskey: M.cfg.sesskey},
it might be worth you reading through this
mdn link for javascript objects.
You usually need to JSON.stringify() the objects sent via ajax.
which may be part of the problem.

Categories

Resources