Pulling a Usable Link out of a JSON Object - javascript

I need to figure out how to have a link that I pull from a JSON object an ACTUAL link that the user can click and follow to the site instead of just text. I feel like it's gotta be a quick fix, but I can't seem to figure it out! Thanks for the help!!
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function(response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals[i].deal.untracked_url'>" + deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
})
};

Assuming your fetched data is correctly used, here's why your link doesn't work : the href is actually deals[i].deal.untracked_url instead of its content.
try this instead :
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $('' + deals[i].deal.untracked_url + "");
couponInfo.append(newUntrackedURL)
}
})
};
Without the generated JSON, I can't help you further if this solution doesn't helps.

Look like maybe you had a typo:
'deals[i].deal.untracked_url' should be 'deals["+ i +"].deal.untracked_url'
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals["+ i +"].deal.untracked_url'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});
Scratch that - you want it to pull the value not write out "deals[i].deal.untracked_url." To do that you do the below.
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='"+deals[i].deal.untracked_url+"'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});

Related

Image source shows up as undefined in IE but works in Chrome

I am trying to display several images(PrinurlonPage) that are contained in an array and also position them on the page randomly. I have two issues,
The first and most important is that I cant get the images to display on IE when I look the source attribute on developer tools I just see undefined whereas in chrome I get the full URL that was passed. I was wondering if there was something wrong with the order in which the script was being run that was causing the problem.
The second question is about positioning the images randomly on the page and also prevent overlapping, I would like to know how can I achieve this, what I have implemented at the moment in some iterations the pictures overlap.
I would appreciate any suggestion on this
var getIndividualPersonDetails = function(GetPictureUrl, printurlonPage, getRandom) {
listName = 'TeamInfo';
var PeopleCompleteList = [];
var personName, userName, UserTitle, UserphoneNumber, UserEmail, Id, myuserPicture;
// execute AJAX request
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=Name/Title,Name/Name,Name/Id,Name/EMail,Name/WorkPhone&$expand=Name/Id",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function(data) {
for (i = 0; i < data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if (data.d.results[i]['Name'] != null) {
personName = data.d.results[i]['Name'].Name.split('|')[2];
userName = data.d.results[i]['Name']['Name'];
UserTitle = data.d.results[i]['Name']['Title'];
UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
UserEmail = data.d.results[i]['Name']['EMail'];
Id = data.d.results[i]['Name']['Id'];
myuserPicture = GetPictureUrl(userName);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber, UserEmail, myuserPicture, Id));
}
}
PeopleObject = PeopleCompleteList;
PrinturlonPage(PeopleCompleteList, getRandom);
},
error: function() {
alert("Failed to get details");
}
});
}
//print all the image links in the peopleCompleteList array and then position them randomly on the page
var PrinturlonPage = function(PeopleCompleteList, getRandom) {
var imageList = [];
for (i = 0; i < PeopleCompleteList.length; i++) {
var top = getRandom(0, 400);
var left = getRandom(0, 400);
var right = getRandom(0, 400);
imageList.push('<img style="top:' + top + ';right:' + right + '" id="image' + PeopleCompleteList[i]['UserId'] + '" alt="' + PeopleCompleteList[i]['Title'] + '"class="imgCircle" src="' + PeopleCompleteList[i]['Picture'] + '"/>');
//imageList +='<img class="img-circle" src="'+PeopleCompleteList[i]['Picture']+ '"/>'
}
var imagesString = imageList.join().replace(/,/g, "");
$('#imageList').append(imagesString);
}
//funtion retrieves the picture
function GetPictureUrl(user) {
var userPicture="";
var imageurls="";
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v='"+encodeURIComponent(user)+"'";
$.ajax({
url: requestUri,
type: "GET",
async:false,
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
console.log(data);
var loginName = data.d.AccountName.split('|')[2];
console.log(loginName);
var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'https://xxxcompany/User%20Photos/Profile%20Pictures/zac_MThumb.jpg?t=63591736810';
imageurls = data.d.PersonalSiteHostUrl+'_layouts/15/userphoto.aspx?accountname='+ loginName+ '&size=M&url=' + data.d.PictureUrl;
userPicture1=imageurls;
}
});
return userPicture1;
}
var getRandom = function(x, y) {
return Math.floor(Math.random() * (y - x)) + x + 'px';
};
$(function() {
getIndividualPersonDetails(GetPictureUrl, PrinturlonPage, getRandom);
$(document).on('click', '.imgCircle', function() {
var theName = jQuery(this).attr('Id');
pullUserObject(theName);
//console.log(theId);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imageList"></div>

ajax call returning null

I have this small script (fiddle) in charged for reading some blog XML. The problem is that it simply stopped working a few days ago. It seems the Ajax function is always returning null, even though there is data in the specified URL.
<script>
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
var buildRSS = function (container_id){
$.ajax({
type: "GET",
url: "http://bloginstructions.blogspot.dk/rss.xml",
dataType: "xml",
success: function(result){
var values = getEntries(result)
console.log(result)
for (var i = 0; i < 10; i++) {
var entry = values[i],
info = entry.__text.split("\n"),
title = info[0],
link = info[1],
date = entry.pubdate.match(/(.*) \d/)[1],
snippet = entry.description.replace(/<\/?[^>]+(>|$)/g, "").substring(0,350)+'...';
var html = '<div><h4>' + title + '</h4><p>' + date + '</p><p>' + snippet + '</p></div>'
$('#' + container_id).append(html)
}
}
})
}
function getEntries(rawXML){
var x2js = new X2JS();
console.log(rawXML);
var xml = rawXML.responseText;
match = xml.match(/<item>(.*)<\/item>/);
xml = match[0] || '';
var json = x2js.xml_str2json(xml);
json = json.rss.channel.item;
return json
}
</script>
<div id="rssfeed">
</div>
<div id="rss">
</div>
<script>
$(document).ready(function() {
buildRSS('rssfeed')
});
</script>

Uncaught TypeError: Cannot read property 'HotelInfo' of undefined

//an ajax call to the api
jQuery(document).ready(function() {
jQuery.ajax({
url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&theme=%22food%22",
dataType: 'JSON', type: 'GET',
success: function (data)
var viewModel;
if(data) {
viewModel = new dealsPageModel(data);
var idList = "";
for (var i = 0; i< data.packageDeal.length; i++)
{
if (i == data.packageDeal.length -1)
{ idList += data.packageDeal[i].hotelId;
}
else
{idList += data.packageDeal[i].hotelId + ',';
}
}
var searchUrl = "http://terminal2.expedia.com/x/hotels?hotelids=" + idList + "&apikey=6weV4ksGIJ5eQhd58o2XTDwVo35lZf2S";
//another call to another api to return hotel specific info
jQuery.get(searchUrl, function ( )
{
for(var i=0; i<viewModel.dealList.length; i++)
{
var hotelId = viewModel.dealList[i].hotelId;
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = HotelInfoList.HotelInfo[i].Name;
}
// Get the hotelid from the current deal
// Loop through the hotelinfolist.hotelInfo and find out the url for the hotel idList
//Loop through the hotelinfolist.hotelInfo and find out the name for the hotel
viewModel.dealList.push(new deal(data.packageDeal[i], url, name));
}
ko.applyBindings(viewModel);
});
}
}
})
});
You loop through data.HotelInfoList.HotelInfo but operate on HotelInfoList.HotelInfo[i].ThumbnailUrl. The data. at the beginning is missing.
Also, place data in the callback function in jQuery.get:
jQuery.get(searchUrl, function(data){
// …
your data is in data.HotelInfoList not in HotelInfoList
your loop should be like this
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = data.HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = data.HotelInfoList.HotelInfo[i].Name;
}

Get closest elments of corresponding list of elements in javascript/jquery

I have a list of elements:
var checked_inputs = $('.select-feedback:checked');
Now i want to get their closest division element whose class is 'MessageRow'. I have done this trick to get it:
$('.radiusRight').click(function(event) {
event.preventDefault();
var feedbacks = new Array();
var checked_inputs = $('.select-feedback:checked');
for (var i=0; i<checked_inputs.length; i++) {
feedbacks.push($(checked_inputs[i]).closest('.messageRow').attr('id'));
}
var feedback_ids = feedbacks.map(function(val) { return val.split('-')[1] });
var feedback_divs = feedbacks.map(function(val) { return '#' + val }).join(',');
$.ajax({
url: '/business/feedback/delete/',
type: 'POST',
data: {'ids': feedback_ids},
success: function(data) {
$(feedback_divs).fadeOut();
}
})
})
Is there any better way to accomplish this? Or is this a good way? Thanks in advance.
Your way is a little bit complicated - imho...
$('.radiusRight').click(function(event) {
event.preventDefault();
var feedback_ids = $(".select-feedback:checked").map(function() {
var id = $(this).closest(".messageRow").attr("id");
return id.split("-")[1];
});
$.ajax({
url: "/business/feedback/delete",
type: "POST",
data { "ids": feedback_ids },
success: function() {
$("#" + feedback_ids.join(", #")).fadeOut();
}
});
})

jquery problem in IE with dynamic dropdown selection

Hi jquery/javascript gurus,
I am trying to use jquery ajax function to populate the dropdown, it works fine with FF, but IE give the javascript error snow below in the scrnshot. howver IE does get the data and selects it.
Am i doing something wrong?
function getAjaxFunction(thisval, curval) {
$.ajax({
type: "POST",
url: "lookup.do?param="+thisval,
cache: false,
success: function(data) {
var values = data;
var vals = values.split(";");
$("#dropdown").find("option").remove().end();
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
$("#dropdown").append($('<option />').val(parts[0]).text(parts[1]));
}
$("#dropdown").val(curval);
}
});
}
You say val(curval) at the end of your function, but your function parameter is named currval with two Rs.
This worked!
function getAjaxFunction(thisval, curval) {
$.ajax({
type: "POST",
url: "lookup.do?param="+thisval,
cache: false,
success: function(data) {
var values = data;
var vals = values.split(";");
$("#dropdown").find("option").remove().end();
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
$("#dropdown").append($('<option />').val(parts[0]).text(parts[1]));
}
try {
$("#dropdown").val(curval);
} catch(ex) {
setTimeout("$('#dropdown').val('"+curval+"')",1);
}
}
});
}

Categories