Garrith Graham Garrith Graham - 4 months ago 9
jQuery Question

undefined value returned using jquery and web api

I changed from searching an ID to searching a name and for some reason the below is returning an undefined value.

var uri = 'http://localhost:11313/api/Mountains?name=';

function formatItem(item) {
return item.Latitude +', '+ item.Longitude;
}

function find() {
var search = $('#MountID').val();
$.getJSON(uri + search)
.done(function (data) {
$('#mountain').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#mountain').text('Error: ' + err);
});
}


This however works fine?

var uri = 'http://localhost:11313/api/Mountains'; //changed

function formatItem(item) {
return item.Latitude +', '+ item.Longitude;
}

function find() {
var search = $('#MountID').val();
$.getJSON(uri + '/' + search) //changed
.done(function (data) {
$('#mountain').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#mountain').text('Error: ' + err);
});
}


Is there a reason this path works
var uri = 'http://localhost:11313/api/Mountains';
and this does not
var uri = 'http://localhost:11313/api/Mountains?name=';
?

I can access
var uri = 'http://localhost:11313/api/Mountains?name=';
with a name on the end from my browser just fine?

<Mountain>
<Height_ft>2953</Height_ft>
<Height_m>900</Height_m>
<ID>c21</ID>
<Latitude>57.073142</Latitude>
<Longitude>-3.3310457</Longitude>
<Name>Culardoch</Name>
<humidity>0.42</humidity>
<snowCover>1.84</snowCover>
<temperature>66</temperature>
</Mountain>


I get a status 200 ok and I get a respone from the actual search when I click the button:
enter image description here

[ResponseType(typeof(Mountain))]
public IHttpActionResult GetMountain(string id)
{
Mountain mountain = db.Mountains.Find(id);
if (mountain == null)
{
return NotFound();
}

return Ok(mountain);
}


public IQueryable<Mountain> GetMountainByName(string name)
{
return db.Mountains.Where(n => string.Equals(n.Name, name));
}

Answer

You'll have to index the data array (I know that's obvious, but I seen op question in the comments) using [ and ], declaring the number 0:

E.g:

data = data[0];

Do that inside your done function, then it's done. Like so:

                $.getJSON(uri + search)
                    .done(function (data) {
                        data = data[0];
                        $('#mountain').text(formatItem(data));
                    })

(yeah, I thought you had solved it)