1

I am trying to POST the data retrieved from the response variable to the post.php page. However I am getting the following error; Uncaught SyntaxError: Identifier 'socket' has already been declared I have tried taking the socket connection outside of the foreach however this hasn't helped.

<?php 

    $xml = file_get_contents("https://explorer.casinocoin.org/ext/getaddress/c4fpX7druW1JfgveFq6e7WabveVkAvW7gj");
    $data = json_decode($xml);
    foreach($data->last_txs as $value){ 
    ?>
            <script>
            let socket = new WebSocket("wss://ws01.casinocoin.org:4443");

            socket.onopen = function(e) {
              console.log("[open] Connection established");
              console.log("Sending to server");
              
              socket.send(`{"id": 1,"command": "tx","transaction": "<?php echo $value->addresses; ?>"}`);
              
            };

            socket.onmessage = function(event) {
             
             var response = event.data;
             
                  $.ajax({
                        type: 'POST',
                        url: 'post.php',
                        data:  { feedback:response },
                         success: function(result) {
                            $('#feedback').html(result);
                        },
                        error: function() {
                            alert('Some error found. Please try again!');
                        }
                        
                        
                });
              
              socket.close();
            };
            </script>
    <?php } ?>
    
<div id="feedback"></div>
  • You're using a foreach loop and creates many time the same script. This duplicates the creation of variables – Cid Nov 30 '20 at 07:39
  • is there a way to destroy the socket connection at the end of each loop? so that the next loop is free to use the same identifier or is there a way for the socket connection to be outside of the foreach so that its not being duplicated? –  Nov 30 '20 at 07:42
  • 2
    This is a variable scope issue. See [this answer](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var). But defining variables in the global scope is generally not considered best practice. You might use an object that has a 'socket' property that you can then overwrite every time. There's no way of 'unsetting' a variable in JavaScript like you can in PHP (different story for object properties). – Ro Achterberg Nov 30 '20 at 07:55

0 Answers0