Home > Software engineering >  Javascript (jQuery) - Weird undefined variable
Javascript (jQuery) - Weird undefined variable

Time:09-27

Here is my jQuery function

function addEntryDatabase(data){
    var entryId;
    $.ajax({
        url: "model/script_ajout.php",  
        async: false,
        type: "POST",
        dataType: 'html',
        data: data
        success: function()
        {

        },
        error: function(){
            console.log('An error occurred while adding adata to the database.');
        }
    });
    return entryId;
}

Here is my code

/**
 * Creating user in the database
 */
var user_id = addEntryDatabase(data);
console.log(user_id);

Here is the console of my web browser (everything is fine, I get my entryId value)

enter image description here

But my console.log of user_id give me 'undefinned'. I can not explain why.

Did somebody know why ?

CodePudding user response:

After success, you need to change your entryId with the response you get in which you will have the id which you want to log.

function addEntryDatabase(data){
    var entryId;
    $.ajax({
        url: "model/script_ajout.php",  
        async: false,
        type: "POST",
        dataType: 'html',
        data: data
        success: function()
        {
          entryId= response.data.id ///change your entryId;
        },
        error: function(){
            console.log('An error occurred while adding adata to the database.');
        }
    });
    return entryId;
}```
  • Related