jquery - I'm having JavaScript issues making an API call and receiving the JSON response -


i'm hosting restful api on localhost when run in browser, returns this:

{    "contactmethod": "email",   "zip": "68504",   "state": "illinois",   "lastname": "mccarthy",   "besttimes": "afternoon",   "address": {     "zip": "68504",     "state": "illinois",     "city": "haylon",     "line1": "1388 dooleys terrace",     "line2": "",     "line3": ""   },   "bestdays": "wednesday",   "firstname": "roy",   "email": "rmccarthy@yah00.com",   "phone": "4812212563" } 

i can request either plain text or application json. api using type of json: http://json.org/example. please note above mocked data , nobody's actual contact information.

i have widget written in javascript , jquery 1.11.3, , i'd make request , consume json response.

i've tried this:

var getjson = function(url) {   return new promise(function(resolve, reject) {     var xhr = new xmlhttprequest();     xhr.open('get', url, true);     xhr.responsetype = 'json';     xhr.onload = function() {       var status = xhr.status;       if (status == 200) {         resolve(xhr.response);       } else {         reject(status);       }     };     xhr.send();   }); };  getjson('myurl').then(function(data) {   alert(data.result); 

the alert never occurs. i've tried this, here: http://www.w3schools.com/json/json_http.asp

function getuserdetails(){   var request = new xmlhttpreqest();   var url = "myurl";    request.onreadystatechange = function() {     if (request.readystate == 4 && request.status == 200) {       var myarr = json.parse(request.responsetext);       alert(myarr);     }   }   request.open("get", url, true);   request.send(); } 

that alert(myarr) never occurs, must wrong request, right? don't alert when try either:

function getuserdetails(){   $.getjson("myurl", function(result){     $.each(result, function(i, field){         alert(field);     })   }); } 

i've tried throwing in jquery.parsejson() here , there, no luck. team trying complete coworker wasn't able finish before leaving, , none of know javascript. we'd appreciate can get!

edit1: upon suggestions comments, checked request in chrome devtools. status 200 ok.

enter image description here

edit2: using this, able alert read [object object].

function getuserdetails(){   var data = $.getjson("myurl");   //var obj = $.json.parse(data);   //var obj = eval ("(" + data + ")");   alert(data);   return data; } 

in widget, it's giving gibberish:

enter image description here

so that's closer, right? when implement either of commented out lines, goes not working.

you not returning array. so, $.each makes no sense.

try this:

var url = "your_url";  function getuserdetails(){   $.getjson(url, function(result){         alert(result);   }) .fail(function( jqxhr, textstatus, error ) {     var err = textstatus + ", " + error;     console.log( "request failed: " + err ); })   .always(function() {alert( "complete" );}); } 

Comments