Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to stop xmlhttp.open duplicating the entire page? (ajax livesearch)
    text
    copied!<p>I am using a simple "live search" script that displays the results from a MySQL database as the user types into a text box. It works perfectly fine if the Javascript is pointing to a completely separate page but I need it to point to the same page. Unfortunately when I try and do this the page is duplicated within itself as the results are generated.</p> <p>This works as expected:</p> <pre><code> Document called: "test.php" containing JavaScript below and test2.php containing the PHP code xmlhttp.open("GET","test2.php?livesearch="+str,true); xmlhttp.send(); </code></pre> <p>This creates a page within a page:</p> <pre><code> Document called: "test.php" containing both the JavaScript and PHP code below xmlhttp.open("GET","?livesearch="+str,true); xmlhttp.send(); </code></pre> <p>I understand that it's because it is opening itself in a loop but I'm not sure what I am supposed to change in the code to avoid this. Any help would be greatly appreciated as I haven't found much help via Google. </p> <p>Here is all my code:</p> <p><strong>Javascript</strong></p> <pre><code>function showResult(str) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) { document.getElementById("livesearch").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","&amp;livesearch="+str,true); xmlhttp.send(); } </code></pre> <p><strong>PHP Code</strong></p> <pre><code>if(isset($_GET['livesearch'])) {liveSearch();} function liveSearch() { $q=$_GET["livesearch"]; $sqlQuery = "SELECT * FROM something WHERE something LIKE '%" . $q . "%' ; etc etc etc } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload