javascript - How to handle undefined response from AJAX call on Autocomplete box? -
i have following function:
function getgames(request) { //replace spaces '+' var url = request.term.replace(/\s/g,"+"); return $.ajax({ 'url': "php/gamescript.php?search=" + url, 'datatype': 'json' }).then(function(data){ return $.map(data.game || [], function(v,i){ return { label: v.gametitle + ' game (' + v.releasedate + ')', value: v.gametitle } }); }) }
and above it, code handles returned data:
function autocomplete() { $(".searchbox").autocomplete({ source: function(request, response) { $.when( getgames(request) ) .done(function(games) { var term = request.term.tolowercase(); var combine = games .map((v,i) => { //precompute such values if possible return { titlelowercase: v.value.tolowercase(), termoffset: (v.value.tolowercase().indexof(term)+1) || infinity, //and keep reference original data data: v } }) .sort((a, b)=>{ //sorton(termoffset asc, titlelowercase asc) return (a.termoffset - b.termoffset) || (a.titlelowercase !== b.titlelowercase && a.titlelowercase > b.titlelowercase? 1: -1) || 0; }) .map(v => v.data).slice(0, 15); response(combine); }); } }); }
my problem sometimes, search on gamescript.php return 'undefined', cause error: "uncaught typeerror: cannot read property 'tolowercase' of undefined"
what way handle error? tried doing simple approach:
return { label: v.gametitle + ' game (' + v.releasedate + ')', value: v.gametitle || " " }
which @ least makes code run, ends creating autocomplete suggestions 'undefined' label. tried write if statement in getgames function, struggle introducing new code without creating new errors it.
in case it's needed, gamescript.php code is:
<?php $xml_string = file_get_contents("http://thegamesdb.net/api/getgameslist.php?name=".$_request['search']); $xml = simplexml_load_string($xml_string); $json = json_encode($xml); $array = json_decode($json,true); echo $json; ?>
edit: i've tried code:
function getgames(request) { //replace spaces '+' var url = request.term.replace(/\s/g,"+"); return $.ajax({ 'url': "php/phpscript.php?search=" + url, 'datatype': 'json' }).then(function(data){ return $.map(data.game || [], function(v,i){ if( typeof( v.gametitle )!='undefined' ){ return { label: v.gametitle + ' game (' + v.releasedate + ')', value: v.gametitle } } }); }) }
edit: i've since realized if add alert(data.game.gametitle);
in getgames function, alerts title of game despite showing 'undefined' in autocomplete list. have no idea why happening... again, error occurs when search 'hunger'. other game queries i've tried, works fine.
Comments
Post a Comment