简体   繁体   中英

Return a mysql result to php using ajax

I've been dealing with that problem for a while, but I can't see the solution here. I am making a simple list application, and anytime the user creates a new item it should be saved to the database. The issue is that every item has a unique ID (auto-incremented), and that ID has to be on the html code when the item is appended to the list (other functions need to use it, so when it's uploaded to the database, then the ID should be selected and sended again to the original html file, but I'm not sure how to do that (in fact, I've got no idea).

Here's my php/html code:

while($row = mysql_fetch_array($selectitems) ){
        echo'<html>
             <li class="i­tem"  data-id="';
        echo $row['IDitem'];     
        echo     '">
          <div class="draggertab"><img src="imatges/botofletxa.jpg" width="30" height="30"></div>
          <div class="deletetab"><img src="imatges/botocreu.jpg" width="30" height="30"></div>
             <span class="item">';
        echo $row['Text'];
        echo'</span>          
          </li>
          </html>';
          }

The javascript:

 ajax.onreadystatechange=function() {
      //la función responseText tiene todos los datos pedidos al servidor
    if (ajax.readyState==4) {
        //mostrar resultados en esta capa
        AppendItem();
        //llamar a funcion para limpiar los inputs
        LimpiarCampos();
    }
 }
    ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //enviando los valores a registro.php para que inserte los datos
    ajax.send("nombre="+nom+"&IDllista="+llista);
}

And the PHP:

$con = mysql_connect($bd_host, $bd_usuario, $bd_password); 
mysql_select_db($bd_base, $con); 

//variables POST

$nom=$_POST['nombre'];
$IDllista = $_POST['IDllista'];

//registra los datos del empleados
 $sql="INSERT INTO items (Text, IDllista) VALUES ('$nom', '$IDllista')";
mysql_query($sql,$con) or die('Error. '.mysql_error());

There is also much more code, but I posted what I think is the most important part. It works perfectly now, I just need to send the ID.

Thank you very much!!

You should avoid using mysql_* and use PDO instead. Mysql_ functions are deprated since PHP5.5

Anyway you could retrieve the last id generated with : mysql_insert_id() and return it to your ajax handler, then you can get it with var id = xmlhttp.responseText;

PHP :

$sql="INSERT INTO items (Text, IDllista) VALUES ('$nom', '$IDllista')";
mysql_query($sql,$con) or die('Error. '.mysql_error());

echo mysql_insert_id(); // return the ID

JS :

ajax.onreadystatechange=function() {
    if (ajax.readyState==4) {
         ....
         var id = ajax.responseText; // get it
    } 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM