JavaScript has a built-in XMLHttpRequest object. You can use that for Firefox, Safari, and Opera. For Internet Explorer use the ActiveXObject, there is also a difference between IE 5.0 and IE 6.0+ in how to create the object.
Read The Full Tutorial.
In this article we will create a simple php tutorials, and how can we use AJAX with PHP.
1. Create an XMLHttpRequest object
The following codes creates an XMLHttpRequest for all browsers:
var req;
if(window.XMLHttpRequest){ //For Firefox, Safari, Opera req = new XMLHttpRequest(); } else if(window.ActiveXObject){ //For IE 5 req = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.ActiveXObject){ //For IE 6+ req = new ActiveXObject("Msxml2.XMLHTTP"); } else{ //Error for an old browser alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera'); }
Here, first we are using the built-in JavaScript function XMLHttpRequest() for creating an XMLHttpRequest for Firefox, Safari and Opera. If the browser does support window.ActiveXObject, then it is Internet Explorer. For IE versions 5.0+, use new ActiveXObject("Microsoft.XMLHTTP") and for IE 6.0+ use new ActiveXObject("Msxml2.XMLHTTP"). If the browser does not support the built-in JavaScript function XMLHttpRequest() or ActiveXObject, then it does not support AJAX. You can also use JavaScript try-catch blocks for the same output.
var req; try { // Firefox, Opera, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera'); } } }
2. Request for a web page
After creating the XMLHttpRequest we now need to send a request for a web page
req.open(“GET”,”somedata.php”); req.send(null);
3. Monitor for the response of the request
You now need to monitor for the state of the request.you can do by this code
req.onreadystatechange=function() { if(req.readyState==4 && req.status == 200) { var resp = req.responseText; } }
|