user4593252
user4593252

Reputation: 3506

Parsing response text as key value pairs in an elegant way

Can't seem to find what I'm looking for in searches so this might be a duplicate but I haven't found an original yet sooo....

I have a an ajax call:

$.ajax({
    url: "/events/instructor/",
    type: 'POST',
    data: {
        instructorID: $(this).attr("id")
    },
    complete: function (data) {
        $("#name").html(data["responseText"]["name"]);
        $("#email").html(data["responseText"]["email"]);
        $("#photo").html(data["responseText"]["photo"]);
        $("#summary").html(data["responseText"]["summary"]);
        $("#url").html(data["responseText"]["url"]);
    }
});

The data being returned is encoded in JSON by the server (C#).

Obviously, data["responseText"]["fieldName"] isn't doing the trick. I could do splits and whatnot but that would mean that if the format changes, I'd need to make sure that the code above keeps up with the changed shape of the data.

How can I say something as simple as data["responseText']["fieldName"] to get the value out of that key?

Upvotes: 2

Views: 1907

Answers (2)

Suchit kumar
Suchit kumar

Reputation: 11859

try using like this:

complete: function (data) {
        var data=JSON.parse(data);
         $("#name").html(data.responseText.name);
        $("#email").html(data.responseText.email);
        $("#photo").html(data.responseText.photo);
        $("#summary").html(data.responseText.summary);
        $("#url").html(data.responseText.url);     

    }

to get only correct response use success.

Upvotes: 0

kpblc
kpblc

Reputation: 902

i think you need to parse json first. look at the api.jquery.com/jquery.parsejson

// data = '{ "name": "John" }'
var obj = jQuery.parseJSON( data );
console.log( obj.name);
// result will be "John"

P.S. also better use 'succes' instead 'complete', you can read about this here Difference between .success() and .complete()?

success: function(data) {
  console.log("response is good", data);
},
error: function (){
  console.log("something is went wrong");
}

Upvotes: 1

Related Questions