0

in the server app I'm creating a hash string of all the HTML output I'm going to send:

ob_start();

?>
<!DOCTYPE HTML>
<html>
...
</html>

<?php

$html = ob_get_clean();

$hash = md5($html);

print $html;
exit;

How can I send the hash string too, but in some way that the javascript is able to read it?

I thought about adding it with header() before calling print but it appears that javascript cannot read page headers, only in ajax mode but this is not an ajax request :/

thelolcat
  • 10,995
  • 21
  • 60
  • 102
  • possible duplicate of [Pass a PHP string to a JavaScript variable (and escape newlines)](http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines) – John Dvorak Feb 01 '14 at 04:45
  • it's not, I'm not looking to put the variable inside the html, because I'm hashing the html lol – thelolcat Feb 01 '14 at 04:46

2 Answers2

0

You could just add this line to your php script:

echo '<script>var hash = ' . $hash . ';</script>';

Then your hash will be available through "hash" javascript variable.

If you want to do this asynchronously, you must use AJAX. AJAX is useful when you want to do an http request without having to reload the entire page. I suggest you to use JQuery, as it's way easier than javascript for ajax calls. Usually, you call ajax on a user event (e.g: button click)

An example of a JQuery implementation would be:

$('.showHashButton').onclick(function(){
    var pageHtml = $("html").html();
    $.get( "url_to_your_server_script", { html: pageHtml} )
      .done(function( data ) {
        alert(data); //show the hash
      });
});

An example of a PHP script implementation:

<?php
echo md5($_GET('html'));
?>

If you have any question, please leave a comment below!

leblma
  • 174
  • 7
0

Here's a full working sample using standard JavaScript. The final DIV tag is not included in the md5 hash. Read the comment in the script for jQuery instructions. Hope this helps!

<?php
ob_start();
?>
<!DOCTYPE HTML>
<html>


<body onLoad="afterLoad();">
<p>...content...</p>
<script>
  // you can also use jQuery(document).ready(function(){...});
  // instead of the onLoad() in body.
  function afterLoad() {
    var md5=document.getElementById('md5hash').innerHTML;
    alert(md5);
  }
</script>
</body>
</html>

<?php

$html = ob_get_clean();

$hash = md5($html);

print $html.'<div id="md5hash" style="visibility: hidden">'.$hash.'</div>';
exit;

?>
David H. Bennett
  • 1,822
  • 13
  • 16