Why can't I access these JSON values? - javascript

In one of my web pages I am making an AJAX call to retrieve a member's profile properties so that they can make changes. The code being used to do this is as so:
function loadProfileData() {
var request = $.ajax({
url: "../handlers/getprofile.ashx",
method: "POST"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#spnProfileErr').html(msg.Status);
$('#toastProfileFail').toast('show');
}
else {
$('#lastname').val(msg.MemberProfile.LastName); // textbox
$('#firstname').val(msg.MemberProfile.FirstName); // textbox
$('#bestemail').val(msg.MemberProfile.BestContactEmail); // textbox
$('#agerange').val(msg.MemberProfile.AgeRange); // select control
$('#zipcode').val(msg.MemberProfile.ZIPCode); // textbox
}
});
request.fail(function (jqXHR, textStatus) {
$('#spnProfileErr').html('Unable to retrieve your existing profile at this time.');
$('#toastProfileFail').toast('show');
});
}
The call to the web service works just fine, and it returns a JSON String, as follows:
I can access the 'Success' and 'Status' properties of the returned JSON, but when I try to access the member profile properties of the MemberProfile in the JSON, it doesn't let me. For example, accessing msg.MemberProfile.LastName throws an undefined error.
What am I not doing right?

Probably, you're receiving just a string, try use
var msg = JSON.parse(msg)
at beginning of your callback, so it will convert your string to a desired object, try out

Try adding the type:"json" property inside the ajax object, just after the method property

Related

Accessing Ajax Response JSON Data in javascript

I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location

How can I send an object via Ajax from within a Javascript Class?

My question title may not be phrased well, sorry.
I want to create a Javascript class to simplify sending information to a php page.
I'm using the method described in this answer to create my class
This is what I have so far:
var ParseObject = Class.extend({
init: function(classname, id){
// required properties
this.classname=classname;
this.objects=[];
this.fields=[];
// optional properties
if(id && id != '') this.id='';
//this.command = command;
//this.callback='';
//this.parent=[];
//this.children=[];
//this.relation='';
},
set: function(field, value) {
if(field == 'classname') this.classname=value;
else if(field == 'callback') this.callback=value;
else if(field == 'command') this.command=value;
else this.fields.push(field, value);
},
addChild: function(obj){
this.children ? this.children.push(obj) : this.children= [obj];
},
addParent: function(linkedFieldName, parentClassName, parentId){
this.parent=[linkedFieldName, parentClassName, parentId];
},
addObject: function(obj){
this.objects.push(obj);
},
isRelatedBy: function(relation){
this.relation=relation;
},
send: function(){
var obj = this;
$.ajax({
type: "POST",
dataType: "json",
url: "php/parseFunctions.php",
data: {data:obj},
success: function(response) {
// do stuff
},
error: function(response) {
// do stuff
}
});
}
});
And here's how Im trying to use the class:
var testObject = new ParseObject('TestObject');
testObject.set('callback','testResopnse');
testObject.set('command','save');
testObject.set('title','New Title');
testObject.set('description','New Description');
testObject.set('stuff',['one','two','three']);
testObject.addParent(['parent', 'MeComment', 'kRh5xcpkhz']);
testObject.send();
Everything works as expected until I get to testObject.send();
What I expect is for the below object to get sent to my PHP page:
But instead, what I get is "Uncaught RangeError: Maximum call stack size exceeded"
Why does this happen, and how can I achieve the desired result?
Update:#
Per Quentin's suggestion, this got me sorted
var obj =$.parseJSON(JSON.stringify(this));
When you pass an object to data:, jQuery will call param on it.
That function includes this code:
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : (value == null ? "" : value);
That ends up calling all the functions in the object (including the constructor) in the context of window. I don't have the tuits to figure out all the effects of that, but it clearly isn't desirable and, based on the error message, leads to infinite recursion.
You have several options here:
Write an explicit function that extracts the data you care about from the object and presents as a simple data structure consisting only of the data types you can serialise with .
Serialise the object to JSON and then deserialise it to strip out all the functions before you pass it to param via data:
Serialise the object to JSON, pass that as a string to data:, set the request contentType: "application/json" and change the PHP to expect a JSON formatted request instead of a form formatted request.
(I don't know if this will work) change the way you construct the class to use Object.defineProperty() and mark all the functions so they are not enumerable. I suspect this approach would fail because the object is, itself a function.

Undefined parameter when returning data from jQuery.post to PHP

I am trying to return data from a database and populate a text field after the user enters an ID in the first text box. Currently I had the code working as long as the user did not enter a space in the ID number. Now I am attempting to allow that use case. My PHP code returns a json encoded array with three fields: first_name, last_name, and full_name.
When I use console.log(data) to view the data being returned I receive the following:
{"first_name":"Test","last_name":"Test","full_name":"Test Test"}
However in my code, I try to write data.full_name in a .val() nothing is populated, and when use the console.log I get an error saying "undefined".
Here is the whole jQuery Code:
$("#ID").blur(function () {
var params = {};
params.ID = encodeURIComponent($(this).val());
$.post("getter.php", params, function ( data ) {
if (!data) {
$("input[name=username]").val("User Not Found");
} else {
$("input[name=username]").val(data.full_name);
$("input[name=username]").attr("readonly", true);
}
});
});
Any help you can offer would be much appreciated.
Force jQuery to read the returned data as json:
$("#ID").blur(function () {
var params = {};
params.ID = encodeURIComponent($(this).val());
$.post("getter.php", params, function ( data ) {
if (!data) {
$("input[name=username]").val("User Not Found");
} else {
$("input[name=username]").val(data.full_name);
$("input[name=username]").attr("readonly", true);
}
}, "json"); // <- json forced
});
and then make sure your returned data is in proper json format (for example with json_encode in php)
Use trim() to remove spaces.
Then you can check if the parameter value is_numeric(), and if false, set a default value.

Return String From XHRGet

I'm creating a tree using Dojo and two seperate sets of data. One set of data makes up the main tree structure. The second set of data is dependent on a value from the first set. I'm using xhrGet and Dojo 1.7.3 to get the data.
Once the second set of data has been returned, I'm looking at the values of the JSON to determine a value of a variable, that's then passed into the tree. The variable displays a "!" if an "alert" value is present in the JSON returned and blank if there isn't.
var theAlert = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json',
load: function(data){
if(typeof data.alerts[0] != 'undefined'){
var hello = "!";
return hello;
}
else{
console.log("There is nothing there");
},
error: function(error){
console.log(error)
}
});
The problem I'm having is that when I write "theAlert" variable where I need to, it appears as "[object Object]" and not as "!".
I feel like I'm doing something wrong, but I can't figure out what.
I have already tried using theAlert.valueOf(); to no success. Help?
The data is received correctly as well, I can view it via console log.
dojo.xhrGet() returns a Deferred - http://dojotoolkit.org/reference-guide/1.9/dojo/Deferred.html
You need to do something like:
var deferred = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json'
});
deferred.then(
function(data){
if(typeof data.alerts[0] != 'undefined'){
processAlert("!");
} else{
console.log("There is nothing there");
}
},
function(error){
console.log(error)
}
);
function processAlert(a) {
alert(a);
}
Look at the docs.
You need to return data, not hello.

Creating a variable from returned data ajax post

I want the data returned from an ajax post to be put into a javascript variable where I can then run an if statement checking whether that variable is equal to true. However, Firebug is telling me the variable verify is not defined. How do I write the function within the ajax post to set the data to verify correctly? Code is below.
$.post('ajax_file.php',
{
user_id: user_id,
band_term: band_term
}, function (data) {
var verify = data;
if (verify == 'true')
{
$('#request_form').hide();
$('#where_to_go').hide();
$('#change_form').show();
}});
The ajax file returns true on success and false on failure.
if (mysql_query($sql) == true)
{ echo 'true';} else {echo 'false';}
Firebug shows me that the ajax file is returning with the string true, so I know the ajax file is working.
The issue is on a few places.
First, how you output data on you .php file. You should be returning JSON and accepting JSON on you ajax request. Look at this example:
<?php
$variable = array("stat" => true, "data" => array(10, 10));
print_r(JSON_Encode($variable));
?>
That will output this:
{"stat":true,"data":[10,10]}
Then on yout JS you'd do:
$.post('ajax_file.php', {
user_id: user_id,
band_term: band_term
}, function (data) {
//Data is the whole object that was on the response. Since it's a JSON string, you need to parse it back to an object.
data = JSON.parse(data);
if (data.stat === true){
$('#request_form').hide();
$('#where_to_go').hide();
$('#change_form').show();
}
});
It's because verify was created in the callback function. Also, that variable isn't visible outside that function.
To operate on returned data from an AJAX call, do it in the callback function.
$.post('ajax.php', {
user_id: user_id,
term: term
}, function (data) {
var verify = data; //assuming data is just true or false
if (verify === 'true') {
unnecessary code
}
});
The variable is defined inside the callback function is does not match the scope of the document.
To make it actually work, just define it anywhere in the beginning of your script as follows:
var verify;
$.post('ajax.php',
{
user_id: user_id,
term: term
},
function (data)
{
verify = data; // then also remove the word var from your code here.
if (verify == 'true')
{unnecessary code}
}
);
-i wouldn not use j query for ajax ( i find getdata to be better but the call back variable needs to be passed to the next function
ie. if you are gonna alert(data) as your call back, do your if statements there.
also i was running into similar problems. using numbers such as one or zero in my php response helped alot, and i just used js to determine what the actual string or alert output would be

Categories