Question

I'm trying to execute a AJAX function script in the same page after the user enters a text and presses a submit button.

After submitting, the AJAX script will send the result over to findme.php which perform a query on the database. The query on findme.php is working as i have tested it before implementing the ajax function.

I have adopted the method from W3school but to no available. I wasnt able to call the script and send the values over to findme.php

Does anyone know what i have done wrongly ?

qwerty.php

<script>
function showUser(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  } 
  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 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","findme.php?q="+str,true);
  xmlhttp.send();
}
</script>

 <tr>
<form name="search" method="post" action="">
Name: <input type="text" name="findName"/>
Location: <input type="text" name="findLocation"/>
Price: <input type="text" name="findPrice"/>
<Select NAME="123">
<Option type="checkbox" value="">
<Option type="checkbox" value="=">Equal
<Option type="checkbox" value="<">Less than
<Option type="checkbox" value=">">More than
</select>

<input onclick="showUser(); return false;" type="submit" name="search" value="Search"/>
</form>

  </tr>
<tr>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</tr>
Was it helpful?

Solution

You have to return false after calling the function, else the form is submitting which causes to lose the ajax call.

<input onclick="showUser(); return false;" type="submit" name="search" value="Search"/>

OTHER TIPS

Since you are using input type = "submit" , try onSubmit event on the form. asa

<form name="search" method="post" action="" onSubmit="return showUser();">

Dont forget the return keyword . Return false in showUser(); when str=="" and like that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top