There is an Ajax request that adds entries to the database.

How can I get the id of the newly added record in the database and record this id in response?

$.ajax({ type: "POST", url: 'send.php', data: {name:name}, success: function(response){ if(response == 0){ $("#section").val(""); $("#resp").append('<div id="resp">'+name+'</div>'); } } }); 

file send.php

 $name = $_POST['name']; $insert = mysqli_query($connection,"INSERT INTO section_list (section) VALUES ('$name')"); if($insert == true){ echo 0; }else{ echo 1; } 
  • one
    Return the result of the mysqli_insert_id () function after the query. - Visman
  • recorded after the request $ id = mysqli_insert_id ($ connection); in send.php, now how can I add this id in response? - LLIAKAJI
  • 2
    So return not 0 as the answer via echo , but the value of $ id, but on the js side, check: if it is non-zero, then everything is ok and in response the id number of the added line. - Visman
  • so as not to create a new topic, tell me, is there another skrit of deleting entries, the entry that is added via append does not trigger the delete script, what could be? - LLIAKAJI
  • Events are assigned when the page is loaded. And when loading - this line did not exist yet, therefore it does not work. You need to properly assign events to dynamically created elements. There are many such questions here. Look for it. For example: ru.stackoverflow.com/questions/83459/… - cyadvert

1 answer 1

Js

 $.ajax({ type: "POST", url: 'send.php', data: {name:name}, dataType: 'json', // получает ответ в json success: function(response){ if(response && response.success == true){ $("#section").val(response.id); // ID новой записи $("#resp").append('<div id="resp">'+name+'</div>'); } }, error: function(){ // не забывайте обрабатывать ошибки } }); 

Php

 $name = mysqli_real_escape_string ($_POST['name']); // SQL инъенкции это так не приятно $insert = mysqli_query($connection,"INSERT INTO section_list (section) VALUES ('$name')"); // лучше юзать PDO $id = mysqli_insert_id($connection); // ID новой строки или 0 в случае ошибки $return = array('success' => false); if($id){ $return = array( 'success' => true, 'id' => $id ); } die(json_encode($return)); // ответ в виде json