PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] Why can't I access these JSON values?

 September 08, 2022     ajax, asp.net-ajax, javascript, json     No comments   

Issue

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:

JSON returned by web service

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?


Solution

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



Answered By - Aloiso Junior
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing