Ajax sends php query in Mysql

0

Hello friends I'm studying Ajax I'm trying to make this run of code work, but I still can not. I am trying to do after form produtos be selector is sent to consultarcor.php via Ajax the information to query the colors of each selected product consultarcor.php checks and the result returned to cores as <option> to selection in another form.

Someone can check what I did wrong because Ajax does not work.

 function showHint(str) {
   if (str.length == 0) { 
    document.getElementById("produto").innerHTML = "";
    return;
} else {
    var xmlhttp = new XMLHttpRequest();
    var vasr="cor="; 
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("produto").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("POST", "consultacor.php"+str, true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(vasr);

Html Form

     <tr>
     <td><input type="text" size="2" maxlength="2"name="quant" placeholder="Quant." onkeypress="return maskKeyPress(event)"/></td>
     <td><input list='produtos' name='produto' onchange="showHint()"/>
     <datalist id='produtos'><?php
      $sql= mysqli_query($conn,"select DISTINCT descricao from produtos  order by descricao");
      while ($resp = mysqli_fetch_array($sql)) {

     $group=$resp['descricao'];
      echo "

         ";           }

      ?> </datalist></td>
      <td>
      <input list='cor' name='cor'/>

      </td>
      </tr>

Codes within querycor.php

    <?php
    include "conecta.inc";
    $q[]= $_POST['produto'];
    $q = array_filter($q);

    $query.= "select * from produtos where descricao='$q'";

    $x = mysqli_query($conn,$query );

    while($prt=mysqli_fetch_array($x)){ 
    $cor[]=$prt['cores'];   

    echo "
    <datalist id='cores'>
    <option value='$cor'>
    </datalist>";
     }
     ?>

This is the error presented "console"

ficha.php: 110 Uncaught TypeError: Can not read property 'length' of undefined

    
asked by anonymous 29.06.2016 / 15:11

1 answer

1

The amount of inconsistencies in the code is great.

In HTML there is no element whose id is product , you are using the getElementbyId tag to get an id that does not exist throughout the code, and analyzing it, you should use getElementsByName("produtos") , so try to recover the value of your selected product and then move on.

As far as PHP goes, <datalist id="cores"> does not equal <input list="cor" /> and then I imagine that while I would print many <datalist> instead of loading a list of <option> within <datalist> .

I suggest giving a good review in the code, and to work with ajax start using the browser "console" to identify errors faster.

    
29.06.2016 / 16:42