简体   繁体   中英

how to pass javascript callback response into php

how to pass the callback javascript response to php if let's say i'm in a single php file ?. here's a sample snippet of eg test.php

<html>
<head>
<script>
var _somestuff = _somestuff || [];
            (function () {
                _somestuff.push(['id', blahblah], ['setApiKey',   "blahblah"] 
                );
            var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0];
            g.type = 'text/javascript';
            g.defer = true;
            g.async = true;
            g.src = 'blahblah.js';
            s.parentNode.insertBefore(g, s);
        })();


             function myCallback(response)
            {

                if (response !== undefined) {
                    var data = JSON.parse(response);
                    var item_ids = data.items;
                    console.log(item_ids);
                }
            }  
   _somestuff.push(['blahblah',"001124","blahblah","myCallback"]);
</script>
</head>
<body>
</body>
</html>  

what I want to happen is, display the data or the item_ids inside the html body using php.. how to do that?, i'm in a single page, I don't want to use ajax or whatever,is that possible ?

IF PHP and your JS are in the same page

  • You need to use AJAX (to send a POST to the same page)
  • In order to make PHP respond with some data but not with the same whole document you need to put exit; in the last line of your PHP code
  • (Your PHP code has to be at the top of the same document.)

PSEUDO:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
       if(isset($_POST["someData"])) {
           // Do some stuff with someData
           // return /*anything you need*/; // this return will be collected by the AJAX success
       }
    }
    exit; // Prevents the AJAX to return the whole document (with HTML etc)
?>
<html>
<head>
<script>
     // JS AJAX POST someData TO PHP (use the same url)
     // on success use the returned data by the PHP's `return`
</script>
</head>
<body>
</body>
</html>  

I solved the my issue by assigning the myCallback function to a variable like

var a = function myCallback(response)
            {

                if (response !== undefined) {
                    var data = JSON.parse(response);
                    var item_ids = data.items;
                    console.log(item_ids);
                }
            };

then passed the variable to

_somestuff.push(['blahblah',"001124","blahblah",a]);

then inside the myCallback if condition, I just manipulated the html there and loaded the data response :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM