Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- ...
- $val = $myService->getValue(); // makes an api and db call
- ?>
- <script>
- myPlugin.start($val); // tried this, didn't work
- <?php myPlugin.start($val); ?> // this didn't work either
- myPlugin.start(<?=$val?> // this works sometimes, but sometimes it fails
- </script>
- /* Do some operation here, like talk to the database, the file-session
- * The world beyond, limbo, the city of shimmers, and Canada.
- *
- * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
- * It all depends on the Content-type header that you send with your AJAX
- * request. */
- echo json_encode(42); //In the end, you need to echo the result.
- //All data should be json_encode()d.
- //You can json_encode() any value in PHP, arrays, strings,
- //even objects.
- <!-- snip -->
- <script>
- function reqListener () {
- console.log(this.responseText);
- }
- var oReq = new XMLHttpRequest(); //New request object
- oReq.onload = function() {
- //This is where you handle what to do with the response.
- //The actual data is found on this.responseText
- alert(this.responseText); //Will alert: 42
- };
- oReq.open("get", "get-data.php", true);
- // ^ Don't block the rest of the execution.
- // Don't wait until the request finishes to
- // continue.
- oReq.send();
- </script>
- <!-- snip -->
- <!-- snip -->
- <div id="dom-target" style="display: none;">
- <?php
- $output = "42"; //Again, do some operation, get the output.
- echo htmlspecialchars($output); /* You have to escape because the result
- will not be valid HTML otherwise. */
- ?>
- </div>
- <script>
- var div = document.getElementById("dom-target");
- var myData = div.textContent;
- </script>
- <!-- snip -->
- <!-- snip -->
- <script>
- var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
- </script>
- <!-- snip -->
- setcookie("MyCookie", $value); // sets the cookie to the value, remember, do not
- // set it with HTTP only to true.
- var cookies = document.cookie.split(";").
- map(function(el){ return el.split("="); }).
- reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});
- cookies["MyCookie"] // value set with php.
- <script>
- var myServerData = <?=json_encode($value)?>; // don't forget to sanitize
- //server data
- </script>
- function callback(data){
- // what do I do with the response?
- }
- var httpRequest = new XMLHttpRequest;
- httpRequest.onreadystatechange = function(){
- if (httpRequest.readyState === 4) {// request is done
- if (httpRequest.status === 200) {// successfully
- callback(httpRequest.responseText);// we're calling our method
- }
- }
- };
- httpRequest.open('GET', "/echo/json");
- httpRequest.send();
- $.get("/your/url").done(function(data){
- // what do I do with the data?
- });
- <$php
- ...
- $val = myService->getValue(); // makes an api and db call
- echo json_encode($val); // write it to the output
- $>
- <div class="service-container" data-service="<?php echo $myService->getValue(); ?>">
- </div>
- <script>
- $(document).ready(function() {
- $('.service-container').each(function() {
- var container = $(this);
- var service = container.data('service');
- // service variable now contains the value of $myService->getValue();
- });
- });
- </script>
- <script>
- var jsvar = <?php echo json_encode($PHPVar); ?>;
- </script>
- <script type="text/javascript">
- var js_variable = '<?php echo $php_variable;?>';
- <script>
- <script type="text/javascript">
- var js_variable = <?php echo json_encode($php_variable); ?>;
- </script>
- class mHeader {
- private $scripts = array();
- /**
- * @param string $id unique script identifier
- * @param string $src script src attribute
- * @param array $deps an array of dependencies ( script identifiers ).
- * @param array $data an array, data that will be json_encoded and available to the script.
- */
- function enqueue_script( $id, $src, $deps = array(), $data = array() ) {
- $this->scripts[$id] = array( 'src' => $src, 'deps' => $deps, 'data' => $data );
- }
- private function dependencies( $script ) {
- if ( $script['deps'] ) {
- return array_map( array( $this, 'dependencies' ), array_intersect_key( $this->scripts, array_flip( $script['deps'] ) ) );
- }
- }
- private function _unset( $key, &$deps, &$out ) {
- $out[$key] = $this->scripts[$key];
- unset( $deps[$key] );
- }
- private function flattern( &$deps, &$out = array() ) {
- foreach( $deps as $key => $value ) {
- empty($value) ? $this->_unset( $key, $deps, $out ) : $this->flattern( $deps[$key], $out );
- }
- }
- function print_scripts() {
- if ( !$this->scripts ) return;
- $deps = array_map( array( $this, 'dependencies' ), $this->scripts );
- while ( $deps )
- $this->flattern( $deps, $js );
- foreach( $js as $key => $script ) {
- $script['data'] && printf( "<script> var %s = %s; </script>" . PHP_EOL, key( $script['data'] ), json_encode( current( $script['data'] ) ) );
- echo "<script id="$key-js" src="$script[src]" type="text/javascript"></script>" . PHP_EOL;
- }
- }
- }
- $header = new mHeader();
- $header->enqueue_script( 'jquery-ui', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js', array( 'jquery' ) );
- $header->enqueue_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' );
- $header->enqueue_script( 'custom-script', '//custom-script.min.js', array( 'jquery-ui' ), array( 'mydata' => array( 'value' => 20 ) ) );
- $header->print_scripts();
- <script id="jquery-js" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
- <script id="jquery-ui-js" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>
- <script> var mydata = {"value":20}; </script>
- <script id="custom-script-js" src="//custom-script.min.js" type="text/javascript"></script>
- myPlugin.start($val); // tried this, didn't work
- myPlugin.start(); // tried this, didn't work
- <?php myPlugin.start($val); ?> // this didn't work either
- myPlugin.start(<?=$val?> // this works sometimes, but sometimes it fails
- <?php
- echo "<script> var x = ". json_encode($phpVariable)."</script>";
- ?>
- <?php
- $variable_1 = "QNimate";
- $variable_2 = "QScutter";
- ?>
- <span id="storage" data-variable-one="<?php echo $variable_1; ?>" data-variable-two="<?php echo $variable_2; ?>"></span>
- <?php
- var variable_1 = undefined;
- var variable_2 = undefined;
- window.onload = function(){
- variable_1 = document.getElementById("storage").getAttribute("data-variable-one");
- variable_2 = document.getElementById("storage").getAttribute("data-variable-two");
- }
- <script type="text/javascript" src="url_to_your_php_file.php" /></script>
- <script type="text/javascript" src="url_to_your_php_file.php?var1=value1" /></script>
- <?php
- // THIS IS A SIMPLE EXAMPLE
- // it demonstrates one method of using the src attribute to link
- // to a PHP file which can generate javascripts dynamically
- // and share data between PHP and javascript
- // you may take this learning example and develop it further
- // relying on your own coding skills for validating data
- // and avoiding errors, of course
- header( 'content-type: text/javascript' );
- // if you pass a $_GET variable from the javascript
- // you should add code to validate your $_GET variable(s)
- // you can add code to query a database
- // using $_GET['var1'] or some other criteria
- // you can add simple variable assignments
- $value = 'some value';
- // for the OP's needs (assumes the class object has been defined)
- $val = $myService->getValue();
- ?>
- function name() {
- // pay attention because you need to use quotes properly
- // and account for possible quotes in the variable strings
- // to avoid both php and javascript errors
- // example assumes $val has been returned as a string
- // validate $val as needed using your method of choice
- var example1 = '<?php echo '"' . $val . '"'; ?>';
- var example2 = '<?php echo '"' . $value . '"'; ?>';
- var example3 = '<?php echo '"some other data"'; ?>';
- alert( example1 + ' / ' + example2 );
- }
- <?php
- // you may even want to include additional files (.php or .js, etc)
- @include 'local_path_to_some_other_js_file.js';
- @include 'local_path_to_some_other_php_file.php';
- exit;
- ?>
- <?php
- $name = 'PHP variable';
- echo '<script>';
- echo 'var name = ' . json_encode($name) . ';';
- echo '</script>';
- <?
- <script>
- console.log("i am everywhere " + name);
- </script>
- <?php
- $myvar = "I'm in "UTF-8" encoding and I have <script>script tags</script> & ampersand!";
- // Fails:
- //echo '<body onload="alert(', json_encode($myvar), ');">';
- // Fails:
- //echo "<body onload='alert(", json_encode($myvar), ");'>";
- // Fails:
- //echo "<body onload='alert(", htmlspecialchars(json_encode($myvar)), ");'>";
- // Works:
- //echo "<body onload='alert(", htmlspecialchars(json_encode($myvar), ENT_QUOTES), ");'>";
- // Works:
- echo '<body onload="alert(', htmlspecialchars(json_encode($myvar)), ');">';
- echo "</body>";
- <?php
- // Optionally pass the encoding of the source string, if not UTF-8
- function escapeJSString($string, $encoding = 'UTF-8')
- {
- if ($encoding != 'UTF-8')
- $string = iconv($encoding, 'UTF-8', $string);
- $flags = JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_SLASHES;
- $string = substr(json_encode($string, $flags), 1, -1);
- return "'$string'";
- }
- <?php
- $myvar = "I'm in "UTF-8" encoding and I have <script>script tags</script> & ampersand!";
- // Note use of double quotes to enclose the event definition!
- echo '<body onload="alert(', escapeJSString($myvar), ');">';
- // Example with regular code:
- echo '<script>alert(', escapeJSString($myvar), ');</script>';
- echo '</body>';
- <$php
- $val = $myService->getValue(); // makes an api and db call
- echo '<span id="value">'.$val.'</span>';
- $>
- <?PHP
- $number = 4;
- echo '<script>';
- echo 'var number = ' . $number . ';';
- echo 'alert(number);';
- echo '</script>';
- ?>
- <script>var number = 4;alert(number);</script>
- <script>var number = abcd;alert(number);</script>
- <?PHP
- $number = 'abcd';
- echo '<script>';
- echo 'var number = ' . json_encode($number) . ';';
- echo 'alert(number);';
- echo '</script>';
- ?>
- <script>var number = "abcd";alert(number);</script>
- <?PHP
- $details = [
- 'name' => 'supun',
- 'age' => 456,
- 'weight' => '55'
- ];
- echo '<script>';
- echo 'var details = ' . json_encode($details) . ';';
- echo 'alert(details);';
- echo 'console.log(details);';
- echo '</script>';
- ?>
- <script>var details = {"name":"supun","age":456,"weight":"55"};alert(details);console.log(details);</script>
- <?php
- $servername = "localhost";
- $username = "";
- $password = "";
- $dbname="";
- $conn = new mysqli($servername, $username, $password,$dbname);
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- $sql = "SELECT id, name ,image FROM phone";
- $result = $conn->query($sql);
- while($row =$result->fetch_assoc()){
- $v[]=$row;
- }
- echo json_encode($v);
- $conn->close();
- ?>
- function showUser(fnc) {
- var xhttp = new XMLHttpRequest();
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- // STEP 3
- var p=JSON.parse(this.responseText);}
- }
- }
- <?php
- $your_php_variable= 22;
- echo "<script type='text/javascript'>var your_javascript_variable = $your_php_variable;</script>";
- ?>
- <?php
- $username = 1;
- ?>
- <script type="text/javascript">
- var myData = <?php echo $username ?>;
- console.log(myData);
- alert(myData);
- </script>
Add Comment
Please, Sign In to add comment