1

I want to ping servers and get the online status of that server with JQuery $.post() method. My current code:

JQuery:

$(window).load(function() {
    $.post('php/ping_server.php', { 'domains[]': ["example.com", ..., ...] }, function(status) {
        for (var i=0; i < status.length; i++) {
            $('.sidebox .onlinestatus').eq(i).addClass(status[i]).text(status[i]);
        }
    }, "json");
});

PHP:

include('functions.php');

if (isset($_POST["domains"])) {
    $status = array();
    foreach($_POST["domains"] as $domain) {
        $status[] = pingDomain($domain);
    }
    die(json_encode($status));
}

The function pingDomain() returns "Offline" or "Online" and it works.
I'm not getting any errors or warnings in the console but nothing happens...

What is wrong?

6
  • 'domains[]': ["example.com", ..., ...] is wrong do 'domains': ["example.com", ..., ...] Commented May 24, 2014 at 19:27
  • @Ehsan: I replaced it but nothing changed - not working, no errors Commented May 24, 2014 at 19:36
  • 1
    console.log(status) in you jquery recieve method, then tell us if it prints what it should. Commented May 24, 2014 at 19:39
  • @kajacx: thats strange - it doesn't print anything on the console... Commented May 24, 2014 at 19:47
  • 1
    Are you using your browser developer tools to inspect the requests and see what's sent and what's responded? Commented May 24, 2014 at 19:52

1 Answer 1

1

You might need use the proper header in the php, like

include('functions.php');

if (isset($_POST["domains"])) {
    $status = array();
    foreach($_POST["domains"] as $domain) {
        $status[] = pingDomain($domain);
    }
    header('Content-Type: application/json'); // here 
    die(json_encode($status));
}

or parse the response in JS like

$(window).load(function() {
    $.post('php/ping_server.php', { 'domains': ["example.com", ..., ...] }, function(status) {
        status = JSON.parse(status); // here
        for (var i=0; i < status.length; i++) {
            $('.sidebox .onlinestatus').eq(i).addClass(status[i]).text(status[i]);
        }
    }, "json");
});

Note: both because you have specified the expected datatype explicitly. otherwise not needed.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok. Didn't know that. So if I leave out the datatype in the $.post()-method I can only do the JSON.parse in JQuery? I'll test it as soon as possible (database down).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.