Search code examples
javascriptphpvariablestwilio

How to pass JavaScript variable into a PHP function parameter?


I am trying to get a response from a Twilio API where I am facing complexity. I have a javascript variable called sid which is containing a string value.

var sid = value['sid']; // 'CA519c6aefde211131f2f44370d67607d4'

Now I need to call this variable into a PHP function as a parameter.

<?php echo $twilio->check_disputed($parameter) ?>

So, the $parameter is coming from the Javascript var sid.

I want to place the javascript variable as the parameter.

Thanks <3


Solution

  • In a very simple form/example you simply need to send an http request ( here done using the Fetch api ) to your PHP script and intercept that request. The following sends a POST request with a single parameter sid which is then passed to the Twilio method as per your requirement.

    <?php
        if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['sid'] ) ){
            $sid=$_POST['sid'];
            exit( $twilio->check_disputed( $sid ) );
        }
    ?>
    <!DOCTYPE html>
    <html lang='en'>
        <head>
            <meta charset='utf-8' />
            <title>Your page</title>
        </head>
        <body>
            <h1>Do lots of things...</h1>
            
            <script>
                /*
                    do whatever it is you do to create your variable sid
                    - here it is explicitly declared rather than derived.
                */
                const sid='CA519c6aefde211131f2f44370d67607d4';
                
                let fd=new FormData();
                    fd.set('sid',sid);
                    
                fetch( location.href, { method:'post', body:fd } )
                    .then(r=>r.text())
                    .then(data=>{
                        alert(data)
                    })
            </script>
        </body>
    </html>