Skip to content

Instantly share code, notes, and snippets.

@gaboratorium
Last active June 3, 2016 07:13
Show Gist options
  • Save gaboratorium/bdf9a0f45c23d6b7841b797791e5f83e to your computer and use it in GitHub Desktop.
Save gaboratorium/bdf9a0f45c23d6b7841b797791e5f83e to your computer and use it in GitHub Desktop.
Basic #ajax call
// creating the object
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
//all modern browsers
if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); }
//if IE 6 or below
else if (window.ActiveXObject("Microsoft.XMLHTTP"))
{ xmlHttp= new ActiveXObject("Microsoft.XMLHTTP"); }
return xmlHttp;
}
//open connection and send request
function process() {
if (xmlHttp) {
try {
// search = encodeURIComponent (document.getElementById("search").value);
xmlHttp.open("GET", "inc/ajax.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch(e) { alert( e.toString() ); }
}
}
//handle response
function handleServerResponse() {
//Target places(divs) where to paste the new content
target = document.getElementById("target");
//if done
if (xmlHttp.readyState==4) {
//if succesful
if (xmlHttp.status==200) {
try {
//Use this to retrieve all the source code
//xmlResponse=xmlHttp.responseText;
//Use this to retrieve particular elements
//xmlResponse=xmlHttp.responseXML;
//xmlDocumentElement=xmlResponse.documentElement;
//xmlResponse=xmlDocumentElement.firstChild.data;
target.innerHTML += xmlResponse;
} catch(e) {alert(e.toString());}
}
}
}
<?php
header("Content-Type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>";
//do php stuff here
//then print the output
echo "<response>";
echo "Output";
echo "</response>";
?>
<?php
include "inc/credentials.php";
$db = new PDO ($dbInfo,$dbUser,$dbPassword);
?>
<!DOCTYPE html>
<html>
<head>
<title>Ajax Framework</title>
<meta charset="utf-8">
<!-- External CSS -->
<link type="text/css" rel="stylesheet" href="style/style.css">
<!-- Extarnal JS -->
<script src="js/ajax.js"></script>
</head>
<body onload="">
<div id="wrapper">
<button onclick="process()">I run AJAX!</button>
<!-- Paste new content here -->
<div id="target" />
</div> <!-- end of #wrapper -->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment