Feeds:
Posts
Comments

Ajax response using json

If you use ajax response as a JSON

<html>
	<head>
	<script type="text/javascript">
		function testAjax() {
			var ajaxRequest;  // The variable that makes Ajax possible!
			try {
				// Opera 8.0+, Firefox, Safari
				ajaxRequest = new XMLHttpRequest();
			}
			catch (e) {
				// Internet Explorer Browsers
				try {
					ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch (e) {
					try {
						ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
					}
					catch (e) {
						// Something went wrong
						alert("Your browser broke!");
						return false;
					}
				}
			}
			ajaxRequest.onreadystatechange = function() {
				if(ajaxRequest.readyState == 4) {
					var result=eval('(' + ajaxRequest.responseText + ')');
					alert(result.fname);
				}
			}
			var queryString = 'test.php';
			ajaxRequest.open("GET",queryString, true);
			ajaxRequest.send(null);
		}
	</script>
	</head>
	<body>
	<input type="button" name="view" value="show" onclick="testAjax();">
	</body>
</html>

in test.php file you will write

<?php 
echo '{"fname":"Brian", "lname":"Chess", "phone":"6502135600",
"purchases":60000.00, "email":"brian@fortifysoftware.com" }';
?>

Ajax response using xml

The server returns this XML document:

<books>
    <book>
       <title>JavaScript, the Definitive Guide</title>
       <publisher>O'Reilly</publisher>
       <author>David Flanagan</author>
       <cover src="/images/cover_defguide.jpg" >
    </book>
    <book>
        <title>DOM Scripting</title>
        <publishe>Friends of Ed</publisher>
        <author>Jeremy Keith</author>
        <cover src="/images/cover_domscripting.jpg" />
    </book>
    <book>
        <title>DHTML Utopia: Modern Web Design using JavaScript DOM</title>
        <publisher>Sitepoint</publishe>
        <author>Stuart Langridge</author>
        <cover src="/images/cover_utopia.jpg" />   
    </book>
</books>

To show the response we need to create a div with id=writeroot

<html>
	<head>
	<script type="text/javascript">
		function testAjax() {
			var ajaxRequest;  // The variable that makes Ajax possible!
		 	try {
		 		// Opera 8.0+, Firefox, Safari
		 		ajaxRequest = new XMLHttpRequest();
	 		}
		 	catch (e) {
		 		// Internet Explorer Browsers
		 		try {
		 			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		 		}
		 		catch (e) {
		 		try {
		 			ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
		 		}
		 		catch (e) {
		 			// Something went wrong
		 			alert("Your browser broke!");
		 			return false;
		 		}
	 		}
		 }
		 ajaxRequest.onreadystatechange = function() {
		 	if(ajaxRequest.readyState == 4) { 
		 		var books = ajaxRequest.responseXML.getElementsByTagName('book');
		 		for (var i = 0; i < books.length; i++) {
					var x = document.createElement('div');
					x.className = 'book';
					x.style.backgroundColor='#00FFFF';
					x.style.paddingLeft='50px';
					var y = document.createElement('h3');
					y.appendChild(document.createTextNode(getNodeValue(books[i],'title')));
					x.appendChild(y);
					var z = document.createElement('p');
					z.className = 'moreInfo';
					z.appendChild(document.createTextNode('By ' + getNodeValue(books[i],'author') + ', ' + getNodeValue(books[i],'publisher')));
					x.appendChild(z);
					var a = document.createElement('img');
					a.src = books[i].getElementsByTagName('cover')[0].getAttribute('src');
					x.appendChild(a);
					var b = document.createElement('p');
					b.appendChild(document.createTextNode(getNodeValue(books[i],'blurb')));
					x.appendChild(b);
					document.getElementById('writeroot').appendChild(x);
		 		}
		 	}
		 }
		 var queryString = 'test.php'; 
		 ajaxRequest.open("GET",queryString, true);
		 ajaxRequest.send(null); 
	}
	function getNodeValue(obj,tag)
	{
	 return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
	}
	</script>
	</head>
        <body>
        <div id="writeroot">
        </div>
   <input type="button" name="view" value="show" onclick = "testAjax();">
       </body>
</html>

before sending the response from server you need to use header(‘content-type:text/xml’)

if you want to send Ajax GET Request


function testAjax() {
    var ajaxRequest;  // The variable that makes Ajax possible!
    var id=document.getElementById('test').value;
     try {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer Browsers
    try {
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
           ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
       }
    catch (e) {
        // Something went wrong
        alert("Your browser broke!");
        return false;
    }
  }
}

ajaxRequest.onreadystatechange = function() {
     if(ajaxRequest.readyState == 4) {
          var result = ajaxRequest.responseText;
          // if response will be in xml format then u need to use
         //var result=ajaxRequest.responseXML;
       }
}
var queryString = 'test.php?id=5';
ajaxRequest.open("GET",queryString, true); // sending ajax request to test.php file
ajaxRequest.send(null);
}

 


In test.php file if you echo $_GET['id'] you will get 5 as a response


If you using ajax post request then

function testAjax() {
    var ajaxRequest;  // The variable that makes Ajax possible!
    var id=document.getElementById('test').value;
    try {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer Browsers
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
        try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {
           // Something went wrong
           alert("Your browser broke!");
           return false;
        }
    }
}

ajaxRequest.onreadystatechange = function() {
    if(ajaxRequest.readyState == 4) {
         var result = ajaxRequest.responseText;
         // if response will be in xml format then u need to use
         //var result=ajaxRequest.responseXML;
    }
}
var queryString = 'test.php';
var params = 'id=5';
ajaxRequest.open("POST",queryString,true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
 


In test.php file if you echo $_POST['id'] you will get 5 as a response

There are good tips for php beginner http://nikhilmisal.com

Follow

Get every new post delivered to your Inbox.