-
- /**
- * COPYRIGHT © 2022 JOHN PEARCEY
- * All rights reserved
- */
-
- /*
- * pagename:
- * The name of the server-side script to handle this post.
- * fnCallback:
- * The javascript callback function, called after the AJAX call completes.
- * map_params:
- * A map containing name value pairs required by the script.
- * e.g.
- * map_params = new Map();
- map_params.set('username', document.getElementById('username').value );
- map_params.set('pwdhash', document.getElementById('pwd').value );
- */
- function postData( pagename, fnCallback, map_params ){
-
- //console.log( 'postData called' );
-
- let formData = new FormData();
- map_params.forEach((value, key, map) => {
- //if(key=='action') console.log("postData: ", pagename, value );
- formData.append( key, value );
- });
-
- //https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-fetch-api-to-get-data
- //https://jsonplaceholder.typicode.com/users
- //https://javascript.info/fetch
- fetch( pagename, {
- method: 'POST',
- body: formData,
-
- })
- /*.then((response) => {
- return response.json(); */
-
- .then(response => response.text())
- .then((dataStr) => {
-
- //console.log(dataStr);
-
- //there's a whole bunch of warnings and errors that might be sent by PHP. It is not possible
- //to catch them in the serverside PHP code. So here we search for our json encoded return string which
- //must be either Error or OK.
- let pos = dataStr.indexOf("[\"OK\"");
- let additional=null;
- if(pos==-1){
- pos = dataStr.indexOf("[\"Error\"");
- if(pos==-1){
- //the PHP is pretty fucked up if you get here!
- console.warn( dataStr );
- let encodedStr = JSON.stringify( ["Illegal return from server. Did not find Error or OK.", dataStr ] );
- return JSON.parse( encodedStr );
- }
- }
- //console.log(dataStr);
- return JSON.parse(dataStr);
-
- }).then((data) => {
- fnCallback( true, data, map_params );
-
- }).catch(function(error) {
- console.log( error );
- fnCallback( false, error, map_params );
- });
-
- }
-
- function checkReturn( success, data, bGetErr=false ){
-
- if(!success){
- console.warn( "callback error: " + data );
- return false;
- }
-
- if(data[0]=="Error"){
- if(bGetErr) return data;
- alert( "Error: " + data[1] );
- for( i=2; i<data.length; i++){
- console.warn( data[i] );
- }
- return false;
- }
-
- if(data[0]!="OK"){
- console.warn( "Unkown server return string ", data );
- if(bGetErr) return data;
- return false;
- }
- if(bGetErr) return null;
- return true;
- }
-
- function stripHtml( txt ){
- txt = txt.replace(/<div>/gi, '\n');
- txt = txt.replace(/<\/?[^>]+>/gi, ''); //strip HTML
- return txt;
- }