Search code examples
javascriptpopuptextareapreview

Popup preview of a textarea using a PHP function


I'd like to make a popup preview of a textarea, using a PHP function inside the popup.

Let's say you type "Hello world" in the textarea, then you click "preview" and you get your text converted to "Hey you" by a PHP function in a popup (of course the function is not that simple, that's the reason why I can't adapt this in pure javascript).

Is it possible to do so ?

I know it could easily send the form to an intermediate page, but I must keep the form in background... that's why I need a quick preview on fly.

I did the following:

        function PreviewMe() {
          var newWin = window.open("", "_blank");
         newWin.document.write("<html><body>"+document.getElementById('myText').value+"</body></html>");
          newWin.document.close();
        }

and

<textarea id="myText"  ... /> 
<input type="submit" ... onclick="PreviewMe();">

Obviously it works without reformatting anything, so how to reformat this result in the popup please ?

Would it be possible (and mayber a better option) to use XMLHttpRequest ?

Thx !


Solution

  • Thanks, it was by far easier in the end.

    In case it might help others, here is what I've done. Js function became :

    function PreviewMe() {
        var xhr = null;
        if (window.XMLHttpRequest || window.ActiveXObject) {
            if (window.ActiveXObject) {
                try {
                    xhr = new ActiveXObject("Msxml2.XMLHTTP");
                } catch(e) {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
            } else {
                xhr = new XMLHttpRequest(); 
            }
        } else {
            alert("XMLHTTPRequest not supported...");
            return;
        }
        xhr.open("POST", "page.php", true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
                document.getElementById('show').innerHTML = xhr.responseText;
            } 
        };      
    
        xhr.send("var="+document.getElementById('myText').value+"");
        return;
    }
    

    Of course page.php includes my PHP function, show is the id of the div where the result is printed.