0

Admittedly, I am a bit out of my league here, but attempting this project anyway.

Background:
I am developing a page that will allow my users to enter data to a database. The database has multiple tables that will have data inserted and updated. The first action the user takes is to select an option from a drop down and click "create". Clicking the create button will create a record in one of my tables. Also, upon clicking "create" a larger form will be displayed. Once the larger form is complete, the user can "save" their work. I am planning on using an update query to allow the user to save their work.
Question:
I am using ajax to post the data (see example below), I essentially want to return the record ID (primary KEY) to the page so that when the visitor saves the additional information, the database knows what record to update.

//script

$(function(){
  $('#create').click(function(event) {
     event.preventDefault();


    $.ajax({
       type: "POST",
       url: "url",
       data: {"optimizationtype": $("#optimizationtype").val()},

       success: function(results){
        $("#mvt-experimentdetails").css("display", "inline-block");
        $("#create").attr('value', 'Save');
        $("#create").attr('id', 'save');


       }
     });

  });

});

//php includes

$expid = mysqli_insert_id($con);


I know that I am suppose to return it in the success area of the ajax, but I am not sure exactly how to do that...Any help would be much appreciated.

1 Answer 1

0

On the PHP side, after you run the insert, you'll want to do the last_insert_id and echo that.

For example (using PDO and pseudocode):

insert into table values (x,y)
$id = $db->lastInsertId();
echo $id;

On the client side, let me recommend $.post instead of $.ajax - I find it much easier to use. However, the theory is the same for both.

$.post('url', {
        data-key: data-value,
        next-data-key: next-data-value
    }, 
    //now for the callback
    function (recordID) {
       //do something with recordID
        alert(recordID);
});
2
  • can I do something like this? function (recordID){ $id = recordID }? Feb 6, 2014 at 1:49
  • That won't work, because $id is a PHP variable, which can only be edited on the server. Feb 6, 2014 at 2:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.