I created a custom table in wordpress that manages a vocabulary list for each user. This list appears as a table in the browser. I added a button so that the user can remove vocabulary from their list. For that I use a jquery script. I retrieve the user’s id and the id of the selected vocabulary that I pass on to my function thanks to ajax. This function must remove the data stored in the database.

it seems to me that my variables are well transmitted to my function but it doesn’t work. Can anyone explain to me what my mistake is? And how to check if the variables are transmitting well.
here my code in “vocabulary.js”

    jQuery('#button').click( function () {

     var vocabulary = jQuery('.selected').children("input").attr("id");
     var user = jQuery('#id_user').attr("name");

        jQuery.ajax({
        url: removeVoca.ajax_url,
        type:'post',
        data : {
            action : 'renove_vocabulary',
            id_vocabulary : vocabulary,
            id_user : user
        },
        success : function(reponse){

          //delete the row
          table.row('.selected').remove().draw( false );
        },
        error: function(xhr){
           //error handling
           console.log("suppression echoué")
        }});

    } );
} );

Here my fonction in ajax-vocabulary.php

add_action( 'wp_ajax_renove_vocabulary', 'renove_vocabulary' );

function renove_vocabulary() {

$id_user = $_POST['user_id'];
$id_vacabulary = $_POST['vocabulary_id'];


global $wpdb;

$reponse = $wpdb-> delete ('wp_user_vocabulary', array ('vocabulary_id' => $id_vacabulary , 'user_id' => $id_user ), array('%d', '%d'));


wp_die();

}

I checked with the debugger. the variables seem to be sent

enter image description here

1 Answer
1

Assuming that your script localization and other stuff are set up properly, there is an issue in your back-end script. Your data is in the following format:

data : {
    action : 'renove_vocabulary',
    id_vocabulary : vocabulary,
    id_user : user
}

But you are trying to get the data as follows:

$id_user       = $_POST['user_id'];
$id_vacabulary = $_POST['vocabulary_id'];

These 2 should be changed to match the above. So, change them into:

$id_user       = $_POST['id_user'];
$id_vacabulary = $_POST['id_vocabulary'];

Also, don’t forget to use nonces, sanitize the inputs and do some security checks. I would recommend using the REST-API altogether.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *