OneCompiler

Contact det(Ajax)

98

Htmlfile
<<!DOCTYPEhtml>

<html> <head> <title>ContactList</title> <scriptsrc=https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js></script> <scriptsrc=”script.js”></script> </head> <body> <buttonid=”printBtn”>PrintContacts</button> <br><br> <tableid=”contactTable”> <thead> <tr> <th>Sr.No.</th> <th>Name</th> <th>ResidenceNumber</th> <th>MobileNumber</th> <th>Address</th> </tr> </thead> <tbody> <!—Contactlistwillbedisplayedhere </tbody> </table> </body> </html

Ajax file
(document).ready(function(){ //Eventlistenerforprintbutton (“#printBtn”).click(function(){
//AJAXrequesttoreadcontact.datfile
.ajax({ url:“contact.dat”, dataType:“text”, success:function(data){ //Splitthefilecontentsintolines Varlines=data.split(“\n”); //Iterateovereachlineandcreateatablerow VartableRows=“”; For(vari=0;i<lines.length;i++){ Varcolumns=lines[i].split(“,”); If(columns.length==5){//Onlyprocessvalidrows tableRows+=“<tr>”; for(varj=0;j<columns.length;j++){ tableRows+=“<td>”+columns[j]+“</td>”; } tableRows+=“</tr>”; } } //Addthetablerowstothetablebody (“#contactTabletbody”).html(tableRows);
},
Error:function(jqXHR,textStatus,errorThrown){
Alert(“Error:“+errorThrown);
}
});
});
})