简体   繁体   中英

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?

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

        }
    });

});

});

print last id in that php file

echo $last_id;

get that in ajax success function

success: function(result){
        alert(result);

}

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