myajaxcall v2.1.6
Video deutsch/german Klicke hier für die deutsche Beschreibung!
New in this version!
- Examples revised!
- Scripts with the attribute src are loaded into the head tag and appended with a version number.
- Scripts with the attribute value type = "module", i.e. modules, are taken into account
What is lib.myAJAX?
myAJAX is a function that helps you to make AJAX calls in a simple way
You can integrate files (.html, .php, .txt etc.) at a defined point (ID) in the DOM (HTML).
Benefits!
When using this feature:
- files are integrated in a defined location (ID),
- all Javascript scripts will executed for the called HTML files,
- PHP / HTML and Javascript scripts are executed in the PHP files,
the src attribute is taken into account. The named file is integrated and executed, e.g .:
<script src="myScript.js"><script>
CSS files are transferred to the head tag and placed in front of the first script-tag (if available).
- Form data will be transmitted with "GET" or "POST" when called,
- a callback function can be called which has access to all essential data (see example 3 below)!
Installation
for testing purposes
Simply link the script tag as follows:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/myajaxcall@2.1.6/myajax_bundle.min.js"></script>
</head>
<body>
</body>
</html>
locale installation
create a package.json
npm init
Install the package
npm i myAJAXcall
Include (e.g. in the index.html)
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
</body>
</html>
Working method and examples
The function is called with:
lib.myAJAX(obj)
Object-Properties
const obj={
site: site-source, // required
contentID: ID, // default null
CSStoHead: boolean, // default True
form: form-control, // default null
user: username, // default null
psw: password, // default null
headers: objHeaders, // default null
callback: callbackFunction // dwfault null
}
lib.myAJAX(obj);
Properties
- site: file that you want to integrate into your current page withlib.myAJAX, e.g .: "myFile.php"
- contentID: the ID at which you want to integrate the called AJAX site
- CSStoHead: if you do not want the link tags of your called page to be moved to the head tag of the current page. e.g.:
{... CSStoHead: false...}
By default, the link-tags are moved to the last place in the head tag, but before the first script-tag - form: Formcontrol like document.getElementById("formID")
- user: username for login in called file (example below)
- psw: password for login in called file (example below)
- headers: an object array consisting of headers (example below)
- callback: a callback function that is called after the asynchronous functionlib.myAJAX has been executed.
Not all parameters are necessary!
Example:
const obj={
site: "sites/php/Table.php",
contentID: "insertTableHere",
form: document.getElementById("myForm")
}
lib.myAJAX(obj);
simple examples and explanations
Example 1: Filename and ID
The index.html calls the test.html and inserts its content in the h1 tag in place of the span tag with the ID content.
test.html
<i>Welt</i>
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<h1>Hallo <span id="content"></span>!</h1>
<script>
new lib.myAJAX({site:"test.html", contentID:"content"});
</script>
</body>
</html>
Example 2: Transfer of form data to a PHP script
After the submit button has been pressed, the form data is transferred to the PHP script showInput.php and the result is then saved in the index.html in the div tag with the ID showData.
Important: please do not forget the command event.preventDefault() !
showInput.php
<?php
$user = $_GET['user'];
$psw = $_GET['pwd'];
echo "Input user: $user <br>";
echo "Input passw: $psw";
?>
Important: please do not forget the command event.preventDefault() ! index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<form method="GET" action="showInput.php" id="form1">
<label for="user"></label>
<input type="text" name="user">
<label for="pwd"></label>
<input type="text" name="pwd">
<input type="submit">
</form>
<div id="showData"></div>
<script>
document.getElementById("form1").addEventListener("submit",
function(event){
event.preventDefault();
const FORM = document.getElementById("form1");
const ACTION_SCRIPT = FORM.getAttribute("action");
new lib.myAJAX({site: ACTION_SCRIPT, contentID: "showData", form: FORM});
})
</script>
</body>
</html>
The transmission method (POST / GET) is determined automatically by lib.myAJAX () from the form tag!
Callback function
There is the possibility of the function libmyAJAX () to integrate a callback function, which has access to all information that the executed AJAX call has determined.
Structure of the callback function
functionName(response, responseText, responseXML, responseURL, responseType, responseHeaders)
- response: property returns the response's body content as an ArrayBuffer, Blob, Document, JavaScript Object, or DOMString, depending on the value of the request's responseType property.
- responseText: get the response data as a string
- responseXML: get the response data as XML data
- responseURL: property returns the serialized URL of the response or the empty string if the URL is null. If the URL is returned, any URL fragment present in the URL will be stripped away. The value of responseURL will be the final URL obtained after any redirects.
- responseType: is an enumerated string value specifying the type of data contained in the response.
- responseHeader: all response headers (see example below)
Example 3: Callback, receives JSON data from a PHP file.
JSON.php
<?php
$ary=[
["name"=>"Otto"],
["name"=>"Torsten"],
["name"=>"Melly"]
];
echo json_encode($ary);
?>
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<button id="btn">Data</button>
<div id="data"></div>
<script>
document.getElementById("btn").addEventListener("click",
function(){
new lib.myAJAX({site: "JSON.php", callback: myCallback});
})
function myCallback(res){
const arr=JSON.parse(res);
const myData = arr[2].name;
document.getElementById("data").innerHTML=myData;
}
</script>
</body>
</html>
Example 4: Authentication, user/password.
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<button id="btn">Data</button>
<div id="data"></div>
<script>
document.getElementById("btn").addEventListener("click",
function(){
let username = "admin";
let password = "1234";
new lib.myAJAX({site: "auth.php", contentID: "data", user: username, psw: password});
})
</script>
</body>
</html>
auth.php
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'The second round get user and pwd!';
exit;
} else if ($_SERVER['PHP_AUTH_USER'] == "admin" and $_SERVER['PHP_AUTH_PW'] =="1234"){
echo "You logged in!";
} else{
echo "User or psw aren't correct!";
}
?>
Example 5: Headers send.
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<button id="btn">Data</button>
<div id="data"></div>
<script>
document.getElementById("btn").addEventListener("click",
function(){
let username = "admin";
let password = "1234";
let myHeaders = [
{header:"Content-type", value: "text/html"},
{header:"MyHeader", value: "nice header"}
]
new lib.myAJAX({site: "auth.php", contentID: "data", user: username, psw: password, headers: myHeaders});
})
</script>
</body>
</html>
auth.php
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'The second round get username and password!';
exit;
} else if ($_SERVER['PHP_AUTH_USER'] == "admin" and $_SERVER['PHP_AUTH_PW'] =="1234"){
echo "You logged in!<br>";
$headers=getallheaders();
forEach($headers as $header => $value){
if ($header !== "MyHeader")
echo "<div><b>headerName: </b>".$header." <b>value : </b>". $value."</div>";
else
echo "<div style='color: white; background-color: green'><b>headerName: </b>".$header." <b>value : </b>". $value."</div>";
}
} else{
echo "User or psw aren't correct! <br>";
}
?>
Example 6: Headers receive.
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<button id="btn">Data</button>
<div id="data"></div>
<script>
document.getElementById("btn").addEventListener("click",
function(){
let username = "admin";
let password = "1234";
new lib.myAJAX({site: "auth.php",callback: myCallback, user: username, psw: password});
})
function myCallback(res,resTxt,resXML,resURL,resType, resHeaders){
// Convert the header string into an array
// of individual headers
var arr=resHeaders.trim().split(/[\r\n]+/);
// Create a map of header names to values
var headerMap = {};
headerMap=arr.map((line)=>{
var parts = line.split(': ');
var headerName = parts.shift();
var value = parts.shift();
return {"headerName": headerName, "value": value}
})
headerMap.forEach((header) => {
var newDiv = document.createElement("div");
newDiv.innerHTML = "<b>Header:</b> " + header.headerName + "<b> value: </b>" + header.value;
if (header.headerName== "myheader")
newDiv.style = "color: white; background-color: green";
document.getElementById("data").appendChild(newDiv);
})
}
</script>
</body>
</html>
auth.php
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'The second round get user and pwd!';
exit;
} else if ($_SERVER['PHP_AUTH_USER'] == "admin" and $_SERVER['PHP_AUTH_PW'] =="1234"){
echo "You logged in!";
header('myHeader: abcd_12345');
} else{
echo "User or psw aren't correct! <br>";
}
?>
Deutsch
Neu in dieser Version!
- Beispiele überarbeitet!
- Scripte mit dem Attribut src werden in den head-Tag geladen und mit eine Versionsnummer angehangen. Die Versionsnummer ist notwendig, damit ein wieder holen der Aufrufe des Scriptes möglich sind.
- Skripte mit dem Attributwert type="module", also Module, werden berücksichtigt.
Was ist lib.myAJAX?
myAJAX ist eine Funktion mit dessen Hilfe Sie, auf eine einfache Weise, AJAX-Calls aufrufen können!
Sie können Dateien (.html, .php, .txt etc.) in den Scope einer aufgerufenen Webseite an einen definierten Punkt (ID) im DOM-Content (HTML) einbinden.
Vorteile!
Bei der Verwendung dieser Funktion:
- werden Dateien an einen definierten Platz (ID) eingebunden,
- bei der gerufenen HTML-Dateien alle Javascript-Scripte ausgeführt,
- in den PHP-Dateien werden PHP/HTML und Javascript-Scripte ausgeführt,
- Das src-Attribut wird berücksichtigt. Die benannte Datei wird eingebunden und ausgeführt, z.B.:
<script src="myScript.js"><script>
- link-tags (CSS) werden inde Head-Tag an die letzt Position übertragen , aber vor dem ersten Script-Tag (wenn vorhanden) plaziert.
- Formulardaten werden mit "GET" oder "POST" beim Aufruf übermittelt,
- kann eine Callback-Funktion aufgerufen werden, die Zugriff auf alle wesentlichen Daten hat (siehe Unten)!
Installation
für Testzwecke
Verlinken Sie den Script-Tag einfach wie folgt:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/myajaxcall@2.1.6/myajax_bundle.min.js"></script>
</head>
<body>
</body>
</html>
locale Installation
erstelle eine package.json
npm init
Installieren des Packages
npm i myAJAXcall
Einbinden (z.B. in die index.html)
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
</body>
</html>
Arbeitsweise und Beispiele
Die Funktion wird aufgerufen mit:
lib.myAJAX(obj)
Object-Properties
const obj={
site: site-source, // required
contentID: ID, // default null
CSStoHead: boolean, // default True
form: form-control, // default null
user: username, // default null
psw: password, // default null
headers: objHeaders, // default null
callback: callbackFunction // dwfault null
}
lib.myAJAX(obj);
Properties
- site: Datei die durch den AJAX-Call gerufen wird, z.B.: "myFile.php"
- contentID: In den Tag mit dieser ID wird die gerufene Datei eingebunden
- CSStoHead: Wenn Sie nicht wollen, das der Link-Tag automatisch in den Head-Tag der aktuellen seite verschoben wird, z.B.:
{... CSStoHead: false...}
Standardmäßig wird der CSS-Link-Tag an die letzte Position des Head-Tags verschoben aber vor dem ersten Script-Tag - form: Formcontrol wir z.B.: document.getElementById("formID")
- user: username für login in die gerufene Datei (Beispiel unten)
- psw: password für login in die gerufene Datei (Beispiel unten)
- headers: ein Objectarray mit zu übertragenen Headern (Beispiel unten)
- callback: Callback-funktion die nach Ausführung desAJAX-Calls (der asyncron ist) ausgeführt werden soll. Nicht alle Parameter sind notwendig! Beispiel:
lib.myAJAX({site: 'JSON.php', callback: myCallback})
einfache Beispiele und Erklärungen
Beispiel 1: Filename und ID
Die index.html ruft die test.html und fügt deren Inhalt im h1-Tag an der Stelle des span-tag mit der ID content ein.
test.html
<i>Welt</i>
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<h1>Hallo <span id="content"></span>!</h1>
<script>
new lib.myAJAX({site:"test.html", contentID:"content"});
</script>
</body>
</html>
Beispiel 2: Übergabe von Formulardaten an ein PHP-Script
Nach dem der Button submit gedrückt wurde, werden die Formulardaten an das PHP-Script showInput.php übergeben und anschließend in der index.html im div-Tag mit der ID showData, angezeigt.
Wichtig: bitte nicht das event.preventDefault() vergessen!
showInput.php
<?php
$user = $_GET['user'];
$psw = $_GET['pwd'];
echo "Input user: $user <br>";
echo "Input passw: $psw";
?>
bitte nicht das event.preventDefault() vergessen! index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<form method="GET" action="showInput.php" id="form1">
<label for="user"></label>
<input type="text" name="user">
<label for="pwd"></label>
<input type="text" name="pwd">
<input type="submit">
</form>
<div id="showData"></div>
<script>
document.getElementById("form1").addEventListener("submit",
function(event){
event.preventDefault();
const FORM = document.getElementById("form1");
const ACTION_SCRIPT = FORM.getAttribute("action");
new lib.myAJAX({site: ACTION_SCRIPT, contentID: "showData", form: FORM});
})
</script>
</body>
</html>
Die Übertragungsmethode (POST/GET) ermittelt lib.myAJAX() selbständig aus dem form-Tag!
Callback-Function
Es besteht die Möglichkeit der Funktion libmyAJAX() eine Callback-Funktion zu übergeben, welche Zugriff hat auf alle Informationen, die der ausgeführte AJAX-Call ermittelt hat.
Aufbau der Callback-Funktion
functionsname((response, responseText, responseXML, responseURL, responseType, responseHeaders)
- response: gibt den Hauptinhalt der Antwort als ArrayBuffer, Blob, Dokument, JavaScript-Objekt oder DOMString zurück, abhängig vom Wert der responseType-Eigenschaft der Anforderung.
- responseText: gibt den Wert als String zurück.
- responseXML: gibt den Wert als XML-Data zurück.
- responseURL: Die Eigenschaft gibt die serialisierte URL der Antwort oder die leere Zeichenfolge zurück, wenn die URL null ist. Wenn die URL zurückgegeben wird, wird jedes in der URL vorhandene URL-Fragment entfernt. Der Wert von responseURL ist die endgültige URL, die nach Weiterleitungen erhalten wird.
- responseType: ist eine Zeichenfolge, die den in der Antwort enthaltenen Datentyp angibt.
- responseHeader: alle empfangenen Headers (siehe Beispiel unten)
Beispiel 3: Callback, empfängt JSON-Daten von einer PHP-Datei.
JSON.php
<?php
$ary=[
["name"=>"Otto"],
["name"=>"Torsten"],
["name"=>"Melly"]]
];
echo json_encode($ary);
?>
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<button id="btn">Data</button>
<div id="data"></div>
<script>
document.getElementById("btn").addEventListener("click",
function(){
new lib.myAJAX({site: "JSON.php", callback: myCallback});
})
function myCallback(res){
const arr=JSON.parse(res);
const myData = arr[2].name;
document.getElementById("data").innerHTML="<h1>" + myData + "</h1>";
}
</script>
</body>
</html>
Example 4: Authentifizierung, user/password.
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<button id="btn">Data</button>
<div id="data"></div>
<script>
document.getElementById("btn").addEventListener("click",
function(){
let username = "admin";
let password = "1234";
let myHeaders = [
{header:"Content-type", value: "text/html"},
{header:"MyHeader", value: "nice header"}
]
new lib.myAJAX({site: "auth.php", contentID: "data", user: username, psw: password, headers: myHeaders});
})
</script>
</body>
</html>
auth.php
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'The second round get username and password!';
exit;
} else if ($_SERVER['PHP_AUTH_USER'] == "admin" and $_SERVER['PHP_AUTH_PW'] =="1234"){
echo "You logged in!";
} else{
echo "User or psw aren't correct! <br>";
echo getallheaders();
}
?>
Example 5: Headers senden.
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<button id="btn">Data</button>
<div id="data"></div>
<script>
document.getElementById("btn").addEventListener("click",
function(){
let username = "admin";
let password = "1234";
let myHeaders = [
{header:"Content-type", value: "text/html"},
{header:"MyHeader", value: "nice header"}
]
new lib.myAJAX({site: "auth.php", contentID: "data", user: username, psw: password, headers: myHeaders});
})
</script>
</body>
</html>
auth.php
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'The second round get username and password!';
exit;
} else if ($_SERVER['PHP_AUTH_USER'] == "admin" and $_SERVER['PHP_AUTH_PW'] =="1234"){
echo "You logged in!<br>";
$headers=getallheaders();
forEach($headers as $header => $value){
if ($header !== "MyHeader")
echo "<div><b>headerName: </b>".$header." <b>value : </b>". $value."</div>";
else
echo "<div style='color: white; background-color: green'><b>headerName: </b>".$header." <b>value : </b>". $value."</div>";
}
} else{
echo "User or psw aren't correct! <br>";
}
?>
Example 6: Headers empfangen.
index.html
<html>
<head>
<script src="node_modules/myajaxcall/myajax_bundle.js"></script>
</head>
<body>
<button id="btn">Data</button>
<div id="data"></div>
<script>
document.getElementById("btn").addEventListener("click",
function(){
let username = "admin";
let password = "1234";
new lib.myAJAX({site: "auth.php",callback: myCallback, user: username, psw: password});
})
function myCallback(res,resTxt,resXML,resURL,resType, resHeaders){
// Convert the header string into an array
// of individual headers
var arr=resHeaders.trim().split(/[\r\n]+/);
// Create a map of header names to values
var headerMap = {};
headerMap=arr.map((line)=>{
var parts = line.split(': ');
var headerName = parts.shift();
var value = parts.shift();
return {"headerName": headerName, "value": value}
})
headerMap.forEach((header) => {
var newDiv = document.createElement("div");
newDiv.innerHTML = "<b>Header:</b> " + header.headerName + "<b> value: </b>" + header.value;
if (header.headerName== "myheader")
newDiv.style = "color: white; background-color: green";
document.getElementById("data").appendChild(newDiv);
})
}
</script>
</body>
</html>
auth.php
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'The second round get user and pwd!';
exit;
} else if ($_SERVER['PHP_AUTH_USER'] == "admin" and $_SERVER['PHP_AUTH_PW'] =="1234"){
echo "You logged in!";
header('myHeader: abcd_12345');
} else{
echo "User or psw aren't correct! <br>";
}
?>
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago