Getting a json from a server and assigning it to a variable

87 Views Asked by At

I'm new to Javascript but not programming. I'm trying to write a program that exchanges information with a server. I can't get it to work and even simplifying and borrowing other peoples code doesn't help. What I'm doing wrong?

Here is the client:

<!DOCTYPE html>
<html>

<head>
    <title>Testing</title>
</head>

<body>
    <script>
        GET_JSON = function(callback) {
            var req = new XMLHttpRequest();
            req.open(POST, "http://www.skutan.com/cgi-bin/hvserver.cgi", true);
            req.onreadystatechange = function() {
                if (this.readyState == 4) {
                    callback(JSON.parse(req.responseText));
                }
            }
            req.send("a=2&b=1");
        }

        JSONCallback = function(JSONObj) {
            alert(JSONObj);
        };
    </script>

    <button type="button" onclick="GET_JSON(JSONCallback)">Test</button>

    <h1>.</h1>
    <span id="koord"></span>
</body>

</html>

The server is witten in perl and looks like this:

#!/usr/bin/perl -wT                                                             
use strict;
use CGI qw(:standard);

my @fields = param;

my $json_ut = "{\"a\": 1, \"b\": 2}";

print("Content-type: application/json; charset=utf-8\n\n");

print("$json_ut");

Why don't I get any alert in the client?

1

There are 1 best solutions below

1
On BEST ANSWER

If you checked your brower's console, you'll see an error such as

ReferenceError: POST is not defined

with a reference to the line

req.open(POST, "http://www.skutan.com/cgi-bin/hvserver.cgi", true);

It should be

req.open("POST", "http://www.skutan.com/cgi-bin/hvserver.cgi", true);