Web Programming Training By OM SIR Call for free Demo :9320957717/18

Ajax onclick event example

(1)write code for  ajaxform.html :

function ajax_post()
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "insert.php";
    var id = document.getElementById("id").value;
    var nm = document.getElementById("name").value;


    var vars = "id="+id+"&name="+nm;
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
          if(hr.readyState == 4 && hr.status == 200) {
                      var return_data = hr.responseText;
                              document.getElementById("status").innerHTML = return_data;
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";

<div id="status"></div>
<input type="text" id="id" name="id">
<input type="text" id="name" name="name">

<input name="myBtn" type="submit" value="postbutton" onclick="ajax_post();">


(2)write code for insert.php  file:
include('connectivity.php'); //connectivity code
$id=$_POST['id']; // form value by text name=myid
$name=$_POST['name']; //form valu by text name=myname

$sql="insert into record(id,name) values('$id','$name')"; //insert command

$result=mysql_query($sql); //go
echo "record inserted";
echo "record not inserted";

Next Post »


Write comments