A
A
Alex Franz2018-08-20 12:20:11
AJAX
Alex Franz, 2018-08-20 12:20:11

Problem with running php function via ajax?

Good afternoon!
Task: it is necessary to redirect the user to another page upon successful connection to the WebSocket server or receiving any messages from it. It is important for me to implement this when calling the php.

<?php
$ws = true;

function location() {
  header('Location: http://www.example.com/');
}

if($_POST['action'] == 'location') {
  location();
}
?>

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>

  <?php if($ws == true) : ?>
    <script type="text/javascript">    
     var socket = new WebSocket("ws://xx.xx.xxx.xx:xxxx");
     
    socket.onopen = function() {
      $.ajax({
       url : 'wsajax.php' ,
       method : 'POST' ,
       data : { action : 'location' },
      success : function(resp){
       }
      });
     };
     </script>
  <?php endif; ?>

</body>
</html>

The result of the work: when the page is refreshed, a connection to the server occurs, but no redirects occur. What's my mistake? Ps wsajax.php is a common file that has both php script and js

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Gleb Starkov, 2018-08-20
@Suyano

AJAX works in another thread, your page has nothing to do with it, how will it reload?
You need to redirect with javascript.

A
Akim Glushkov, 2018-08-20
@mikaakim

By means of JS: When responding from php, you can pass the address encoded in JSON or read the response header from ajax and redirect the user to it with the function above.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question