code_junkie

How to pass a variable / data from javascript to php and vice versa?

Nov 13th, 2011
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. <!-- headers etc. omitted -->
  2. <script>
  3. function callPHP(params) {
  4. var httpc = new XMLHttpRequest(); // simplified for clarity
  5. var url = "get_data.php";
  6. httpc.open("POST", url, true); // sending as POST
  7.  
  8. httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  9. httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
  10.  
  11. httpc.onreadystatechange = function() { //Call a function when the state changes.
  12. if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
  13. alert(httpc.responseText); // some processing here, or whatever you want to do with the response
  14. }
  15. }
  16. httpc.send(params);
  17. }
  18. </script>
  19. <a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
  20. <!-- rest of document omitted -->
  21.  
  22. <script language="javascript" type="text/javascript">
  23. function _vals(target, value){
  24. form1.all("target").value=target;
  25. form1.all("value").value=value;
  26. form1.submit();
  27. }
  28. </script>
  29.  
  30. <a onclick="_vals('name', 'val')" href="#">My Link</a>
  31.  
  32. $val = $_POST['value'];
  33.  
  34. <script>
  35. var php_value = '<?php echo $php_variable; ?>';
  36.  
  37. var infobar_active = $.cookie('php_value');
  38. var infobar_alert = any_process(infobar_active);
  39.  
  40. //set a cookie to readit via php
  41. $.cookie('infobar_alerta', infobar_alerta );
  42.  
  43. </script>
  44.  
  45. <?php
  46.  
  47. var js_value = code to read a cookie
  48.  
  49. ?>
Add Comment
Please, Sign In to add comment