I have a textarea text field. I need that when you press Enter, the data of this form is sent by the POST method to the file "ajax.php". As you understand, you need to do this with js and ajax.

<script> function getXmlHttp(){ var xmlhttp; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } function sendAjax(textSend){ if((event.keyCode==10)||(event.keyCode==13)) { /************************************/ } textSend.value=''; } </script> <textarea onkeydown="sendAjax(this)"></textarea> 

instead of these asterisks you need to put the necessary code. Thanks in advance

    1 answer 1

    Something like this, ajax asynchronous:

     var request = getXmlHttp(); // глобальная переменная request.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200 ) { var serverResponse = this.responseText; // alert(serverResponse); // -> ответ сервера // тут можно как-то продолжить цепочку событий ... // например очистить textarea document.getElementById("yourTextAreaId").value = ''; } } // тело if'a var texterea = document.getElementById("yourTextAreaId"); if(textarea.value != '') { // если значение не пустое request.open("POST", "/yourScript.php", true); request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); request.send("textareaData=" + textarea.value); // на сервер прийдет $_POST['textareaData'] } 

    To pass several parameters to request.send, you need to write something like this:

      request.send("param1=value1&param2=value2&param3=value3 .... "); 

    Generally for these purposes it is best to write a function

     function prepareParams(paramsObj) { var paramsString = ''; for(i in paramsObj) { paramsString += i + "=" + paramsObj[i] + "&"; } return paramsString.slice(0, -1); } 

    Apply something like this:

     request.send(prepareParams({ param1 : "value1", param2 : "value2", param3 : "value3" .......... paramN : "valueN" })); 

    In the example you cited:

      request.send(prepareParams({ textareaData : textarea.value, textareaData2 : textarea2.value }));