jquery check json data - javascript

I am using the google news search api and get back data in json format. I am using ajax to get the data and parse through it.
This is my code:
function doAjax(query){
alert(query);
var target = "https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q="+query+"&rsz=large";
$.ajax({
url: target,
cache: false,
dataType:'jsonp',
success: function(data) {
//alert(data.responseData.results);
for(var x = 0; x < 8; x++){
var title = data.responseData.results[x].titleNoFormatting;
//var content = data.responseData.results[x].content;
//var image = data.responseData.results[x].image.url;
$("#home").append(x+"---"+title+'<hr>');
}
},
error: function(jxhr,e){
alert(jxhr.status+" --- "+e.responseText);
}
});
}
When I run the code this way I get 8 titles. but when I uncomment this line var image = data.responseData.results[x].image.url; I get 3 or 4 results only. I investigated the data being retrieved from google I found that some results has no images. How can I check the json result if it has an image. I still want to display the title of the article even if there was no image.

you should check the image exists before get it's url
if(typeof(data.responseData.results[x].image) == "undefined"){
alert('no image');
}else{
var image = data.responseData.results[x].image.url;
}

What does the response look like? Most browsers have developer tools that will let you see the requests and response. Likely, your loop is choking because data.responseData.results[x].image is undefined so data.responseData.result[x].image.url throws a type error (undefined doesn't have a url property).
To guard against this, just check for it like this:
if(data.responseData.result[x].image) {
var image = data.responseData.result[x].image.url;
}
If data.responseData.result[x].image is undefined then it will evaluate as falsey and the body of the if won't be executed (and won't throw an error that breaks you out of the function).

You can check for image like
if (typeof data.responseData.image != 'undefined' && typeof data.responseData.image.url != 'undefined' ) {
// set the image here
}

Typeof can be used to determine if a variable is defined or not.
Example
var var_one = "";
alert(typeof var_one); // alerts "string"
alert(typeof var_two); // alerts "undefined"
alert(typeof var_two == "undefined"); // alerts "true"
So you can specify:
if (typeof var_two != "undefined")
{
alert("variable is undefined!");
}
else
{
alert("variable is defined... use it!");
}
Taking the above into account, you could do:
var image = "";
if (typeof data.responseData.results[x].image.url != "undefined")
{
image = data.responseData.results[x].image.url;
// You can then specify where the image url will go.
}

Related

AngularJS: HTTP request is not responding after page is fully loaded

I have an invoice page all values are based on AngularJS ng-models (variables) so they are dynamic.
When I change text field DISCOUNT, all values change according to discount value (also call function abc repeatedly). This was working fine.
But now I have created a new function loadadditionalvalues inside function abc and request an HTTP call. First time this function work properly. However, when I type something in discount field, it requests, but never responds and gets hanged at my new function loadadditionalvalues.
function abc(){
$scope.loadadditionalvalues = function (n,o,scope)
{
arr=[];
$scope.isAppInitialized = false;
var requestUrl = 'page_test.php?do=action_netvalues&action=ID' ;
$http({
url: requestUrl,
method: 'GET'
}).then(function(response){
if(typeof response.data.ERROR_MSG !== 'undefined' || typeof response.data !== 'object' || typeof response.data.message !== 'undefined' || (typeof response.data.success !== 'undefined' && !response.data.success))
{
console.log("error ");
}
else
{
$scope.staffel_liste =response["data"];
}
});
};
$scope.loadadditionalvalues(null,null,scope);
}

Multiple arrays in javascript doens't work passing values

I'm trying to create a multidimensional arrays in JS like this:
On my app.js file I have this
var equipValue = new Array();
var selectedTrucks = new Array();
In my function.js file instead I have:
for (var i in selectedTrucks) {
(function(i){
// Simple Ajax request that return me a Json values
var ajaxUrl = '/ajaxRequest/getSingleTruckPosition/' + selectedTrucks[i];
$.ajax({
url: ajaxUrl,
})
.done(function(data) {
if(data != null){
// equipValue doens't go.
// Unable to set property '0' of undefined or null reference
equipValue[i] = jQuery.parseJSON(data);
}
});
Why I obtain: Unable to set property '0' of undefined or null reference ?
Why that variables doens't work on my function.js file but selectedTrucks work perfectly?
Thanks guy
EDIT
Doing some test I've tried this:
equipValue = jQuery.parseJSON(data);
So, the problem isn't scoope but create multidimensional array on Runtime? Or similar?
** EDIT 2**
Here the problem:
var selectedTrucks = new Array();
// other 15 lines of codes and then this:
if(selectedTrucks === undefined || selectedTrucks.length == 0){
cleanMapMarkers();
}
Why cleanMapMakers() is always launched even when selectedTrucks is empty?? All problems that I've found is here.
Thanks
Update : seems equipValue is changed, or overwritten to a different type, somewhere else.
In your code, maybe you're looking for, if selectedTrucks is undefined OR if it's not empty
if(selectedTrucks === undefined || selectedTrucks.length != 0){
cleanMapMarkers();
}
jQuery.parseJSON() parses json text to an object, but the callback already returns an object
.done(function(data) {
if (data != null) {
equipValue[i] = data;
http://jsfiddle.net/dw74gk7j/
for var i in *object*
is used to iterate over an object properties.
So in equipValue[i] you seems to have equipValue['131-00004131'] which is
equipValue = {
131-00004131: 'your data'
}

Javascript google api call - How to add "url missing" to json obj if no picture url in response

I am trying to get the url value of a user account on google drive.
I have successfully achieved this however, I believe that if there is no picture set then the response from my api call is that it will send me the object without the URL inside.
Here is the response.
"lastModifyingUser": {
"kind": "drive#user",
"displayName": string,
"picture": {
"url": string
},
output:
Without display pic?
drive#user
#Hidden Name
true
#Hidden ID
With display pic?
drive#user
#Hidden Name
#HIDDEN URL <-- Missing
false
#Hidden ID
Anyways, I was wondering if I was able to determine the size of json objects in javascript and IF the url is missing, I would still like "URL Missing" in my imageDateObj.
Here is my code
var id = resp.id;
var obj = resp.lastModifyingUser;
for(var k in obj) {
var value = obj[k];
if (typeof value === 'object') {
for (var k2 in value) {
var value2 = value[k2];
console.log(value2); //value 2 is the url
imageDateObj[id] = value2;
}
} else if(typeof value === 'undefined'){
console.log("url missing"); //not working
}
else {
console.log(value);
}
}
In other words, if Url is mising, add to
imageDateObj[id] = "url missing"
Ok I sorted it.
I added this
var count = Object.keys(obj).length
console.log(count);
if(count == 4){
imageDateObj[id] = "Url missing";
}

Getting URL data with JavaScript (split it like php $_GET)

I found this script at Stack Overflow:
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
This splits a URL into data, like PHP does with $_GET.
I have another function, which uses it and it refreshes the iframe. I want to get the data from the URL and add another with it if some of these data exist. Firebug shows me, that search is not defined, but why?
function RefreshIFrames(MyParameter) {
var cat = window.params.cat;
var category = window.params.category;
var search = window.params.search;
if (search.length>0 && category.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search="+search+"&category="+category+"&rendez="+MyParameter;
}
if (cat.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat="+cat+"&rendez="+MyParameter;
}
if (cat.length==0 && category.length==0 && search.length==0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez="+MyParameter;
}
alert(window.location);
}
If you want to add rendez OR change the existing rendez, do this - I am assuming the URL is actually beginning with http://siriusradio.hu/kiskunfelegyhaza/video/index.php so no need to create it. Let me know if you need a different URL than the one you come in with
The parameter snippet did not work proper (for in should not be used on a normal array)
Here is tested code
DEMO
DEMO WITH DROPDOWN
function getParams(passedloc){
var params = {}, loc = passedloc || document.URL;
loc = loc.split('?')[1];
if (loc) {
var param_array = loc.split('&');
for(var x,i=0,n=param_array.length;i<n; i++) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
}
return params;
};
function RefreshIFrames(MyParameter,passedloc) { // if second parm is specified it will take that
var loc = passedloc || document.URL; //
window.param = getParams(loc);
loc = loc.split("?")[0]+"?"; // will work with our without the ? in the URL
for (var parm in window.param) {
if (parm != "rendez") loc += parm +"="+ window.param[parm]+"&";
}
// here we have a URL without rendez but with all other parameters if there
// the URL will have a trailing ? or & depending on existence of parameters
loc += "rendez="+MyParameter;
window.console && console.log(loc)
// the next statement will change the URL
// change window.location to window.frames[0].location to change an iFrame
window.location = loc;
}
// the second parameter is only if you want to change the URL of the page you are in
RefreshIFrames("rendez1","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat=cat1&search=search1");
RefreshIFrames("rendez2","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search=search2");
RefreshIFrames("rendez3","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez=xxx&search=search2");
RefreshIFrames("rendez4","http://siriusradio.hu/kiskunfelegyhaza/video/index.php");
// here is how I expect you want to call it
RefreshIFrames("rendez5"​); // will add or change rendez=... in the url of the current page

XMLHttpRequest Error Checking- Better way to write this?

I wrote a webpage that runs from the desktop to grab information off of a public website. I am trying to make it to where 1) if there is no internet connection there is a alert 2) if there is a an internet connection but somehow the info was not retrieved correctly, the user would be alerted.
The try and catch works for the test if there is no internet connection.
I am using the xml.status codes for the second test...if the website is active but the info that is pulled is messed up....that test condition isn't working the way I wanted it. I tried giving the xml.open a bogus website and was expecting a non 200-300 status code. But it did not work...instead the catch statement was activated. Why is this? And is there a better way to write this?
Also, on a side note I had return ""; because I the calling variables that use this could not be have null or undefined: variable = getInfo(); n.setAttribute("placeholder", variable);
function getInfo() {
var xml = null;
xml = new XMLHttpRequest();
try {
xml.open("get", "http://example.asp", false);
xml.send(null);
if ((xml.status >= 200 && xml.status <= 300) || xml.status == 304) {
var hi = xml.responseText;
hi = hi.replace(/(\r\n|\n|\r)/gm, "");
var what1 = /winning_number_sm.*?ul/
var what2 = /\d+/g
hi = what1.exec(hi);
var temp;
for (i = 0; i < 6; i++) {
if (null !== (temp = what2.exec(hi))) {
numbers[i] = temp;
}
}
return numbers;
} else {
alert("Error Connecting to Website! You will have to eneter informatin by hand");
return "";
}
} catch (e) {
alert("No Internet Connection! You will have to enter information by hand");
return "";
}
}
I don't know if you can use jQuery framework but to get error from an ajax connection (test if a website is up) you can do easely that :
//your ajax object
var request = $.ajax({
url: "http://www.exemple.com/script.php",
type: "POST",
data: {/*your datas*/},
dataType: "html"
});
request.done(function(msg) {
//make your stuff automatically
});
request.fail(function(jqXHR, textStatus) {
alert( "Error Connecting to Website! You will have to enter informatin by hand");
});
An other approch can be to call a local php script whose test distant url with curl function (ex : http://www.php.net/manual/en/function.curl-error.php)

Categories

Resources