Amar Amar - 12 days ago 5
PHP Question

Send Ajax post request and retrieve the inserted id

I am trying to submit a form which will insert data into a mysql database which is working fine. I then would like to return the id of the new inserted row (id auto increment in mysql table) as I want to open up a modal once the form is submitted so I can provide a link which includes id as a parameter in the url.

To send the data for the form I am using the following code:

$(document).ready(function(){
$("#submitForm").click(function(){

var string = $('#commentForm').serialize();

// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
//alert(result);
}
});
});
});


The SubmitData.php file then inserts the form data into the database.

In the SubmitData.php I can create a variable to pick up the id of the newly inserted row like

$last_id = mysqli_insert_id($conn);


Is there a way I can return the $last_id from the SubmitData.php file within the same function?

Answer

Yes return from SubmitData.php the id using the following echo:

echo json_encode(['id'=>$last_id]);

js:

$(document).ready(function(){
$("#submitForm").click(function(){

var string = $('#commentForm').serialize();

// AJAX Code To Submit Form.
    $.ajax({
        type: "POST",
        url: "SubmitData.php",
        data: string,
        cache: false,
        success: function(result){
          alert(result.id);//this will alert you the last_id

        }
    });

});

});