-1

I am trying to load a JavaScript function with will take a PHP variable after getting a response from XMLHttpRequest.

This is the JavaScript function that I would like to call:

function print_text(text) {
  console.log(text);
}

These are the different ways that I tried to include a JavaScript function call in the response of XMLHttpRequest. However, none of them can successfully call the JavaScript function test() and console log "Hello World"

Way 1:

<?php
 $text  = "Hello World!";
 $html  = '';
 $html .= '<script>print_text(' . $text . ');</script>';
?>

Way 2:

<?php
    
?>
<script type="text/javascript">
    print_text(<?php echo $text; ?>);
</script>

This is how I handle the XMLHttpRequest response:

  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("id").innerHTML = this.responseText;
    }
    
  };
  xmlhttp.open("POST", "file.php", true);
  xmlhttp.send(data);

I can see <script>print_text(Hello World!);</script> when I inspect the website, but the function doesn't load, the console doesn't log the text "Hello World!". I wonder why can't I call the JavaScript function?

David
  • 11
  • 5
  • You should write your functions in JavaScript before you return a PHP `json_encode`d response which you send to your prewritten JavaScript. You should also use external ` – StackSlave Sep 21 '21 at 00:22

1 Answers1

0

Below is an example of how the XMLHttpRequest is used with PHP.

First you should have a tiny library in JavaScript that reduces all or most of your future coding. Here's how that might look, along with an explanation of tiny_library.js:

//<![CDATA[
/* js/tiny_library.js */
let get, post, doc, htm, bod, nav, M, I, mobile, beacon, S, Q, hC, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
get = (url, func, responseType = 'json', context = null)=>{
  const x = new XMLHttpRequest;
  const c = context || x;
  x.open('GET', url); x.responseType = responseType;
  x.onload = ()=>{
    if(func)func.call(c, x.response);
  }
  x.onerror = e=>{
    if(func)func.call(c, {xhrErrorEvent:e});
  }
  x.send();
  return x;
}
post = (url, send, func, responseType ='json', context = null)=>{
  const x = new XMLHttpRequest;
  if(typeof send === 'object' && send && !(send instanceof Array)){
    const c = context || x;
    x.open('POST', url); x.responseType = responseType;
    x.onload = ()=>{
      if(func)func.call(c, x.response);
    }
    x.onerror = e=>{
      if(func)func.call(c, {xhrErrorEvent:e});
    }
    let d;
    if(send instanceof FormData){
      d = send;
    }
    else{
      let s;
      d = new FormData;
      for(let k in send){
        s = send[k];
        if(typeof s === 'object' && s)s = JSON.stringify(s);
        d.append(k, s);
      }
    }
    x.send(d);
  }
  else{
    throw new Error('send argument must be an Object');
  }
  return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id); mobile = /Mobi/i.test(nav.userAgent);
beacon = (url, send)=>{
  let r = false;
  if(typeof send === 'object' && send && !(send instanceof Array)){
    let d;
    if(send instanceof FormData){
      d = send;
    }
    else{
      let s;
      d = new FormData;
      for(let k in send){
        s = send[k];
        if(typeof s === 'object' && s)s = JSON.stringify(s);
        d.append(k, s);
      }
    }
    r = nav.sendBeacon(url, d);
  }
  else{
    throw new Error('send argument must be an Object');
  }
  return r;
}
S = (selector, within)=>{
  let w = within || doc;
  return w.querySelector(selector);
}
Q = (selector, within)=>{
  let w = within || doc;
  return w.querySelectorAll(selector);
}
hC = (node, className)=>{
  return node.classList.contains(className);
}
aC = (node, ...classNames)=>{
  node.classList.add(...classNames);
  return aC;
}
rC = (node, ...classNames)=>{
  node.classList.remove(...classNames);
  return rC;
}
tC = (node, className)=>{
  node.classList.toggle(className);
  return tC;
}
}); // end load
//]]>
/* css/site.css */
li>span{
  display:inline-block; font:10px san-serif;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Site Title Here</title>
    <link type='text/css' rel='stylesheet' href='css/site.css' /> <!-- in css folder with site.css file inside -->
    <script src='js/tiny_library.js'></script><!-- in js folder with tiny_library.js inside - no need add get url if created correctly -->
    <script src='js/site.js'></script><!-- in js folder with with site.js in it - update with get url on live used site-->
  </head>
<body>
  <p>Just look at the <code>&lt;head&gt;&lt;/head&gt;</code> tag to see how you would load external CSS and JavaScript</p>
  <p><code>tiny_library.js</code></p>
  <ol>
    <li>get(url, func, responseType = 'json', context = null) <span>XMLHttpRequest get request</span></li>
    <li>post(url, func, responseType = 'json', context = null) <span>XMLHttpRequest post request</span></li>
    <li>doc <span>document</span></li>
    <li>bod <span>document.body</span></li>
    <li>nav <span>navigator</span></li>
    <li>M(htmlTag) <span>document.createElement(htmlTag)</li>
    <li>I(htmlId) <span>document.getElementById(htmlId)</li>
    <li>mobile <span>mobile test via regular expresssion</span></li>
    <li>beacon(url, send) <span>Fast http request with no response for logging out</span></li>
    <li>S(cssSelector) <span>document.querySelector(cssSelector)</span></li>
    <li>Q(cssSelector) <span>document.querySelectorAll(cssSelector)</span></li>
    <li>hC(element, className) <span>has HTML class</span></li>
    <li>aC(element, ...classNames) <span>add one or more HTML classes</span></li>
    <li>rC(element, ...classNames) <span>remove one or more HTML classes</span></li>
    <li>tC(element, className) <span>toggle HTML class</span></li>
  </ol>
</body>
</html>

The code above also has access to js/site.js:

//<![CDATA[
/* js/site.js */
let test; // for use on other loads
addEventListener('load', ()=>{
test = json=>{
  const o = JSON.stringify(json);
  // do stuff with `o.prop1` and `o.prop2` or whatever
}
post('folder/postToURL.php', {prop1:'value 1', prop2:'value 2'}, resonseJson=>{
  test(responseJson);
});
}); // end load
//]]>

As you can see that tiny snippet above sends code to folder/postToURL.php, so your PHP would look something like:

<?php // folder/postToURL.php - should do an https force here really
// this example just creates a standard Object and sends it back to JavaScript at `js/site.js`
if(isset($_POST['prop1'], $_POST['prop2'])){
  $p1 = $_POST['prop1']; $p2 = $_POST['prop2']; $o = new StdClass;
  $o->prop1 = $p1; $o->prop2 = $p2;
  // normally do a bunch of database stuff here
  echo json_encode($o); // sent back
}
?>
StackSlave
  • 10,613
  • 2
  • 18
  • 35