ajax call returning null - javascript

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>

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>

Pulling a Usable Link out of a JSON Object

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)
}
});

jQuery AJAX call freezes all other JS logic

I am trying to get a *.srt file and parse it with this script: Parse a SRT file with jQuery Javascript.
I've got a problem with the AJAX call blocking rest of the JS code. I tried to add syncs, set timeout, I wrapped it into a setTimeout function, tried with another *.srt file, but still it's not working. It doesn't throw error, it alerts end dialog, parsed lines are stored in variable but another scripts are frozen.
var subtitles = [];
$.ajax({
method: "GET",
url: '{% static "file.srt" %}',
async: true,
error: function(data) {
alert("error");
},
success: function(data) {
function strip(s) {
return s.replace(/^\s+|\s+$/g, "");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
srt = strip(srt);
var srt_ = srt.split('\n\n');
var cont = 0;
for (s in srt_) {
st = srt_[s].split('\n');
if (st.length >= 2) {
n = st[0];
i = strip(st[1].split(' --> ')[0]);
o = strip(st[1].split(' --> ')[1]);
t = st[2];
if (st.length > 2) {
for (j = 3; j < st.length; j++)
t += '\n' + st[j];
}
//define variable type as Object
subtitles[cont] = {};
subtitles[cont].number = n;
subtitles[cont].start = i;
subtitles[cont].end = o;
subtitles[cont].text = t;
document.body.innerHTML += " (" + subtitles[cont].start + " - " + subtitles[cont].end + " ) " + subtitles[cont].text + "<br>";
}
cont++;
}
alert("end");
},
timeout: 2000,
});
Please help me.

use ajax success:function(data) on document ready jquery function

I am loading responsive calendar in document ready :
eventList=disp();
$(".responsive-calendar").responsiveCalendar({
events:eventList //json object data
});
function disp(){
//getArr();
//alert(data1); //not working
stb = '{';
edb = '}';
dt = ["2015-09-13","2015-10-22","2015-10-02"]; // dynamically to be created from ajax data
ct = [2,5,6]; // dynamically to be created from ajax data
ev = dt.length;
var ddt = stb;
for(var i=0; i<ev;i++){
ddt += '"' + dt[i] + '":{"number":'+ct[i]+'},';
}
mString = ddt.substring(0,ddt.length-1)
ddt = mString+edb;
return JSON.parse(ddt);
}
function getArr() {
$.ajax({
url:"../JLRFile.php",
success:function(data) {
data1 = data;
}
});
}
Here in disp() I need dt and ct to load from ajax data function, can any one provide proper solution, I called ajax function in disp() but its not working.
Please provide proper solution
eventList = getArr();
$(".responsive-calendar").responsiveCalendar({
events: eventList //json object data
});
function disp(data1) {
alert(data1); //getting now
stb = '{';
edb = '}';
dt = ["2015-09-13", "2015-10-22", "2015-10-02"]; // dynamically to be created from ajax data
ct = [2, 5, 6]; // dynamically to be created from ajax data
ev = dt.length;
var ddt = stb;
for (var i = 0; i < ev; i++) {
ddt += '"' + dt[i] + '":{"number":' + ct[i] + '},';
}
mString = ddt.substring(0, ddt.length - 1)
ddt = mString + edb;
return JSON.parse(ddt);
}
function getArr() {
$.ajax({
url: "../JLRFile.php",
success: function (data) {
data1 = data;
disp(data1);
}
});
}

How to call ajax on fly for implementing pagination

I have the following javascript code having class named as PurchaseHistory.
var baseUrl = null;
var parameters = null;
var currentPageNumber = null;
var TotalPages = null;
var PageSize = null;
$(document).ready(function () {
baseUrl = "http://localhost/API/service.svc/GetOrderHistory";
parameters = '{"userId":1 , "page":1 ,"pageSize":4}';
currentPageNumber = 1;
var history = new PurchaseHistory();
history.ajaxCall(parameters);
});
function PurchaseHistory() {
/* On ajax error show error message
-------------------------------------------------*/
this.onAjaxError = function() {
$('#error').text('No internet connection.').css('color', 'red');
}
/* Ajax call
-------------------------------------------------*/
this.ajaxCall = function (parameters) {
$.support.core = true;
$.ajax({
type: "POST",
url: baseUrl,
data: parameters,
//dataType: 'json',
contentType: "application/json; charset=UTF-8",
error: function () { this.onAjaxError() }
}).done(function (data) {
var json = data.GetOrderHistoryResult;
var jsonObject = $.parseJSON(json);
var history = new PurchaseHistory();
history.populateOrderHistory(jsonObject);
TotalPages = jsonObject.PgCnt;
currentPageNumber = jsonObject.CrntPg;
});
}
this.populateOrderHistory = function(results) {
var rowOutput = "";
var his = new PurchaseHistory();
for (var i = 0; i < results.Results.length; i++) {
rowOutput += this.renderCartList(results.Results[i], 1);
}
}
this.renderCartList = function(res, i) {
var container = $('#prototype-listelement>li').clone();
container.find('.order-date').text(res.OdrDate);
container.find('.item-count').text(res.Qty);
container.find('.total').text(res.Amt);
container.find('.order-id').text(res.OdrId);
$('#mainul').append(container).listview('refresh');
}
this.loadNextPage = function () {
parameters = '{"userId":1 , "page":' + currentPageNumber + 1 + ',"pageSize":4}';
this.ajaxCall(parameters);
}
}
The ajaxCall is made on the ready function of the javascript.
This ajax calls returns Json object with pages information, which includes current page number, total pages and page size.
Currently I am able to display the information on the UI, when the page gets loaded.
My Issue:-
I want to call the ajax method again, on the button click event.
How this can be made possible and where can I store the information obtained from previous ajax call?
For pagination I would create a link that will load more items onto the page, and save a starting number to pass to your data layer. This example loads 20 at a time.
<a class="more" href="#" data-start="0">show more</a>
$("a.more").click(function(e){
e.preventDefault();
var start = $(this).attr('data-start');
$.get('/more-data, { start: start }, function(d){
var next = start+20;
$("a.more").attr('data-start', next);
//process results here, do something with 'd'
});
});

Categories