Send an ajax request

From PROGRAMAGE
Jump to navigation Jump to search


In order to send an ajax request to the server using JavaScript we use the XMLHttpRequest() Object embedded into most modern web browsers, the code below helps achieve most of the requirement to send and receive responses without reloading the current web page :

<syntaxhighlight lang="Javascript"> function send_comment(task_id){ //alert('Function is answering'); var method='POST'; var filename='add_comment.php'; var comment = document.getElementById("textarea_"+task_id).value; var request='comment='+comment; var xhr=new XMLHttpRequest(); xhr.onreadystatechange = function() {

   			if (this.readyState == 4 && this.status == 200) {
     				alert(this.responseText);
   			}
 			};						

xhr.open(method,filename,true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send(request); }

</syntaxhighlight>