Hi one and all,

Have taken a look through the mass of other threads and whilst not covering what I need, certainly given me a dozen other ideas for other things, so definately not wasted hours but learning diversion, anyway sorry.

I have been trying to utilize a pre existing snippet of JS that makes a call to some PHP, where the PHP echo's out the answer, namely a dynamic quick search output, that gains its data from an xml file (which works as expected) and thought I might be able to rework the code to work for my altered purpose (which has been a disaster at every attempt) which is as follows:

1. I have a JS file called - JS that has a string (str) value assigned (could be number or a combination of numbers and letters) which is passed to a PHP script called call4section.php.

2. The PHP script takes receipt of the string and finds a match within an XML file for the entry under <reference>.

3. The XML file has a format as follows:

<pages>
<note>
<section>value</section>
<reference>value</value>
<name>value</name>
</note>
.... multiples of the <note> ... </note> entries.
</pages>

The XML file is fine and dandy.

4. The PHP script then locates the corresponding <section>value</section> and then needs to parse that back to the calling JS.

5. The calling JS takes receipt back of the response value and then continues using it.

This is what I have so far:

var xmlhttp;

function showResult(str)
{
if (str.length<1)
  {
  alert ("The String is empty");
  return;
  }
xmlhttp=GetXmlHttpObject()
if (xmlhttp==null)
  {
  alert ("Your browser does not support XML HTTP Request");
  return;
  }
var url="call4section.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

I think I am right in calling this JS file by the following, which sends the reference as ABC12345:

<script src="call4section.js" type="text/javascript"></script>
document.ready(showResult("ABC12345"));

call4section.php which takes receipt of the str is as follows:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("call4section.xml");

$x=$xmlDoc->getElementsByTagName('pages');

//get the q parameter from URL
$q=$_GET["q"];

//lookup all references from the xml file if length of q>0
if (strlen($q) > 0)
{
$reply="";
for($i=0; $i<($x->length); $i++)
  {
  $y=$x->item($i)->getElementsByTagName('reference');
  $z=$x->item($i)->getElementsByTagName('section');
  if ($y->item(0)->nodeType==1)
    {
    //find a reference matching the search text
    if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
      {
      if ($reply=="")
        {
        $reply= $z->item(0)->childNodes->item(0)->nodeValue;
        }
      }
    }
  }
}

//output the reply
echo $reply;
?>

And well, I dont seem to be able to get any further forward with it. Effectively, I can echo out the $reply (if it worked I think), but my stumbling block is sending the starting string, with the JS expecting some reply sent from the PHP.

If anyone has some words of wisdom or if I have missed a thread that embarasses me because the bits I am missing are so easy, then be mucho appreciated.

Thanks, Ian

Dani AI

Generated

Brief clarification and practical fixes that build on 's description and 's onreadystatechange hint.

Common pitfalls: the JS often never waits for a response (calling the function immediately or not wiring a callback), the query string isn't URL-encoded, or the XML is not well-formed (a mismatched tag will make DOMDocument fail). Also confirm whether jQuery is actually loaded — document.ready(showResult("ABC12345")) calls the function immediately instead of registering it.

A simpler, modern front-end pattern (avoids manual XHR readyState handling):

document.addEventListener('DOMContentLoaded', function() {
  fetch('call4section.php?q=' + encodeURIComponent('ABC12345') + '&sid=' + Math.random(), { cache: 'no-store' })
    .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.text(); })
    .then(section => { console.log('section:', section); /* use section value */ })
    .catch(err => console.error('Request failed:', err));
});

On the PHP/XML side, SimpleXML gives a compact, robust lookup and clearer error handling than looping DOM nodes by tag names. Example pattern:

<?php
if (!empty($_GET['q'])) {
  $q = $_GET['q'];
  $xml = @simplexml_load_file('call4section.xml');
  if ($xml === false) { header('HTTP/1.1 500 Internal Server Error'); echo 'XML parse error'; exit; }
  foreach ($xml->note as $note) {
    if (stripos((string)$note->reference, $q) !== false) {
      header('Content-Type: text/plain; charset=utf-8');
      echo (string)$note->section;
      exit;
    }
  }
}
echo '';
?>

Quick troubleshooting checklist: watch the Network tab for the actual request URL, response body and HTTP status; console.log the response; temporarily echo the received q in PHP to confirm it arrives; enable libxml_use_internal_errors(true) to inspect XML parse errors; ensure response Content-Type is appropriate; sanitize q before use; and remember CORS rules if the script is on another origin. As noted, XHR onreadystatechange works fine, but Fetch promises are easier to read and less error-prone for newer code.

Recommended Answers

All 2 Replies

The flow seems fine.
To read the echoed $reply in the js use the 'onreadystatechange' event of the xmlhttp object.
Following code snippet in will display the reponse text echoed in an alert box. You can process it as you wish

.........
xmlhttp.open("GET",url,true);
xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState == 4) { 
		if (xmlhttp.status == 200) {		
			alert(xmlhttp.responseText);				
		}
		else{//Error
			alert("Error:"+xmlhttp.status);
		}
       }
}
xmlhttp.send(null);

.............

Many thanks.

Will give that a go and see how I get on.

Many thanks once again, Ian.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.