Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Let's say I have one page that displays the number "5". The page source code looks like this:

5

Now, on a different web page, I want to save the contents of this page (5) to a Javascript variable. I'm pretty sure this can be done by using jQuery/AJAX to access the external page, and then grab the contents, but I'm unsure as to how I would write the value into a Javascript variable.

How would you approach this? What code should be used?

share|improve this question
    
Make a webservice which returns the 5. –  Travis J Jun 14 '13 at 17:49

2 Answers 2

up vote 1 down vote accepted

You can do this using the .get() function, along with a callback:

function get_data(callback) {
    $.get('get.php', function (data) {
        callback(data);
    });
}

function use_data(param) {
    alert(param);
}

You can now call the get_data function with a callback function. You can do whatever you want to this variable inside that callback, for now, it simply alerts.

get_data(use_data);
share|improve this answer
    
Thanks for this :) –  goddfree Jun 14 '13 at 18:10

You can do it using .get() function

var distinctTaxis = 0;
$.get('get.php', {"distinct": "yes"}, function (data) {
    distinctTaxis = data;
});
share|improve this answer
    
This isn't working. I am doing this: var distinctTaxis = 0; $.get('get.php?distinct=yes', function (data) { distinctTaxis = data; }); alert(distinctTaxis); but the alert still returns 0. –  goddfree Jun 14 '13 at 18:00
    
please see the edited post, you need to pass parameters in the method –  Sampriti Panda Jun 14 '13 at 18:03
2  
This is an Async function, throwing an alert immediately after isn't going to work. You'll need a callback. –  tymeJV Jun 14 '13 at 18:04
    
Alright, thanks for that. By callback, you mean like pressing a button to display the alert? –  goddfree Jun 14 '13 at 18:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.