Maximilian Walter
Maximilian Walter

Reputation: 154

Error while using jQuery

I am confused, i included the jQuery 1.7 library before executiong this script:

var rq;

function request(localTarget, parameter)
{
    $("#" + localTarget).text("Laden...");
    rq = new XMLHttpRequest();
    rq.open("GET", parameter, false);
    rq.onreadystatechange = auswerten(localTarget, parameter);
}

function auswerten(target, site)
{   
    if (rq.readyState == 4 && rq.status == 200) {
        $("#" + target).text(rq.responseText);
    } else {
        $("#" + target).text("Wert konnte nicht geladen werden");
    }
}

But the Text won't show up, i tried everything, but it won't work!

the Html code i want to insert the text goes like this:

<table width='100%' cellpadding='4' cellspacing='0'>
<tr>
  <td class='tablesubheader' width='50%'>Typ</td>
  <td class='tablesubheader' width='50%'>Wert</td>
</tr>

<tr>
<td>Geld heute</td>
<td><div id="money_today">Test</div></td>
</tr>

<tr>
<td>Geld Monat</td>
<td id="money_month"></td>
</tr>

<tr>
<td>Klicks heute</td>
<td id="klicks_today"></td>
</tr>

<tr>
<td>Klicks Monat</td>
<td id="klicks_month"></td>
</tr>

</table>
</td>

The method above is called like this:

<script type="text/javascript">
$(window).load(function() {
    request('money_today','<?php echo $link1; ?>');
    request('money_month','<?php echo $link2; ?>');
    request('klicks_today','<?php echo $link3; ?>');
    request('klicks_month','<?php echo $link4; ?>');
});
</script>

Upvotes: 1

Views: 89

Answers (3)

Anoop
Anoop

Reputation: 23208

Move your code inside $(document).ready and use .html instead of .text.

modified code: jquery load

    function request(localTarget, parameter)
    {
        $("#" + localTarget).("Wert konnte nicht geladen werden");
        $("#" + localTarget).load(parameter);
    }

Note: you should provide function reference to rq.onreadystatechange load not return value of function. auswerten(localTarget, parameter); will assign undefined to onreadystatechange .

Upvotes: 1

pimvdb
pimvdb

Reputation: 154818

rq.onreadystatechange = auswerten(localTarget, parameter);

You're calling the function right here. You don't what that - the browser should call the function when the response has arrived:

// pass a function (that you don't call), which in turn calls `auswerten`
rq.onreadystatechange = function() {
  auswerten(localTarget, parameter);
};

Anyway, jQuery has a built-in $.ajax function that has cross-browser normalization and is quicker to use.

Upvotes: 0

BenjaminRH
BenjaminRH

Reputation: 12172

It's possible the problem is that your code is running before the elements you're trying to deal with exist on the page: i.e. before the pages is loaded. Try putting that code inside the following:

$(document).ready(function() {
    // Your code here
});

Upvotes: 0

Related Questions