1

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?

hemalp108
  • 1,129
  • 1
  • 12
  • 22
Amar
  • 17
  • 2
  • 9

2 Answers2

4

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

        }
    });

});

});
madalinivascu
  • 30,904
  • 4
  • 32
  • 50
  • This also works and would be great if there was a lot of data returned but as it's only 1 id then is there really a need to return as json? – Amar Nov 25 '16 at 06:22
  • its not necessary but will give a little structure to your code, you should return a status code first, what happens if the query doesn't find results you need to tell the user that the query didn't return result – madalinivascu Nov 25 '16 at 06:34
2

print last id in that php file

echo $last_id;

get that in ajax success function

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

}
Gopal Patel
  • 238
  • 1
  • 5
  • 12