user3692432
user3692432

Reputation: 1

JavaScript/JQuery to retrieve JSON data from Web API

The output from the Web API is:

<string>[{"FNAME":"Prasy","LNAME":"San"}]</string>

And I need to retrieve FNAME from the API using JavaScript/JQuery.

I tried using the code below:

$(document).ready(function () {             
       $.ajax({
           type: 'GET',
           url: 'http://localhost:63456/api/LoginUser',
           data: { q: $(this).val(), format: 'json', pretty: 1 },
           jsonpCallback: 'jsonp',
           dataType: 'jsonp'
       }).then(function (data) {
           alert(FNAME);
       });
   });

I am using the below method in the APIController class

public string Userloginvalues()
    {

        List<LoginUser> objModel = new List<LoginUser>();
        OracleConnection con;
        OracleDataAdapter da;
        DataSet ds = new DataSet();
        con = new OracleConnection(ConfigurationManager.ConnectionStrings["ConString"].ToString());
        con.Open();
        da = new OracleDataAdapter("select FNAME,LNAME from ACCOUNTS where USERNAME=" + "'" + username + "'" + "  and PASSWORD=" + "'" + password + "'", con);
        da.Fill(ds);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            FNAME_C = dr[0].ToString();
            LNAME_C = dr[1].ToString();

            objModel.Add(new LoginUser{ FNAME = FNAME_C,LNAME = LNAME_C});
        }
        con.Close();

        string json = Newtonsoft.Json.JsonConvert.SerializeObject(objModel);
        return json;
    }

Upvotes: 0

Views: 412

Answers (2)

Chickenrice
Chickenrice

Reputation: 5727

Are you doing a cross-domain API invokation? I notice that you're using "JSONP" technique. Currently the output of the Web API is not valid for JSONP.

<string>[{"FNAME":"Prasy","LNAME":"San"}]</string>

It will cause the syntax error. Try to return valid JSON data with a function call wrapped around it.

callback({result:[{"FNAME":"Prasy","LNAME":"San"}]});

Let's make API return a proper response for JSONP :

Server side (PHP) :

<?php
  header("Content-Type: application/javascript");

  $callback = $_GET("callback");
  $data = '{result:[{"FNAME":"Prasy","LNAME":"San"}]}';

  echo $callback."(".$data.");";
?>

Server side (ASP.net):

public string Userloginvalues()
{

    List<LoginUser> objModel = new List<LoginUser>();
    OracleConnection con;
    OracleDataAdapter da;
    DataSet ds = new DataSet();
    con = new OracleConnection(ConfigurationManager.ConnectionStrings["ConString"].ToString());
    con.Open();
    da = new OracleDataAdapter("select FNAME,LNAME from ACCOUNTS where USERNAME=" + "'" + username + "'" + "  and PASSWORD=" + "'" + password + "'", con);
    da.Fill(ds);
    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        FNAME_C = dr[0].ToString();
        LNAME_C = dr[1].ToString();

        objModel.Add(new LoginUser{ FNAME = FNAME_C,LNAME = LNAME_C});
    }
    con.Close();

    string json = Newtonsoft.Json.JsonConvert.SerializeObject(objModel);

    if(!string.IsNullOrEmpty(Request.QueryString["callback"]))
    {
      json = Request.QueryString["callback"] + "("+json+");";
    }
    return json;
}

Client side

$.ajax({
  type: 'GET',
  url: 'http://localhost:63456/api/LoginUser',
  data: { q: $(this).val(), format: 'json', pretty: 1 },
  jsonpCallback: 'jsonp',
  dataType: 'jsonp'
}).then(function(data){
  alert(data.result[0].FNAME);
});

Upvotes: 0

Ninad
Ninad

Reputation: 433

Using Jquery you can do like this to get any field you want(using same format of data you are getting).

var $string=$('<string>[{"FNAME":"Prasy","LNAME":"San"}]</string>');
var jsonData=JSON.parse( $string.text());    
$(jsonData).each(function(i,val){
           console.log(val.FNAME);
})

Working fiddle http://jsfiddle.net/a8qWg/

Upvotes: 1

Related Questions