سؤال

I am trying to pass values from a form through AJAX into my SQL query file (findme.php) I was able to follow the example from W3school, however their AJAX script only pass 1 value. Is there a way i can pass multiple values over ?

<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>
<div id="txtHint">Info will be listed here.</div>


<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> 

Over at my (findme.php) script, i used to have the following assigner. I am hoping that i can still pass the value into the respective variables.

$findName = $_POST['findName'];
$findLocation = $_POST['findLocation'];
$findPrice = $_POST['findPrice'];
$options = $_POST['123'];

Any idea how can this be done ?

هل كانت مفيدة؟

المحلول 2

If you want to do a form POST (you're using the $_POST array on the server) you can do it this way -

var myForm = document.getElementById('<form id>'); // add an id to the form and use it here
var formData = new FormData(myForm);
xmlhttp.open("POST","findme.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(formData);

نصائح أخرى

You have to send the body params of your POST request with the send() call:

var params = "name=value&name1=value1";
xmlhttp.send(params);

Your parameters needs to be URI-encoded in order to avoid issues with "&" and other reserved characters

And don't forget to change your request type to POST instead of GET

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top