basically what I want to do is grab 5 images from the RSS feed and display them afterwards. Unfortunately the RSS items don't have links to images so what I do is grab the article URL from the RSS feed and then I use YQL to scan through the article to see if there is an image. The articles may or may not have an image and there can be 10 or more articles so I have to have a counter to determine when I get 5 images. That's where I'm having the problem, I can't figure out how to update the counter in the success part of the ajax call (I have also tried using an array but it didn't work).
I have seen other examples and I've been trying to do this since yesterday but I have had no luck. Maybe there are other easier ways to do this but I have no clue. Any help would be greatly appreciated.
Please see my code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>La Retama</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).bind('mobileinit',function(){
$.mobile.changePage.defaults.changeHash = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link rel="stylesheet" href="./my_style.css">
</head>
<body>
<div id="home" data-role="page" >
<div id="my_header" data-role="header">
<h1>Insert Page Title Here</h1>
</div>
<div data-role="main" class="ui-content">
</div>
<div id="my_footer" data-role="footer" data-position="fixed">
<h1>Insert Footer Text Here</h1>
</div>
</div>
</body>
<script>
var pagina7Arr = [];
var pagina7SSPArr = [];
/*Getting the RSS feed*/
$.ajax({
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('http://web.paginasiete.bo/rss/feed.html?r=77'),
dataType : 'jsonp',
success : function (data) {
var myObject = data.responseData.feed.entries;
var how_many = 0;
for (var i=0; i < myObject.length;i++){
var article_url = myObject[i].link;
var YQL_link = checkPagina7URL(article_url)
var YQL = "https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20data.html.cssselect%20WHERE%20url%3D'"+YQL_link+"'%20AND%20(css%3D'.fotoNota-ext%20'%20OR%20css%3D'.fotoNota')&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
pagina7Arr.push(YQL)
}
pageImages(pagina7Arr)
}
});
/* Here is where I want to store the 5 images */
function pageImages(input){
var module = 0;
var testarr=[];
for (var i=0; i<input.length; i++){
$.ajax({
url: input[i],
dataType : 'jsonp',
success : function (data) {
/*I would like to update a counter here or insert images to an array I can use later on*/
try{
testarr.push(data.query.results.results[0].div.img.src);
}catch(err){
try{
testarr.push(data.query.results.results[1].div.img.src);
}catch(err){
}
}
}
});
console.log("array: "+testarr.length)
}
}
/*Formatting the page URL to insert into YQL call*/
function checkPagina7URL (data){
data = data.substr(data.indexOf('.bo')+4,data.length);
var section = data.substr(0, data.indexOf('/'));
data = data.substr(data.indexOf('/')+1,data.length)
var year = data.substr(0,data.indexOf('/'))
data = data.substr(data.indexOf('/')+1,data.length);
var month = data.substr(0,2);
if(month.indexOf('/') != -1){
month = data.substr(0,1);
}else{
month = data.substr(0,2);
}
data = data.substr(data.indexOf('/')+1,data.length);
var day = data.substr(0,2);
if(day.indexOf('/') != -1){
day = data.substr(0,1);
}else{
day = data.substr(0,2);
}
data = data.substr(data.indexOf('/')+1,data.length);
var page_link = data.substr(data.indexOf('/')+1,data.length);
var result = "http%3A%2F%2Fwww.paginasiete.bo%2F"+section+"%2F"+year+"%2F"+month+"%2F"+day+"%2F"+page_link;
return result;
}
</script>
</html>
When you make $.ajax({}) call, the success is called asynchronously. So when you are calling this line:
console.log("array: "+testarr.length)
It is too early to count the images, so what is happening here is that you are calling ALL the pages, and fetching the images for all of them. You can certainly do that, but then you have to stop calling testarr.push after your counter becomes >=5. (The counter check should be just before you make such push call)
A more efficient way, would be to fetch only what you need (though will be slower due to syncronousity) and that is by only making subsequent url calls from within the success function of previous call. The above should be easy to do.
You can also do more fancy work (though trickier to code), doing hybrid, fetching 5 urls async, then see in the success callback if you got 5 images you stop, if not, make (5-counter) async requests of the remaining page urls.
Related
function createPost(){
$('#body').append("<p>Welcome to calmspace.</p>");
}
How would I utilize user input so the user can create a post with their own message? I am a newbie with jQuery so if this is a stupid question please forgive me. Possible duplicate but I couldn't find another post like this.
First things first - you should not have added '#' in front of body, it'd mean that the body element is of id 'body', assigning id to an element that is unique does not bear that much sense, instead you should just target the tag - $('body').
In order to provide some sort of message you first have to capture it, for instance using some sort of input. Here is a working demo.
$('#submit').click(function(){
createPost($('#text').val());
})
You read it as follows, grab element of id 'submit', assign it a click event, grab the value of input box of id 'text' and pass it to a function named create post which accepts a string parameter and then prints it in a <p> tag.
#Simion Benderschii a working example of a post which appends to the document or sends via ajax. Hope this helps
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<div>
<h2>Enter your post here</h2>
<form>
<textarea id='user-input-post'></textarea>
<div>
<button id=user-post-button>Post</button>
</div>
</form>
</div>
<div>
<h2>Below are your posts</h2>
<ul id='user-post-display'>
</ul>
</div>
</body>
<script>
/*possible options can be
'display' - which shows the post in the UI in a unordered list
'ajax' - which send the post to the server via ajax
*/
var post_type = 'display';
//the id of the list where the post will be appended
var list_id = '#user-post-display';
//the id where the post will be entered
var post_id = '#user-input-post';
//the id of the button which triggers some action
var button_id = '#user-post-button';
//this gets the post from the textarea
var get_post = function() {
var post = $(post_id).val();
return encodeURIComponent(post);
};
//this appends the post to the list
var append_post = function() {
var post = get_post();
var html_string = '';
if (post) {
html_string = '<li>' + post + '</li>';
$(list_id).append(html_string);
}
};
//this sends the post via ajax and triggers callbacks
var send_post = function() {
var post = get_post();
var post_created_on = Date.now();
var url = 'dummy_url_for_posting';
$.ajax({
method: 'POST',
url: url,
data: { data: {
post: post,
post_created_on: post_created_on
}}
})
.done(function() {
window.alert('post success');
})
.fail(function() {
window.alert('post fail');
})
.always(function() {
window.alert('post triggered');
});
}
//main function which is the entry point
var main = function() {
$(button_id).on('click', function() {
event.preventDefault();
debugger;
if (post_type === 'display') {
append_post();
} else if (post_type === 'ajax') {
send_post();
}
});
};
//triggers the main function
main();
</script>
</html>
I am not exactly sure what you want to do from your question. In future questions you will find it helpful to provide more detail on exactly what you want to do with your application or function.
The basic idea here is to use a button or any action you can capture with jQuery (like pressing enter or checking $(element).on('click',... and then putting that info where you want using $(element).html(...) or .append(...).
Here is a fiddle I made with the rough idea. Try to use this fiddle tool a lot, and you can also post the link to what you have tried in future questions. Good luck :-)
JSFiddle example of submitting a post
I am pulling data via a CRM API and successfully rendering that data in the front end of my Google Script web app. But manipulating or formatting this data for the front end is a challenge for me.
In the code below, the Potential Name on the second line is rendering the correct data to the page. But the first line called Quote is showing undefined. This data is the data I am trying to format so that only the last six characters or the string are printed to the page.
Clearly, I must be trying to access the data from the API incorrectly. Could someone please provide me with the correct way to manipulate this data in Google Scripts?
Code.gs
function doGet() {
var templ = HtmlService.createTemplateFromFile('Allied-po');
templ.data = requestRecordFromCRM();
return templ.evaluate()
.setTitle('Purchase Order')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
/*Fetch record data from CRM*/
function requestRecordFromCRM() {
requestedId = '1234';
var authToken = 'XXXX';
var zohoRequestUrl = 'https://crm.zoho.com/crm/private/json/Potentials/getRecordById?&authtoken=' + authToken + '&scope=crmapi&id=' + requestedId;
var response = UrlFetchApp.fetch(zohoRequestUrl);
var sanitizedResponse = (response.getContentText());
/*Sanitize json*/
var output = JSON.parse(sanitizedResponse);
Logger.log(output);
/*Declare the variables you want to print*/
var parsedOutput = output.response.result.Potentials.row.FL;
var recordObj = {}
Logger.log(typeof output)
Logger.log(output.response.result.Potentials.row.FL.length)
for (var i = 0; i < output.response.result.Potentials.row.FL.length; i++) {
if (output.response.result.Potentials.row.FL[i].val == 'Potential Name') {
recordObj.potentialName = output.response.result.Potentials.row.FL[i].content
}
}
return (recordObj);
}
Index.html
<html>
<head>
<base target="_blank">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Purchase Order</title>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<div>
Quote: <span id="job-number"><?= data.potentialName ?></span>
</div>
<div>
Potential Name: <?= data.potentialName ?>
</div>
<?!= HtmlService.createHtmlOutputFromFile('Javascript').getContent(); ?>
</body>
</html>
Javascript.html
<!-- Load jQuery, jQuery UI, and Bootstrap libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
//Format Job Numbers - return only last six characters in potentialName string
(function() {
var parts = document.getElementById('job-number');
var selectedPart = parts.split(":");
var thePart = selectedPart[0];
return (thePart);
}());
</script>
This particular code retrieves the HTML element but not the innerHTML text
var parts = document.getElementById('job-number');
Instead do this to get the embedded HTML which can used to split the string like so:
var parts = document.getElementById('job-number').innerHTML;
The final code will look like this:
<script>
//Format Job Numbers - return only last six characters in potentialName string
(function() {
var parts = document.getElementById('job-number');
var selectedPart = parts.innerHTML.split(":");
console.log(parts)
console.log(selectedPart)
var thePart = selectedPart[1];
parts.innerHTML = thePart
return (thePart);
}());
</script>
There is limited information on how the object structure looks like? The assumption here is there is six character before ":" in the data.potentialName value. if you rather want exactly six characters you can do this:
var selectedPart = parts.subString(0,6)
Hope that helps!
<html>
<head>
<script type="text/javascript">
function open_urls() {
var url1="https://finance.yahoo.com/";
var newpage=window.open(url1);
alert(newpage.document.body.innerText.split(' ').length);
}
</script>
</head>
<body onload="javascript: open_urls()"></body>
</html>
The code above did not work, how to access DOM for a different URL?
I'd like to open an URL and show the word count of that URL.
You can't simply open another window and page and expect to have access to it. The web follows many security policies to prevent operations like this, such as the Same-Origin policy. Long-story short, you can't access URLs that don't fall under the same-origin as the page you're calling from. You couldn't therefore access Yahoo finance in your example (most likely).
If you were calling from the same origin, you could use an API like fetch to get just the text and do a word count there, or you could even load an iframe and query that: myIframe.contentWindow.document.body.innerHTML.
So knowing that you cannot do this from the browser, you could do it from a NodeJS application (perhaps also using fetch):
var fetch = require('node-fetch');
fetch('https://finance.yahoo.com/')
.then(function(res) {
return res.text();
}).then(function(body) {
console.log(body);
// perform word-count here
});
I understand that you were hoping to do this from the browser, but unfortunately you will not be able to do so for origins that you do not control.
You can try this out.
In you index.html (suppose) write this:
<html>
<head>
<title>Index Page</title>
</head>
<script type="text/javascript">
function poponload()
{
testwindow = window.open("new_window.html", "mywindow","location=1,status=1,scrollbars=1,width=600,height=600");
}// here new_window.html is file you want to open or you can write any url there
</script>
<body onload="javascript: poponload()">
<h1>Hello this can Work</h1>
</body>
</html>
And suppose your new_window.html is like this:
<html>
<head>
<script>
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
}
}
return ret;
}
function run_this(){
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;
alert(count);
}
</script>
</head>
<body onload='javascript: run_this()' id="content">
<h1>This is the new window</h1>
</body>
</html>
I have built out a site that is constantly refreshing data using an AJAX call to an external API. The AJAX call uses JSONP to grab a JSON string of data due to the cross-domain restrictions involved with browsers.
The site's function is to stay open on a bigger monitor so that our help desk can be notified about how many tickets are in their queues. The site works fine some some undetermined amount of time, usually between 30 minutes to an hour. But for some odd reason it breaks and tries to redirect to "index.php", which doesn't exist. I'm not sure what is causing this.
I have relevant code below. I've spent some time in narrowing it down to that specific javascript function. I have spent some time on Google looking for answers, but have come up empty.
Perhaps someone has some insight into what is happening? Or does anyone know of any good website monitoring tools I can use to observe what is happening?
To add, the "token" part of my AJAX call is valid in my site, but I just cleared it out here for security purposes.
HTML
<!DOCTYPE html>
<html>
<head>
<title>WALLBOARD</title>
<link href="Content/style.css" type="text/css" rel="stylesheet">
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="Scripts/wallboard.js" type="text/javascript"></script>
</head>
<body>
<div id="div_hardware" class="div_normal span6">
<h1>Hardware</h1>
<div id="span_hardwareTickets">-</div>
</div>
<div id="div_atschool" class="div_normal span6">
<h1>AtSchool</h1>
<div id="span_atschoolTickets">-</div>
</div>
<div id="div_network" class="div_normal span3">
<h1>Network</h1>
<div id="span_networkTickets">-</div>
</div>
<div id="div_software" class="div_normal span3">
<h1>Software</h1>
<div id="span_softwareTickets">-</div>
</div>
<div id="div_openTickets" class="span3 div_normal">
<h1>Open Tickets</h1>
<div id="span_openTickets">-</div>
</div>
<div id="div_newTickets" class="span3 div_normal">
<h1>New Tickets</h1>
<div id="span_newTickets">-</div>
</div>
<script>
grabParature();
</script>
</body>
JAVASCRIPT
function grabParature() {
var url = "https://s3.parature.com/api/v1/5406/5426/Ticket";
$.ajax({
url: url,
type: "GET",
dataType: "jsonp",
cache: true,
jsonp : "_callback_",
jsonpCallback: "theData",
data: {
"_status_type_": "open",
"_pageSize_" : "500",
"_output_" : "javascript",
"_token_" : "##################################"
},
success: function (results) {
var openTickets = 0;
var newTickets = 0;
var atschoolTickets = 0;
var hardwareTickets = 0;
var softwareTickets = 0;
var networkTickets = 0;
for(var i = 0; i < results.Entities.Ticket.length; i++)
{
var queue = "";
var status = results.Entities.Ticket[i].Ticket_Status.Status.Name["#text"];
if (results.Entities.Ticket[i].Ticket_Queue != undefined) {
queue = results.Entities.Ticket[i].Ticket_Queue.Queue.Name["#text"];
}
if (status === "Open") {
openTickets++;
}
else if (status === "New") {
newTickets++;
}
if (queue === "Hardware") {
hardwareTickets++;
}
else if (queue === "Atschool") {
atschoolTickets++;
}
else if (queue === "Network") {
networkTickets++;
}
else if (queue === "Software") {
softwareTickets++;
}
}
$('#span_openTickets').html(openTickets);
$('#span_newTickets').html(newTickets);
$('#span_hardwareTickets').html(hardwareTickets);
$('#span_atschoolTickets').html(atschoolTickets);
$('#span_networkTickets').html(networkTickets);
$('#span_softwareTickets').html(softwareTickets);
setInterval(grabParature, 10000);
}
});
};
EDIT
I changed setInterval(grabParature, 10000), to setTimeout(grabParature, 10000) as per Ryan Wheale's suggestion. I still get a redirect to index.php.
Try not setting an interval. You should only have to setTimeout(). The interval would eventually stack up a bunch of these calls so that after about 30 minutes I can see you running out of memory as you would have about 180 ajax calls going out at the same time. Not sure why the redirect is happening - I would expect the browser to freeze... hard to tell without testing out.
I'm new in Jquery, I would like to have Jquery code to get the current page url and if the url contains certain string then load remote element.
example:
i have the page urls like this:
"http://......./Country/AU/result-search-to-buy"
"http://......./Country/CA/result-search-to-buy"
"http://......./Country/UK/result-search-to-buy"
the part "/Country/AU" is what I need to determine which page element I should load in, then if "AU" I load from "/state-loader.html .state-AU", if "CA" I load from "/state-loader.html .state-CA"
I have a builtin module "{module_pageaddress}" to get the value of the current page url, I just dont know the Jquery logic to let it work.
I expect something like this:
if {module_pageaddress} contains "/Country/AU/"
$('#MyDiv').load('state-loader.html .state-AU');
if {module_pageaddress} contains "/Country/CA/"
$('#MyDiv').load('state-loader.html .state-CA');
please help and many thanks.
Here is some code:
<!DOCTYPE html>
<html>
<head>
<title>jQuery test page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
function stateURL() {
var startOfResult = '../../state-loader.html #state-';
var match = (/(?:\/Country\/)(AU|US|CA|UK)(?:\/)/).exec(window.location.pathname);
if (match) {
return startOfResult + match[1];
} else {
return startOfResult + 'AU';
}
}
</script>
</head>
<body>
Link 1
<div id="content">content will be loaded here</div>
</body>
</html>
And the file to load the different content for the states:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="state-US">Go USA!</div>
<div id="state-CA">Go Canada!</div>
<div id="state-AU">Go Australia!</div>
<div id="state-UK">Go United Kingdom!</div>
</body>
</html>
See it work here:
http://www.quirkscode.com/flat/forumPosts/loadElementContents/Country/US/loadElementContents.html
Replace .../US/... with .../AU/..., etc. to see how it behaves.
Original post where I got the ideas/original code:
http://frinity.blogspot.com/2008/06/load-remote-content-into-div-element.html
You can try
var countryCode = ... // parse the country code from your module
$('#yourDiv').load('state-loader.html .state-' + countryCode);
See more examples of .load() here.
As far as pulling the url path you can do the following
var path_raw = document.location.path,
path_array = path_raw.split("/");
Then, you could do something like this:
$.ajax({
url: "./remote_data.php?country=" + path_array[0] + "&state=" + path_array[1],
type: "GET",
dataType: "JSON",
cache: false,
success: function(data){
// update all your elements on the page with the data you just grabbed
}
});
Use my one line javascript function for getting an array of the URL segments: http://joshkoberstein.com/blog/2012/09/get-url-segments-with-javascript
Then, define the variable $countrySegment to be the segment number that the country code is in.
For example:
/segment1/segment2/CA/
(country code would be segment 3)
Then, check if the 3rd array index is set and if said index is either 'CA' or 'AU'. If so, proceed with the load, substituting in the country-code segment into the .html filename
function getSegments(){
return location.pathname.split('/').filter(function(e){return e});
}
//set what segment the country code is in
$countrySegment = 3;
//get the segments
$segments = getSegments();
//check if segment is set
//and if segment is either 'AU' or 'CA'
if(typeof $segments[$countrySegment-1] !==undefined && ($segments[$countrySegment-1] == 'AU' || $segments[$countrySegment-1] == 'CA')){
$countryCode = $segments[$countrySegment-1];
$('#target').load('state-loader.html .state-' + $countryCode);
}
var result= window.location.pathname.match(/\/Country\/([A-Z]+)\//);
if(result){
$('#MyDiv').load('state-loader.html .state-' + result[1]);
}