0

I'm using WebIM for chat support on a website. I would like to be able to setup a timer for when a client initiates a chat session, if an operator/tech does not respond within 'x' seconds I would like the page to redirect to another page where the client can leave a message.

Sortof a 'please hold while we try to connect you' thing. That way if all the techs are too busy or helping other clients the client waiting can simply try back later or leave a message (as such when chat is offline).

I looked extensively over mibew.org the creators of the chat script, there is nothing regarding this feature, also it looks as though their website has just about been abandoned.

I have come up with an idea of using Javascript setTimeout function to run some php after 'x' amount of time. The php will basically query the DB to see if a tech has entered the session in question and if not then redirect the client to another page explaining that no one is available at the moment, but they can leave a message, etc.

Problem is, I don't have much of any experience with JS.

Is this a possibility? Is there another more effective/efficient was to accomplish this?

Sabyre
  • 97
  • 10

4 Answers4

1

Yes, you can do that.

You can use the timeout function to perform a javascript function every x seconds.

var time = 200;
setTimeout(function()
{ 
    func(); 
}, time);

Then make the function perform an ajax call, asking for some result from the database, and do something depending on the results.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • setTimeout is built in function available in the window object, you don't need jQuery for it – Andy Jones Mar 01 '13 at 19:06
  • @Jonast92 setTimeout() will execute the callback after a specified time as passed. To perform the function every x seconds you need to you setInterval() – moranjk Mar 01 '13 at 19:45
  • Thank you very much for this insite. A few hours later and I finally got it using this: `var time = 150000; setTimeout(function() { if ('' == 'n') window.location.replace("http://stackoverflow.com"); }, time);` – Sabyre Mar 01 '13 at 22:45
  • Cool, but you should consider not mixing PHP and Javascript (Ideally it shouldn't even work), instead perform some ajax calls which receive some information from a PHP script. But if it works then great :) – Jonast92 Mar 02 '13 at 13:48
  • I have no idea how to do that... PHP I know, java/ajax I've barely scratched the surface. Can you recoomend a good place to get started with that? – Sabyre Mar 02 '13 at 16:12
  • I was wrong.... This code is NOT waiting 2.5 mins before it runs the PHP, it's running it immediately. How can I make it wait before running the PHP? – Sabyre Mar 02 '13 at 16:59
  • You should never mix PHP and Javascript together, I don't even think It's possible. Using the method isn't that complicated, I'll put together an example and post here. – Jonast92 Mar 03 '13 at 00:29
  • I posted a VERY detailed (semi tutorial) about how you can post something to a php page from a javascript script and get a JSON array returned and how to use it. Please read it and give me your thoughts. – Jonast92 Mar 03 '13 at 01:09
  • Thank you Jonas, you are absolutely correct. I utilized ajax to make this happen and it is now working as intended. Thank you for all your help! – Sabyre Mar 03 '13 at 01:40
0

It wouldn't be too difficult at all. When your timeout method dictates:

 $.post('url/of/phpscript', 
        $data /* data you'd like to send*/,
        function(returnData) { doSomethingWithThisPhpValue(data) });

 function doSomethingWithThisPhpValue(data) {
     if (data == signed_in) //...
 }

Of course, the value test and variables will ultimately depend on what data you're returning from your php method, so I can't be much more exact.

Sturm
  • 4,105
  • 3
  • 24
  • 39
  • `setTimeout( $.post('libs/newchattimer.php', function(returnData) { ReDirect(data) }); function ReDirect(data) { if (data == "n") window.location.replace("http://stackoverflow.com"); }, 500);` – Sabyre Mar 01 '13 at 19:45
  • I turned error reporting on and got nothing..... `error_reporting(E_ALL); ini_set('display_errors', '1');` – Sabyre Mar 01 '13 at 19:56
  • That would be because your ajax query is failing, due to javascript errors. You use returnData then try to pass your next method data instead. Resolve your javascript errors. – Sturm Mar 01 '13 at 20:00
  • I'm certain that Google Chrome's developer console will help you debug the javascript errors, I believe that most browsers have a feature like this, you'll have to look it up for your particular browser and use that. – Sturm Mar 01 '13 at 20:06
0

An example of how to use make javascript and PHP work together without mixing it up (ajax):

First you need a javascript function:

function example()
{
    var select = true;
    var url = '../scripts/ajax.php';

    $.ajax(
    {
        // Post select to url.
        type : 'post',
        url : url,
        dataType : 'json', // expected returned data format.
        data : 
        {
                'select' : select // the variable you're posting.
        },
        success : function(data)
        {
            // This happens AFTER the PHP has returned an JSON array,
            // as explained below.
            var result1, result2, message;

            for(var i = 0; i < data.length; i++)
            {
                // Parse through the JSON array which was returned.
                // A proper error handling should be added here (check if
                // everything went successful or not)

                result1 = data[i].result1;
                result2 = data[i].result2;
                message = data[i].message;
                // Do something with result and result2, or message.
                // For example:
                $('#content').html(result1);
            }
        },
        complete : function(data)
        {
            // do something, not critical.
        }
    });
}

Now we need to receive the posted variable in ajax.php:

$select = isset($_POST['select']) ? $_POST['select'] : false;

The ternary operator lets $select's value become false if It's not set.

Make sure you got access to your database here:

$db = $GLOBALS['db']; // En example of a PDO database connection

Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:

if($select)
{
    // Fetch data from the database.
    // Return the data with a JSON array (see below).
]
else
{
    $json[] = array
    (
        'message' => 'Not Requested'
    );
}
echo json_encode($json);
flush();

How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.

Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):

function selectMultipleRows($db, $query)
{
    $array = array();
    $stmt = $db->prepare($query);
    $stmt->execute();
    if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
    {
        foreach($result as $res)
        {
            foreach($res as $key=>$val)
            {
                $temp[$key] = utf8_encode($val);
            }
            array_push($array, $temp);
        }
        return $array;
    }
    return false;
}

Then you can do something like this:

if($select)
{
    $array = array();
    $i = 0;

    $query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
    foreach(selectMultipleRows($db, $query) as $row)
    {
        $array [$i]["result1"] = $row['result1'];
        $array [$i]["result2"] = $row['result2'];
        $i++;
    }

    if(!(empty($array))) // If something was fetched
    {
        while(list($key, $value) = each($array))
        {
             $json[] = array
             (
                 'result1' => $value["result1"],
                 'result2' => $value["result2"],
                 'message' => 'success'
             );
       }
    }
    else // Nothing found in database
    { 
        $json[] = array
        (
             'message' => 'nothing found'
        );
    }
}
// ...

Or, if you want to KISS (Keep it simple stupid):

Init a basic function which select some values from the database and returns a single row:

function getSingleRow($db, $query)
{
    $stmt = $db->prepare($query);
    $stmt->execute();
    // $stmt->execute(array(":id"=>$someValue)); another approach to execute.
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if($result)
    {
        $array = (
            'result1' => $result['result1'], 
            'result2' => $result['result2']
        );
        // An array is not needed for a single value.
        return $array;
    }
    return false;
}

And then fetch the row (or the single value) and return it with JSON:

if($select)
{
    // Assume that the previously defined query exists.
    $results = getSingleRow($db, $query);
    if($results !== false)
    {
         $json[] = array
         (
             'result1' => $results['result1'],
             'result2' => $results['result2'],
             'message' => 'success'
         );
    }
    else // Nothing found in database
    { 
        $json[] = array
        (
             'message' => 'nothing found'
        );
    }
}
// ...

Anyway, I hope I'm not shooting myself in the leg by being so precise, but I love this technique and @Sabyre wanted an example so here it is. Please comment if you find something weird happening.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • Jonast, again thank you ... That was very kind of you to offer such an indepth explination to an obvious rookie. I wish I had enough room to post the actual code and process I used. I'm also new to this site. Basically I used ajax to run a php after x time that created a flat file that ajax reads to determin if chat is answered. With js I am such a newb. The site im working on is [link](www.itdsi.com) if you want to check out the chat and talk to me. Thanks again!@ – Sabyre Mar 03 '13 at 01:53
-1

Something like this would work

function callAfter5Seconds() {
  // your redirect or any other work goes here
}

// the second argument is the time, in milli-seconds (5000 = 5 seconds)
var myTimeout = setTimeout(callAfter5Seconds, 5000);

... and then don't forget to cancel your timeout if the operator does pickup

clearTimeout(myTimeout);
Andy Jones
  • 6,205
  • 4
  • 31
  • 47