deerox
deerox

Reputation: 1055

Reading values in html (response) with Ajax

I get this html as response when i post api call, so i want to know how i can read client_id and session_token with jquery or some simple javascript code??

function getNewsFeed(d) {
    var c = {
        page_num: b,
        num_events: d,
        return_as_html: true,
        source: "web"
    };
    TAGGED.api.call(c, check)
}

Now want to check things:

function check() {
    // checking here
}

["{\"stats\":\"ok\",\"dia\":\"44\",\"result\":{\"success\":true,\"session_token\":\"969ndg1ai0c43034\",\"next_event_id\":0,\"client_id\":1314852}}"]

I dont have JSON so cant read it with JSON.parse i tried using but in firebug it does not show JSON

i get same code in response and html when i check it with firebug.

Thanks.

Upvotes: 1

Views: 390

Answers (1)

Billy Moon
Billy Moon

Reputation: 58531

If you can be sure there are not going to be certain special characters in your values, you can split by comma, then by colon, and strip out non-matching characters...

str = '["{\"stats\":\"ok\",\"dia\":\"44\",\"result\":{\"success\":true,\"session_token\":\"969ndg1ai0c43034\",\"next_event_id\":0,\"client_id\":1314852}}"]'

// replace all characters that are not letters, numbers, underscore, colon or comma
str = str.replace(/[^a-zA-Z0-9_:,]/g,'')

// get array of key value pairs
all = str.split(',')

// create empty opts object to store final data
opt = {}

// loop through array of key value pairs
for(i in all){

    // split into key value array
    bits = all[i].split(/:/)

    // assign to opt object
    opt[bits[0]] = bits[1]

}

// access values vie keys of opt
alert(opt.client_id+": "+opt.session_token)

Upvotes: 2

Related Questions