JSON Data are undefined in JavaScript after server response - javascript

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

Related

Data received from ajax get request

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))

Javascript parse json from URL

Trying to parse a json response from URL in javascript.
Here is what the response looks like
{"data":[{"version":"7.4.0","startDate":"2016-12- 12","totalSessions":"6208723","totalCrashes":"2944","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-11","totalSessions":"4979676","totalCrashes":"2378","crashRate":"0.048"},{"version":"7.4.0","startDate":"2016-12-10","totalSessions":"534913","totalCrashes":"208","crashRate":"0.039"},{"version":"7.4.0","startDate":"2016-12-09","totalSessions":"309564","totalCrashes":"147","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-08","totalSessions":"255597","totalCrashes":"162","crashRate":"0.063"},{"version":"7.4.0","startDate":"2016-12-07","totalSessions":"21379","totalCrashes":"12","crashRate":"0.056"}]}
I can dump the json output using
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$('#show-list').html(data2); //shows json
});
Then I tried to parse it using
document.getElementById("placeholder").innerHTML=data2.data[0].version
also tried
obj = JSON.parse(crash);
console.log(obj.data2[0].version);
But no luck.
You should tell jQuery that the AJAX function returns JSON, then it will parse it automatically for you.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$("#placeholder").text(data2.data[0].version);
}, 'json');
Or you can call JSON.parse() yourself.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
var data = JSON.parse(data2);
$("#placeholder").text(data.data[0].version);
});

Parsing server response with $.parseJSON failed

I've got these two simple functions:
function getBatchSliceInfo(batch_num){
//get the batch slice info for the batch_num
alert('batch num is ' + batch_num); //returns the batch_num correctly
$.getJSON("statistics_batchdb.jsp", {batch_number: batch_num, slice_stats: 'true'}, showTable);
}
function showTable(data){
$("#table_slice_stats").hide();
if(data.error){
console.log("Something went wrong");
}
var jo = $.parseJSON(data);
alert('This JSON object has this many elements: ' + jo.length);
$.each(jo[0], function (i, val){
alert('This i value is' + i );
alert('This val value is' + val);
});
$("#table_slice_stats").show();
}
So I call getBatchSliceInfo on the click of a button and we get the JSON.
The response seems to be correct, so server side I'm alright.
However, I'm not passing that response correctly to showTable. "data" appears to be null because in the console I get the error:
Uncaught TypeError: Cannot read property 'length' of null batch_statistics_new.jsp:274
showTable batch_statistics_new.jsp:274
o jquery-1.7.2.min.js:2
p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
d jquery-1.7.2.min.js:4
I'm sure this is a very simple syntax question but I have no idea what's going on.
check your data
var data= [{slice_name:Nutrion,iteration_zero:.....},{......},{......}]
After convert to json Format.your data become like this,
var data= {[{slice_name:Nutrion,iteration_zero:.....},{......},{......}]} //It not json format.
if you tring to use length property it throwing an exceptions.so,do the same think without parsing into json.

jquery using json object

script.js
$('#loginform').submit(function(e){
$.ajax({
type:"POST",
url:"/accounts/login/ajax/",
data:$('#loginform').serialize(),
success: function(msg){
var msg = msg;
msg = JSON.parse(msg);
$('#messagestatus').html('');
if(msg.username != null){
$('#messagestatus').append(msg.username);
}
if(msg.password != null){
$('#messagestatus').append(msg.password);
}
}
});
e.preventDefault();
});
returned object
{'username':['Required'],'password':['Required']}
When I am using JSON.parse and I am alerting, it's showing the correct error, but when I am appending it to the messagestatus div its not responding, please help .
Your username and password are arrays in your json.Either make it that your json looks like
{'username':'Required','password':'Required'}
or change your script:
if(msg.username.length > 0)
{
$('#messagestatus').text(msg.username[0]);
}
if(msg.password.length > 0)
{
$('#messagestatus').text(msg.password[0]);
}
Might be significant, might not be, but your json object actually consists of sub-arrays:
{'username':['Required'],'password':['Required']}
^----------^ ^----------^
meaning that the decoded data structure in JS would actually be
obj['username'][0] and obj['password'][0]
First of all, parameters do not need to be redeclared in their function.
then, to parse your json using $.parseJSON() :
msg = $.parseJSON(msg);
Your JSON contains arrays, use msg["username"][0] to access the first string and not the full array.
And I would put e.preventDefault(); as first statement before AJAX.
And .html('') => .empty() but it's the same result.

Prototype believes JSON from PHP is string

I have the following code in JS:
new Ajax.Request('http://www.some_random_url.com',
{
parameters: { start : this.start, stop : this.stop },
method: 'post',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response.posts);
$(response.posts).each( function(item) {
alert(item.title);
}
},
onFailure: function(){ alert('Something went wrong...') }
});
and then I have the following code in PHP. The function takes an array as an argument, and is meant to output JSON.
function view_api($array) {
header('Content-type: application/json');
echo json_encode(array('posts'=>$array));
}
Still, it seems to be treated by prototypejs as a string. When response is alerted, everything is fine. But the each loop in JS says response.posts is undefined.
Do you know why?
If it's returning the JSON as a string then you should parse it first.
var data = JSON.parse(payload);
use evalJSON() to typecast the response in JSON object as
var response = transport.responseText.evalJSON() || "no response text";
set evalJSON: 'force' in the prototype ajax request options. then use var response = transport.responseJSON
A neat trick with prototype.js is that you can pass the following headers and it will automatically be converted to json.
header('X-JSON: (' . json_encode($data) . ')');
header('Content-type: application/x-json');

Categories

Resources