http://icyarena.com
http://icyarena.com
How to make ajax request without jquery,using only javascript
  Posted by : Color Picker     Date : 06 February       Leave a comment
Many people learns jquery,ajax without knowing basic javascript.But if you are a web developer or do not want to include jquery plugin that is about 100 KB,you may follow this article to learn how to fetch data from a url and showing it within a div using only javascript.

Steps

1
Make a basic html page that contains one div box and one button.When we will click on that button a request will be sent to browser and it will show data whithin div box.
  • Copy following codes and paste in Notepad than save it as index.html.
    <html>
    <title>how to make ajax request without jquery,using only javascript</title> 
    <body>
    <div id="ajax_div" style="height:100px;">
    	This text is replaced when you click on the button
    </div>
    <button id="Clickme_to_load" type="button">Click Me!</button>
    <script type="text/javascript">
    function ajaxRequest(url,divid){
    	var xmlhttp;
    	if (window.XMLHttpRequest){//for new browser
    		xmlhttp=new XMLHttpRequest();
    	}else{//for old browser
    		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    	}
    	xmlhttp.onreadystatechange=function(){
    		if (xmlhttp.readyState==4 && xmlhttp.status==200){
    			var div=document.getElementById(divid);
    			div.innerHTML=xmlhttp.responseText;
    		}
    	}
    	xmlhttp.open("GET",url,true);
    	xmlhttp.send();
    }
    var bt=document.getElementById("Clickme_to_load");//select button
    bt.onclick=(function(){//make a click event
    	ajaxRequest("request.php","ajax_div");
    });
    </script>
    </body>
    </html>
2
Here we are using a function ajaxRequest("Your_URL","div_where_data_load"); that have two arguments one is url and other is div id.
  • Upload this file to your server and test.
    Preview on Browser
    how to make ajax request without jquery,using only javascript
    This text is replaced when you click on the button

Tips

  • Do not forget to upload request.php file to your server.
  • You may request to a php file to fetch dynamic data.
  • You may comment or ask question about this article.Please feel free to contact us.
  • Dont't forget to share this article with your friends.Click here to share.
You may try :