views:

38

answers:

2

I'm doing a lending rates page. I have a url which, upon entering in a browser, returns a number.

I need to be able to do (in human terms) this:

var x=http://www.wherever.com/assest?cmsid=P-2870159

in the html:

<td>Our rate today is:<var x></td>

So in javascript, I'm just blanking on how I get the value returned from the url to be assigned to a variable that I can document.write the variable into an html file wherever I need the value.

The url stays the same but the number it somehow generates is dynamic.

I don't have full access to where the url is actually hosted.

NOTE: the url above is fictitious but the ?cmsid on is real so that is the proper format.

+5  A: 

You are looking to make an AJAX call.

A simple jQuery example:

$.get('http://www.wherever.com/assest?cmsid=P-2870159', function(data) {
  x = data;
  alert('x is now' + x);
});

Note that AJAX is asynchronous. That means that you can't work with x straight away in your code, but you have to put anything that works with the fetched result into the success callback (the function(data) part in the above example).

It is also possible to make the above example synchronous (so that x is available in the script afterwards) but that is not recommended, as it could freeze the browser when the request times out.

AJAX is a technique independent from jQuery, but as you can see the JavaScript frameworks take a lot of hassle out of what would be a 10-20 line code block using plain JavaScript and the XMLHTTPRequest object.

Note that like @Paul Dixon says, you can't do cross-domain AJAX calls. The only technique to do that is JSONP.

Unicron
Note that to do this with an XmlHttpRequest (AJAX) the "Same Origin Policy" comes into play - you can only make requests to the same domain as the hosting page.
Paul Dixon
Good point @Paul, I added that to the answer.
Unicron
A: 

The quick answer, thought it may not be the best is to do something like

<td>Our rate today is<iframe id='rate' src='http://www.wherever.com/assest?cmsid=P-2870159
'></iframe></td>

Then style with css the iframe so that is inline and whatever size you need.

To avoid the same origin problem you can always do an HTTP request to the server and let the server get the number and then return it. Though, I'm thinking it would be better just to the hole thing server side and just insert it into the HTML before the page is sent to the browser.

<td>Our rate is today is <?php getRate(); ?></td>
qw3n