0

Is there anyway to run / trigger / call a javascript (client side) from server side (PHP) ?

I can run the javascript if i call it from browser (of course, because it's client), but not from server side / postman (i wonder if there's any?)

function validate_answer($p) {
?>

<script>
    $.ajax({ url: '/validate_time.php',
     data: {'action': 'test'},
     type: 'post',
     timeout:5000
    });
</script>

<?php

}

The reason i want to use this way, because in PHP, there's no such function like setTimeout like javascript does.

Thanks guys

EDIT

Okay, here's the thing. I'm creating a game that has a timeout, whenever the game starts, it will have a timelimit (10 mins example). And i need a function to do that, unfortunately, it's not accessible via browser (it's like a web service). I've tried using sleep, but it's not what i wanted.

9
  • What do you need this for? Commented Nov 8, 2016 at 8:25
  • you could use php sleep Commented Nov 8, 2016 at 8:26
  • hi @u_mulder, as i said above, i need it because in php there's no such thing like settimeout (javascript). Sleep isnt the same like settimeout. it will not execute other stuff until it wake up. Commented Nov 8, 2016 at 8:28
  • Why do you need timeout on server? Commented Nov 8, 2016 at 8:29
  • 1
    Try to check GearmanWorker::setTimeout function. This may help you. Here is the link php.net/manual/en/gearmanworker.settimeout.php Commented Nov 8, 2016 at 8:33

2 Answers 2

2

You cannot run javascript on the server side. If you want to get the effect of the timeout without holding up your main script, you can call the URL with a parameter like this:

function validate_answer($p) {

    $ms_delay = 5000;

    file_get_contents('http://www.yoursite.com/validate_time.php?action=test&delay='.$ms_delay)

}

And then in validate_time.php at the start of the file do this:

sleep($_GET['delay'] / 1000)

Not very elegant though.

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

Comments

1

PHP is single-threaded, and in general PHP is focused on the HTTP request cycle, so this would be tricky to allow a timeout to run code, potentially after the request is done.

I can suggest you look into Gearman as a solution to delegate work to other PHP processes.

1 Comment

Hi, i will try it, and will update the result. thanks :)

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.