Tuesday, 20 November 2012

How to call ajax with javascript

How to call ajax with javascript
   its so simple just call javascript function onclick or onchange or onblur or onhover,
   on which event you want to call the function its depend on you.
  
 create  callajax.php
  

  <html>
  <head>


 <script>
 
  function callajax()
  {
  stateval=document.getElementById('state').value;
  if(Window.XMLHTTP)
  {
  xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
  }
  else
  {
  xmlhttp=new XMLHttpRequest();
  }
  xmlhttp.onreadystatechange=function(){
 if(xmlhttp.readyState==4 && xmlhttp.status==200)
 {
 document.getElementById('citytd').innerHTML=xmlhttp.responseText;
 }
  }
  xmlhttp.open('GET','ajax.php?state_id='+stateval,true);
  xmlhttp.send()
  }
  </script>
  </head>
  <body>
  <table>
  <tr>
  <td>name</td><td><select name="state" id="state" onchange="callajax()">
  <option>select state</option>
  <option value="1" >Alaska</option>
  <option value="2" >Alabama</option>
  <option value="3" >California</option>
  <option value="4" >Florida</option>
  </select>
  </td></tr>
<tr> <td>address</td><td id="citytd"><select name="city" id="city"><option>Select City from here</option></select></td>
  </tr>
 
  </table>
 
  </body>
  </html>
 
 
  Now below code is ajax.php, where you will execute your code and display on call ajax.php
 
  ajax.php
 
  <!-- write you code here, you can use the $_GET['state_id'] and select the data of city from database -->
<!-- here i am typing only static content -->
<select><option>apol</option><option>ajax</option></select>



Note: You can customize your code according to your requirement

No comments:

Post a Comment