Return last_insert_id() to javascript

I am not sure if this is even possible but I have a page where an event can be added:


$("#events-form").on("submit", function(e) {
        url        : "/admin/shop/add_event",
        type       : "post",
        data       : new FormData( this ),
        processData: false,
        contentType: false,
        cache      : false,
        success: function(data){  
        error: function(data){            

PHP /admin/shop/add_event

public function add_eventAction()
        $category_id      = filter_input(INPUT_POST, 'category_id', FILTER_SANITIZE_NUMBER_INT);
        $sub_category_id  = filter_input(INPUT_POST, 'sub_category_id', FILTER_SANITIZE_NUMBER_INT);
        $event_name       = filter_input(INPUT_POST, 'event_name', FILTER_SANITIZE_STRING);
        $event_date       = filter_input(INPUT_POST, 'event_date', FILTER_SANITIZE_STRING);
        $event_id         = $this->shop->evenement_toevoegen($category_id,$sub_category_id,$event_name,$event_date);

$event_id is representing the last_insert_id(). Now I am wondering if it is possible to pass this value back to the above Javascript to use in the succes function?

Thank you in advance

Sure you can do that.


dataType: 'json',

to the $.ajax options

and return JSON object in your PHP action:

header('Content-Type: application/json');
echo json_encode(['id' => $event_id]);

after that you should be able to use value in your success callback

Megazoid has answered the question but I just would like to add that what you are asking is what the success clause will do in ajax technique. success: function(data) returns all the php outputs in a single variable, and in your case it’s called data

usually in ajax php I do something like this:

$response = ''; // Initialize response

....Some codes here...

echo json_encode( $response ); // Return response

The reason why I use json is because you can return arrays and complex objects via json encode, otherwise I think you can only return a simple variable

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.