How do I update_post_meta() or add_post_meta() with an AJAX call

I just resolved this. Apparently, when you do AJAX calls to post edit pages in WordPress, or administrator, things work different and you don’t get the ID of the post you are editing. I read a lot of similar questions like this, but none of the solutions worked for me, but they gave me hints.

This is what I did to solve this:

The AJAX code in the JS file:

        var track_artist = $("#album-artist").val();
        var track_name = $("#add-new-track").val();
        var track_url = $("#track-url").val();        
        if ( track_name  !== "") {
                url : track.ajax_url,
                type : 'post',
                data : {
                action: 'save_track_data',
                track_artist : track_artist,
                track_name : track_name, 
                track_url : track_url,
                post_url : window.location.href, //get the complete url of the post editor, wich includes post id
                execute: "add track" //This is not necessary in this code, I'am using it to know when to erase or add a track 
                success: function(response) {


        } else {
            alert("Tienes que introducir el título del track");

The code in functions.php

add_action( 'wp_ajax_save_track_data', 'save_track_data' );
function save_track_data() {    
    $post_url = $_POST['post_url']; //The post edit page's url string from AJAX call
    $id_start = strpos($post_url, 'post=") + 5; //Get the position where the id number starts in the url string
    $id_end = strpos($post_url, "&'); //Get the position where the id number of the post ends
    $post_id = substr($post_url, $id_start, ($id_end - $id_start)); //Extract the number from the urs string
    $tracks_info = get_post_meta($post_id, 'tracks-info', true); //Get the array with the tracks information          
    $track_name = $_POST['track_name'];
    $track_artist = $_POST['track_artist'];
    $track_url = $_POST['track_url'];
    $track_partial = array("artist" => $track_artist, "url" => $track_url);    
    if($tracks_info === '') { //If the meta key has no information
        $track_info[$track_name] = $track_partial; // assign the first array element
         add_post_meta($post_id, 'tracks-info', $track_info); //Save the track info in post meta
    } else { //If the post meta have at least one track
         $tracks_info[$track_name] = $track_partial; //assign a new element to the array of tracks
         update_post_meta($post_id, 'tracks-info', $tracks_info); //Update the post meta

I hope this helps somebody with the same problem.