Ajax read HTML after fully processed - javascript

I am trying to load the HTML content of a webpage outside of my domain, which I can do just fine using functionality provided by this jQuery plugin: http://www.ajax-cross-origin.com/. However, when I print out the HTML there are pieces missing, which I assume is because the ajax request gets the HTML before the page is fully loaded. When I say "pieces missing," I mean that some tags that should have innerHTML in fact have none. Here's my code:
$.ajax({
crossOrigin: true,
url: "http://siriusxm.com/bpm",
success: function(data) {
console.log(data);
},
timeout: 5000
});
The crossOrigin attribute is from the plugin I mentioned. I get the same behavior with and without the timeout (and strangely, it doesn't seem as though the timeout is doing anything at all--when I check the console, it logs data pretty much immediately).
Is there a way to wait until the page is fully loaded before getting the content? For what it's worth, this is all part of a chrome extension I'm developing, so if there's anything else code-wise you might need just ask.
Thanks!

So according to your comments, the information you're looking for is just the Now Playing artist and Song, which you won't be able to get by loading just the source of the main page.
To find the data you're looking for just open up your Chrome DevTools, go to the network tab, and Refresh to see all requests on the page.
It looks like this is the request you want, you just need to update the timestamp every minute:
http://www.siriusxm.com/metadata/pdt/en-us/json/channels/thebeat/timestamp/08-12-03:48:00
Just parse that json and grab what you need. Of course they can always change the location or format of the file, but for right now that's what it is.

If the console log is showing all of the data you're looking for then the ajax call should be fine.
Any code in the success callback will be ran after the ajax call, so just use JQuery in the success callback function to insert data into the html. All I see there now is the console.log(data) unless you've removed some code.
The timeout just gives the ajax call a set amount of time to complete before it "times out", in other words it tells it to stop waiting after the set amount of time.

Related

Problems using Ajax calls in reloaded page

I am a novice writing a website using jquery and jquery mobile. This loads a set of questions in the form of a JSON file, using jquery ajax, and then users work through questions. On first opening, the page successfully opens 2 JSON files using code that looks like this:
function loadJSON (keytoload) {
$.ajax({
url: keytoload,
dataType: "json",
async: false,
success: function (keyloaded) {
dataset=keyloaded;
},
error: function (request,error) {
alert('Error has occurred please try again!');
}
});
}
I find that async has to be set to false for this to work. If async is true, the page is displayed without the data from the JSON file.
After the user works through a series of steps, a new JSON file is loaded to replace the first and this usually works fine. However, reloading the page is erratic. It works fine in Firefox/Chrome on Windows, but throws an error if a page refresh is done when loading on Android Chrome. So I assume there is a problem in my code somewhere.
Is there a better way I could do this?
Your problem here is cause by the fact that you don't use ajax correctly. You don't know how long is going to take until the result comes back from the server.
A correct architecture here will be:
display an loading div before starting ajax.
On success add the questions in the page.
On next display the loading again.
On success render the new content.
Just setting an variable on success is wrong; on success you render the content based on the values from backend. Also using an ajax in a synchronous way is not recommended, since it can block the script.

Can I speed this $.post callback somehow?

I'm using a $.post callback in the following to redirect the page after the data has been posted. Sometimes the page redirects pretty fast, but other times it can take a good 3-5 seconds.
I'm a novice, so not sure why it's taking so long. Is it waiting for the php to end? Anything here I can change to speed this up?
On another note... encodeURIComponent doesn't seem to be working. The URL always has a space in it like ?fbname=John Doe" which I am trying to remove withencodeURIComponent`
Thanks!
FB.api('/me', function(response) {
$.post("addtodb.php",
{fbname:response.name},
function(data) {
window.location.href = "step2.php?fbname="+encodeURIComponent(response.name); //redirect after post callback
})
});
If you use're using a tool like Firebug or Google Chromes inbuilt tools you can view network activity. This will give you an idea of where the holdup is. The wait time could be due to the responsiveness of the server, or even something within your JavaScript.
Example:
I can see that on my personal website Facebook's like.php had a fairly slow transfer time..
http://i.imgur.com/pApRt.png

read content from Twitter sample using Javascript

I'm pretty new to programming, and recently have been playing with Twitter API. From statuses/sample method, how would you read the content of following URL using Javascript?
https://stream.twitter.com/1/statuses/sample.json
Edit: perhaps I shall explain my intention. I'm trying to read the Twitter sample data, read the hashtags every 30 seconds, and then sort them ascendingly every 30 seconds the top 10 hashtags.
The problem is, I'm not even sure how to read the Twitter data in the first place..
Not looking for solutions, but definitely could use some ideas.. especially for getting started.
You should be able to utilize JSONP which is a special type of response back from the server.
It basically takes the response, wraps it in an anonymous function callback, and returns it to the client inside of a script tag thereby calling it when the response gets back to the browser.
​$.ajax({
type: 'post',
dataType: 'jsonp',
url: 'http://twitter.com/status/user_timeline/msdn.json?count=10&callback=?',
success: function (data) {
console.log(data);
}
});​
Inspecting the request url in Chrome's debugger you'll see the request...
https://twitter.com/status/user_timeline/msdn.json?count=10&callback=jQuery1706531336647458375_1335842234009&_=1335842234045
And the response back is...
jQuery1706531336647458375_1335842234009( /* data */ );
Then jQuery wraps the data in the script tag and appends it to the body.
Notice how the callback in the request matches the function call in the response.
Hope that helps!
You can't. Read up on cross site scripting.
Basically you're going to need to proxy your request through the hosting server.

loading effect in java

I have two jsp pages and one servlet. When user clicks submit button then processing is done in servlet and then result goes to another jsp page so that user sees his result. But I want to show a loading gif so that that gif will run till user gets his result and if in the mid time user stops that browser from loading then automatically that gif will also stop, how to do it?? In javascript or other only user will see that gif picture but when user will stop browser's processing still that gif is running which should not happen. How can i resolve this??
index.jsp---------------goes to a servlet------------result.jsp
Since all of this is going to happen in the user's browser, the solution cannot be in Java, it will have to be JavaScript, reacting to the onabort event.
As for stopping a GIF animation, that's not really possible (except perhaps through nasty hacks). I suggest using JavaScript (e.g. jQuery builtins or plugins) to do the animation as well.
Update: On second thought, why do you think you need to do anything at all? If the browser aborths the loading, it's their own fault, and the browser already has a loading animation that does exactly what you want. Why duplicate that?
That's nothing Java specific since everything will happen in the browser. You might need some JavaScript to open up that popup before the request is issued and register an event handler that closes the popup on window.onabort.
Try this
function doWork() {
//start loading gif
$.ajax({
'type': 'POST',
'cache': false,
'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
'url': #your_servlet_url#,
'data': $('form#' + #your_form_id#).serialize(),
success: function (data) {//data can be json or plain HTML depending on your scenario
// stop the loading gif
//redirect to result.jsp if you need to redirect user to completely new page with 'data' received
// or just send the result.jsp with processed data from the servlet and load the content 'data'
// received above in some div on index.jsp
},
error: function (xhr, status, err) {
//request cancelled by user or due to any other reason such timeout
if (xhr.status == 0) {
//stop the loading gif
}
// you can handle other errors(401,403 etc) too by examining xhr, status and err objects
}
});
}
Two things I can think of:
on submit simply show the gif. All browsers I have checked will not change the current page until the result from the second one is received.
use ajax (jQuery) to show the results. Then you can use an ajax activity indicator
The jQuery JavaScript library probably can provide some nice in progress effect.
For the future: HTML5 has a progressbar or such.
Use of Ajax might make sence (callback when loaded say inside DIV).
A very crude solution would be to use ajax for your form submit. You can display a loading gif on submit and as soon as you receive a response update the page and remove the gif.
Jquery ajax method would be able to handle abort by user, which would enable you to write logic to remove the gif for instance(or any other processing on page in case of abort)
Other possibility is if you use frameworks like struts(2.0). This gives a wait and execute interceptor especially for this kind of purpose(display an intermediate page while request is processed)

best practice for loading necessary JSON data: jquery's $(document).ready() hook? in the <HEAD> of page?

I have been reading Yahoo's Best Practices For Speeding Up Your Website, but still have a question that I could really use your help with:
The very first page of my web app needs to display a bunch of data that is dependent on the city the user is in. On the first visit, the user is prompted to pick her city and I store a cookie in the browser recording which city to start with. On her following visits to the site, the Javascript code checks the cookie and retrieves the data for that city as JSON.
Given that this data is necessary to display the fundamental part of the page, where should I load it from? Currently I am doing it from the top of Jquery's $(document).ready(), but it occurred to me that by definition that only gets executed once the entire page has loaded.
Which is the correct way to do this? (Eg, will it improve matters if I instead put some Javascript in the that checks for the cookie and loads the JSON feed for the right city? Some other solution...?)
Thank you for any insight
lara
Currently I am doing it from the top
of Jquery's $(document).ready(), but
it occurred to me that by definition
that only gets executed once the
entire page has loaded.
$(document).ready() will be called when the DOM is ready for manipulation, not when the entire page has loaded. The DOM will be ready as soon as the markup has been read and parsed into the DOM. This occurs before the entire page has loaded.
Putting your code to check the cookie value and retrieve city-specified data in $(document).ready() is perfectly fine.
If you really need this data to show the page correctly, how about simply inlining the data in the page itself? Save yourself an AJAX round-trip, be nice to your users in sub-Saharan Africa on the 300 baud modem.
I think the $(document).ready() is as soon as you can do it, although I'm not sure why you wouldn't just inspect the cookie values on the first request. Just check to see if they are set, and if they are, get the content for the user there are save yourself having to make any AJAX call. Maybe I'm missing something in your situation, but cookies are always sent with every request to a specific domain so AJAX/JavaScript shouldn't be necessary.

Categories