Guest User

Untitled

a guest
Aug 1st, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.97 KB | None | 0 0
  1. <?php
  2. ...
  3. $val = $myService->getValue(); // makes an api and db call
  4. ?>
  5.  
  6. <script>
  7. myPlugin.start($val); // tried this, didn't work
  8. <?php myPlugin.start($val); ?> // this didn't work either
  9. myPlugin.start(<?=$val?> // this works sometimes, but sometimes it fails
  10. </script>
  11.  
  12. /* Do some operation here, like talk to the database, the file-session
  13. * The world beyond, limbo, the city of shimmers, and Canada.
  14. *
  15. * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
  16. * It all depends on the Content-type header that you send with your AJAX
  17. * request. */
  18.  
  19. echo json_encode(42); //In the end, you need to echo the result.
  20. //All data should be json_encode()d.
  21.  
  22. //You can json_encode() any value in PHP, arrays, strings,
  23. //even objects.
  24.  
  25. <!-- snip -->
  26. <script>
  27. function reqListener () {
  28. console.log(this.responseText);
  29. }
  30.  
  31. var oReq = new XMLHttpRequest(); //New request object
  32. oReq.onload = function() {
  33. //This is where you handle what to do with the response.
  34. //The actual data is found on this.responseText
  35. alert(this.responseText); //Will alert: 42
  36. };
  37. oReq.open("get", "get-data.php", true);
  38. // ^ Don't block the rest of the execution.
  39. // Don't wait until the request finishes to
  40. // continue.
  41. oReq.send();
  42. </script>
  43. <!-- snip -->
  44.  
  45. <!-- snip -->
  46. <div id="dom-target" style="display: none;">
  47. <?php
  48. $output = "42"; //Again, do some operation, get the output.
  49. echo htmlspecialchars($output); /* You have to escape because the result
  50. will not be valid HTML otherwise. */
  51. ?>
  52. </div>
  53. <script>
  54. var div = document.getElementById("dom-target");
  55. var myData = div.textContent;
  56. </script>
  57. <!-- snip -->
  58.  
  59. <!-- snip -->
  60. <script>
  61. var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
  62. </script>
  63. <!-- snip -->
  64.  
  65. setcookie("MyCookie", $value); // sets the cookie to the value, remember, do not
  66. // set it with HTTP only to true.
  67.  
  68. var cookies = document.cookie.split(";").
  69. map(function(el){ return el.split("="); }).
  70. reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});
  71.  
  72. cookies["MyCookie"] // value set with php.
  73.  
  74. <script>
  75. var myServerData = <?=json_encode($value)?>; // don't forget to sanitize
  76. //server data
  77. </script>
  78.  
  79. function callback(data){
  80. // what do I do with the response?
  81. }
  82.  
  83. var httpRequest = new XMLHttpRequest;
  84. httpRequest.onreadystatechange = function(){
  85. if (httpRequest.readyState === 4) {// request is done
  86. if (httpRequest.status === 200) {// successfully
  87. callback(httpRequest.responseText);// we're calling our method
  88. }
  89. }
  90. };
  91. httpRequest.open('GET', "/echo/json");
  92. httpRequest.send();
  93.  
  94. $.get("/your/url").done(function(data){
  95. // what do I do with the data?
  96. });
  97.  
  98. <$php
  99. ...
  100. $val = myService->getValue(); // makes an api and db call
  101. echo json_encode($val); // write it to the output
  102. $>
  103.  
  104. <div class="service-container" data-service="<?php echo $myService->getValue(); ?>">
  105.  
  106. </div>
  107.  
  108. <script>
  109. $(document).ready(function() {
  110. $('.service-container').each(function() {
  111. var container = $(this);
  112. var service = container.data('service');
  113.  
  114. // service variable now contains the value of $myService->getValue();
  115. });
  116. });
  117. </script>
  118.  
  119. <script>
  120. var jsvar = <?php echo json_encode($PHPVar); ?>;
  121. </script>
  122.  
  123. <script type="text/javascript">
  124. var js_variable = '<?php echo $php_variable;?>';
  125. <script>
  126.  
  127. <script type="text/javascript">
  128. var js_variable = <?php echo json_encode($php_variable); ?>;
  129. </script>
  130.  
  131. class mHeader {
  132.  
  133. private $scripts = array();
  134.  
  135. /**
  136. * @param string $id unique script identifier
  137. * @param string $src script src attribute
  138. * @param array $deps an array of dependencies ( script identifiers ).
  139. * @param array $data an array, data that will be json_encoded and available to the script.
  140. */
  141. function enqueue_script( $id, $src, $deps = array(), $data = array() ) {
  142. $this->scripts[$id] = array( 'src' => $src, 'deps' => $deps, 'data' => $data );
  143. }
  144.  
  145. private function dependencies( $script ) {
  146. if ( $script['deps'] ) {
  147. return array_map( array( $this, 'dependencies' ), array_intersect_key( $this->scripts, array_flip( $script['deps'] ) ) );
  148. }
  149. }
  150.  
  151. private function _unset( $key, &$deps, &$out ) {
  152. $out[$key] = $this->scripts[$key];
  153. unset( $deps[$key] );
  154. }
  155.  
  156. private function flattern( &$deps, &$out = array() ) {
  157.  
  158. foreach( $deps as $key => $value ) {
  159. empty($value) ? $this->_unset( $key, $deps, $out ) : $this->flattern( $deps[$key], $out );
  160. }
  161. }
  162.  
  163. function print_scripts() {
  164.  
  165. if ( !$this->scripts ) return;
  166.  
  167. $deps = array_map( array( $this, 'dependencies' ), $this->scripts );
  168. while ( $deps )
  169. $this->flattern( $deps, $js );
  170.  
  171. foreach( $js as $key => $script ) {
  172. $script['data'] && printf( "<script> var %s = %s; </script>" . PHP_EOL, key( $script['data'] ), json_encode( current( $script['data'] ) ) );
  173. echo "<script id="$key-js" src="$script[src]" type="text/javascript"></script>" . PHP_EOL;
  174. }
  175. }
  176. }
  177.  
  178. $header = new mHeader();
  179.  
  180. $header->enqueue_script( 'jquery-ui', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js', array( 'jquery' ) );
  181. $header->enqueue_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' );
  182. $header->enqueue_script( 'custom-script', '//custom-script.min.js', array( 'jquery-ui' ), array( 'mydata' => array( 'value' => 20 ) ) );
  183.  
  184. $header->print_scripts();
  185.  
  186. <script id="jquery-js" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
  187. <script id="jquery-ui-js" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>
  188. <script> var mydata = {"value":20}; </script>
  189. <script id="custom-script-js" src="//custom-script.min.js" type="text/javascript"></script>
  190.  
  191. myPlugin.start($val); // tried this, didn't work
  192.  
  193. myPlugin.start(); // tried this, didn't work
  194.  
  195. <?php myPlugin.start($val); ?> // this didn't work either
  196.  
  197. myPlugin.start(<?=$val?> // this works sometimes, but sometimes it fails
  198.  
  199. <?php
  200. echo "<script> var x = ". json_encode($phpVariable)."</script>";
  201. ?>
  202.  
  203. <?php
  204.  
  205. $variable_1 = "QNimate";
  206. $variable_2 = "QScutter";
  207.  
  208. ?>
  209. <span id="storage" data-variable-one="<?php echo $variable_1; ?>" data-variable-two="<?php echo $variable_2; ?>"></span>
  210. <?php
  211.  
  212. var variable_1 = undefined;
  213. var variable_2 = undefined;
  214.  
  215. window.onload = function(){
  216. variable_1 = document.getElementById("storage").getAttribute("data-variable-one");
  217. variable_2 = document.getElementById("storage").getAttribute("data-variable-two");
  218. }
  219.  
  220. <script type="text/javascript" src="url_to_your_php_file.php" /></script>
  221.  
  222. <script type="text/javascript" src="url_to_your_php_file.php?var1=value1" /></script>
  223.  
  224. <?php
  225. // THIS IS A SIMPLE EXAMPLE
  226. // it demonstrates one method of using the src attribute to link
  227. // to a PHP file which can generate javascripts dynamically
  228. // and share data between PHP and javascript
  229. // you may take this learning example and develop it further
  230. // relying on your own coding skills for validating data
  231. // and avoiding errors, of course
  232. header( 'content-type: text/javascript' );
  233.  
  234. // if you pass a $_GET variable from the javascript
  235. // you should add code to validate your $_GET variable(s)
  236.  
  237. // you can add code to query a database
  238. // using $_GET['var1'] or some other criteria
  239.  
  240. // you can add simple variable assignments
  241. $value = 'some value';
  242.  
  243. // for the OP's needs (assumes the class object has been defined)
  244. $val = $myService->getValue();
  245.  
  246. ?>
  247. function name() {
  248. // pay attention because you need to use quotes properly
  249. // and account for possible quotes in the variable strings
  250. // to avoid both php and javascript errors
  251. // example assumes $val has been returned as a string
  252. // validate $val as needed using your method of choice
  253. var example1 = '<?php echo '"' . $val . '"'; ?>';
  254. var example2 = '<?php echo '"' . $value . '"'; ?>';
  255. var example3 = '<?php echo '"some other data"'; ?>';
  256. alert( example1 + ' / ' + example2 );
  257. }
  258. <?php
  259. // you may even want to include additional files (.php or .js, etc)
  260. @include 'local_path_to_some_other_js_file.js';
  261. @include 'local_path_to_some_other_php_file.php';
  262.  
  263. exit;
  264. ?>
  265.  
  266. <?php
  267. $name = 'PHP variable';
  268. echo '<script>';
  269. echo 'var name = ' . json_encode($name) . ';';
  270. echo '</script>';
  271. <?
  272. <script>
  273. console.log("i am everywhere " + name);
  274. </script>
  275.  
  276. <?php
  277. $myvar = "I'm in "UTF-8" encoding and I have <script>script tags</script> & ampersand!";
  278. // Fails:
  279. //echo '<body onload="alert(', json_encode($myvar), ');">';
  280. // Fails:
  281. //echo "<body onload='alert(", json_encode($myvar), ");'>";
  282. // Fails:
  283. //echo "<body onload='alert(", htmlspecialchars(json_encode($myvar)), ");'>";
  284.  
  285. // Works:
  286. //echo "<body onload='alert(", htmlspecialchars(json_encode($myvar), ENT_QUOTES), ");'>";
  287. // Works:
  288. echo '<body onload="alert(', htmlspecialchars(json_encode($myvar)), ');">';
  289.  
  290. echo "</body>";
  291.  
  292. <?php
  293.  
  294. // Optionally pass the encoding of the source string, if not UTF-8
  295. function escapeJSString($string, $encoding = 'UTF-8')
  296. {
  297. if ($encoding != 'UTF-8')
  298. $string = iconv($encoding, 'UTF-8', $string);
  299. $flags = JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_SLASHES;
  300. $string = substr(json_encode($string, $flags), 1, -1);
  301. return "'$string'";
  302. }
  303.  
  304. <?php
  305. $myvar = "I'm in "UTF-8" encoding and I have <script>script tags</script> & ampersand!";
  306. // Note use of double quotes to enclose the event definition!
  307. echo '<body onload="alert(', escapeJSString($myvar), ');">';
  308. // Example with regular code:
  309. echo '<script>alert(', escapeJSString($myvar), ');</script>';
  310. echo '</body>';
  311.  
  312. <$php
  313. $val = $myService->getValue(); // makes an api and db call
  314. echo '<span id="value">'.$val.'</span>';
  315. $>
  316.  
  317. <?PHP
  318. $number = 4;
  319.  
  320. echo '<script>';
  321. echo 'var number = ' . $number . ';';
  322. echo 'alert(number);';
  323. echo '</script>';
  324.  
  325. ?>
  326.  
  327. <script>var number = 4;alert(number);</script>
  328.  
  329. <script>var number = abcd;alert(number);</script>
  330.  
  331. <?PHP
  332. $number = 'abcd';
  333.  
  334. echo '<script>';
  335. echo 'var number = ' . json_encode($number) . ';';
  336. echo 'alert(number);';
  337. echo '</script>';
  338.  
  339. ?>
  340.  
  341. <script>var number = "abcd";alert(number);</script>
  342.  
  343. <?PHP
  344. $details = [
  345. 'name' => 'supun',
  346. 'age' => 456,
  347. 'weight' => '55'
  348. ];
  349.  
  350. echo '<script>';
  351. echo 'var details = ' . json_encode($details) . ';';
  352. echo 'alert(details);';
  353. echo 'console.log(details);';
  354. echo '</script>';
  355.  
  356. ?>
  357.  
  358. <script>var details = {"name":"supun","age":456,"weight":"55"};alert(details);console.log(details);</script>
  359.  
  360. <?php
  361.  
  362. $servername = "localhost";
  363. $username = "";
  364. $password = "";
  365. $dbname="";
  366. $conn = new mysqli($servername, $username, $password,$dbname);
  367.  
  368. if ($conn->connect_error) {
  369. die("Connection failed: " . $conn->connect_error);
  370. }
  371.  
  372. $sql = "SELECT id, name ,image FROM phone";
  373. $result = $conn->query($sql);
  374.  
  375. while($row =$result->fetch_assoc()){
  376. $v[]=$row;
  377. }
  378.  
  379. echo json_encode($v);
  380.  
  381. $conn->close();
  382. ?>
  383.  
  384. function showUser(fnc) {
  385. var xhttp = new XMLHttpRequest();
  386.  
  387. xhttp.onreadystatechange = function() {
  388. if (this.readyState == 4 && this.status == 200) {
  389. // STEP 3
  390. var p=JSON.parse(this.responseText);}
  391. }
  392. }
  393.  
  394. <?php
  395. $your_php_variable= 22;
  396. echo "<script type='text/javascript'>var your_javascript_variable = $your_php_variable;</script>";
  397. ?>
  398.  
  399. <?php
  400. $username = 1;
  401. ?>
  402.  
  403. <script type="text/javascript">
  404. var myData = <?php echo $username ?>;
  405. console.log(myData);
  406. alert(myData);
  407. </script>
Add Comment
Please, Sign In to add comment