vendredi 31 juillet 2015

Ajax copy text from one textarea to another via post

I am trying to use ajax to post the text from one text area to a php page to echo back into another textarea. When I do this it works for about 5 characters and then stops completely. I've tried with and without encoding doesn't seem to make a difference since I'm just trying simple plan text like "ddddddddddd".

in example.html

<!DOCTYPE html>
<html>
<body>
<style>
.center{
margin: 0 auto;
margin-left: auto;
margin-right: auto;
text-align:center;
}

</style>

<div class="center">

<textarea   onkeyup="changed()" onkeydown="changed()" onkeypress="changed()"  id="b1" rows="30" cols="81">
</textarea>

<textarea id="b2" rows="30" cols="81">
</textarea>

</div>

</body>
</html>
<script>
function changed(){

var text =document.getElementById("b1").value;

if(!text){
text ="";
}

     var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {

                document.getElementById('b2').value =xhr.responseText;

        }
    }

    xhr.open('POST', 'echo.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("text=" + text);



}

</script>

In echo.php

<?php 
 $mytext = $_POST["text"];
 echo $mytext;

?>

I've looked at several similar posts but none of them fix my issue. I'm not using a form. Do I have to? Textarea not POSTing with form

Aucun commentaire:

Enregistrer un commentaire