View Single Post
Join Date: Aug 2008
Posts: 381
Reputation: langsor is an unknown quantity at this point 
Solved Threads: 33
langsor langsor is offline Offline
Posting Whiz

Re: How to call a PHP function from Javascript and return the results back into Javas

 
0
  #7
Aug 12th, 2008
Originally Posted by nemo5 View Post
The best way would be to make an ajax call, but the proposed iframe solution would work as well. You don't even have to make the iframe small, just set it's style attribute to:
  1. style="visibility: hidden"
Worth considering if you do this, is that 'hidden' elements still affect the page flow and layout -- thus creating a break in the flow of visible elements.

I don't have experience in XML-RPC or SOAP but if I understand correctly, the HttpRequest object does not allow cross-site requests. I believe this is going to be included in future releases of some browsers though. Correct me if I'm wrong here.

You can always make an Ajax call to a locally hosted PHP script and have it query the remotely served database.

You can make an Ajax query to a locally hosted PHP script and have it make a call to a remotely hosted PHP script and set up a conversation that way.

You can use an iframe as mentioned above

Of course there are a multitude of Ajax libraries available these days -- not all created equal though in terms of robustness or ease of implementation. Or you could learn how to roll your own and gain invaluable experience that way.

Another fun non-Ajax (read old-skool) trick is to use JavaScript to call the PHP file as a JavaScript include file -- see example bellow.

page: test.html
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. window.onload = init_loader;
  5.  
  6. function init_loader (){
  7. var head = document.getElementsByTagName('head').item(0);
  8. document.getElementById('loader').onclick = function () {
  9. var script = document.createElement('script');
  10. script.setAttribute( 'type', 'text/javascript' );
  11. script.setAttribute( 'src', 'remote.php?value=my message' );
  12. head.insertBefore( script, head.firstChild );
  13. };
  14. };
  15. </script>
  16. </head>
  17. <body>
  18. </body>
  19. <a id="loader" href="#">Load Script</a>
  20. </html>

page: remote.php
  1. <?php
  2.  
  3. // get the request
  4. $query = $_GET['value'];
  5. $query = "'".addslashes( $query )."'";
  6.  
  7. // print back as plain javascript
  8. print <<<ENDLINE
  9. alert( $query );
  10. ENDLINE;
  11.  
  12. ?>

What ever way you do it should be a learning experience ... :-)
Last edited by langsor; Aug 12th, 2008 at 8:20 pm.
Reply With Quote