0

I want to do ajax call on window load and use a url which is inside div#links

This is what I've come up with so far:

$(window).load(function() {


    baseUrl =  $("#links a").attr("href");
    $.ajax({
        url: baseUrl,
        type: "get",
        dataType: "",
        success: function(data) {

            // from here not important

HTML:

<div id="links"></div> 

Links are created dynamicly:

$('<a href="' + text + lnk + '">' + text + lnk + '</a>')
    .appendTo($('#links'));

However this doesn't seem to work.

Asciiom
  • 9,867
  • 7
  • 38
  • 57
Youss
  • 4,196
  • 12
  • 55
  • 109

2 Answers2

3

updated

it should be

var baseUrl = ...

(for proper scoping)

but that's not the real problem... looks like (for a start) at the the line

$foop = $('<form>' + data.responseText + '</form>');

data.responseText is an entire html document (which this line of code then attempts to wrap with a form element) - so that'll be a major source of issues....

Nathan
  • 6,095
  • 2
  • 35
  • 61
  • Please look at my code http://jsfiddle.net/m4QCt/142/ It should work, but it doesn't... – Youss Sep 20 '12 at 09:21
  • 1
    Without the `var` wouldn't it just create a global variable? – David Thomas Sep 20 '12 at 09:21
  • I don't think its the var that is causing problems – Youss Sep 20 '12 at 09:25
  • I googled and replaced data.responseText with innerHTML.responseText Doesn't work...(sadly that's all I can think of) – Youss Sep 20 '12 at 09:44
  • 1
    @David Thomas - possibly, depending on your javascript engine - but that's certainly not the standard as far as I know... I believe that if a variable is undeclared, any reference to it will generate an error (except when using the typeof function) - see the accepted answer here: http://stackoverflow.com/questions/2559318/how-to-check-for-undefined-or-null-variable-in-javascript – Nathan Sep 20 '12 at 09:45
  • @Youss I'm afraid you'll probably need to create a question that is more specific ... Stack Overflow is not about doing other people's work for them - sorry – Nathan Sep 20 '12 at 09:47
  • I've found the problem, see my answer. – Asciiom Sep 20 '12 at 09:48
  • @Nathan var deadline = thisQuestion :) – Youss Sep 20 '12 at 10:24
1

Looks like you're just not waiting for your #links div to be filled with content.

The first ajax call fills the links div with its content. On window.load your ajax call hasn't finished yet but you try to access these links already.

You need to execute that code when the first ajax call's success handler is fired. Now the links div doesn't contain anything yet so trying to get an atag's href from an atag that isn't there yet fails.

Asciiom
  • 9,867
  • 7
  • 38
  • 57