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.
Related
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))
I have this code:
GameManager.prototype.initGame = function () {
var api = 'my_url';
$.ajax({
url : api,
type : 'POST',
data: "",
dataType : 'json',
success : function(data) {
alert(data);
}
});
};
I see in the Firebug console the JSON:
[{"data":{"score":500,"token":"2896c5380bf3e3e29467258c7fe885fe"}}]
But the alert(data) shows me [object Object].
Use alert(JSON.stringify(data));.
The object will already have been parsed when using:
dataType : 'json'
This is what the doc says:
"json": Evaluates the response as JSON and returns a JavaScript objec
You can read more about the dataType parameter here http://api.jquery.com/jquery.ajax/
Did you tried ?
var json = JSON.parse(data);
alert(json["score"]);
You should use JSON.Stringify().
JSON.Stringify()
console.log is for strings (link). I think you are doing everything ok, you just need to get certain properties from your object, eg. data.score if you want to output them using console.log, because I assume you will be working with data ir JSON format, and not in stringified version.
Try JSON.stringify() method to display the data of JSON object in alert. It will convert the JSON Object into JSON String.
DEMO
var jsonObj = [{
"data": {
"score": 500,
"token": "2896c5380bf3e3e29467258c7fe885fe"
}
}];
alert(JSON.stringify(jsonObj));
How can I do a AJAX request in ColdFusion?
I have my javascript:
function getdata(){
var formElements=document.getElementById("CFForm_1").elements;
var data=[];
for (var i=0; i<formElements.length; i++){
if(formElements[i].name == 'customersid')
data.push({'customersid':document.getElementById("customersid").value});
if(formElements[i].name == 'customerstoid')
data.push({'customerstoid':document.getElementById("customerstoid").value});
}
$.ajax(
{
type: "get",
url: "components/BillingCalc.cfc",
data: {
method:"ajaxGetTotalCost",
data: data.join()
},
dataType: "json",
success: function( objResponse ){
}
});
}
My component:
component displayName="Calc" {
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
I am getting the error: JSON parsing failure at character 2:'o' in [object Object],[object Object]
Does anyone knows how to do AJAX request in CF?
This function:
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
is not complete. It's at the stage where you have to call it from a ColdFusion page, not with javascript. That will enable you to see the results of the writedump(data) command to ensure it's what you expect. You have to add more code to the function to get it to produce a variable javascript can receive, and then return that variable to whatever is calling the function.
The issue is related to dataType attribute you are passing with $.ajax() method. dataType: "json" indicates your AJAX request is expecting JSON data as a response. But in your case you are simply returning DUMP of the deserialized JSON, which is HTML not JSON. So if you want it to work properly, then you need to return JSON data from your ColdFusion function. You can try this and see if it works.
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
return serializeJSON(data));
}
Basically response consist of two things JSON Array and isValid(flag)
I can get flag value successful But it gives the null var resJSON = jQuery.parseJSON(data.notification);. I debug my script in chrome console but json response exist in data.
Might be following code and console result help you to understand my problem!
function getNotificationById(notificationId) {
jQuery.ajax({
type: "POST",
url: "<%=request.getContextPath()%>/GetNotifications/",
dataType : "json",
data: {"operation": "getNotificationById", "notificationId": notificationId},
success:function(data){
var resJSON = jQuery.parseJSON(data.notification);
// ^-- here is null
if (data.isValid) {
// ^-- response is true
jQuery.each(resJSON,function(i, value){
console.log(value.Body);
});
}
}
});
}
Chrome Console Result:
Edit
I have tried following solutions:
var resJSON = data.notification; // Chrome Console return **undefined**
You have a typo.
The data as shown in traces are included in data.notificaiton and not data.notification
I am having a problem with this code, could someone help me out?
<script type="text/javascript">
$(document).ready(function()
{
$obj = $.get('getSesion.php',function(data){ } );
//$dato=JSON.stringify(obj);
//$dato=dojo.toJson(obj);
alert($obj);
if($obj != 'NULL')
{
$('#apDiv7').load('logeado.php');
}else{
$('#apDiv7').load('deslogeado.php');
}
}
);
</script>
The problem is that from $obj I get [object Object]. I searched how to convert it but I had no success.
MORE DETAILS. From data I can get a number (0-infinite) or the string NULL. Depend on what value I get, in apDiv7 I will load login window or a window's user connected.
I tried
var data =$obj.d;
but i get "undefined" string
Console log
http://imageshack.com/a/img46/4004/ufgv.jpg
Solution for this case:
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
.get is an async call, so you should be doing this logic in the callback:
$.get('getSesion.php',function(data) {
console.log(data);
});
Always use console.log so you can actually expand the complex object. Then simply reference the property names of the data response object.