0

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 ?

1
  • You declare entryId without a value (var entryId;) and then you return it (return entryId;). At no point are you assigning a value to it. The default value is undefined. Commented Sep 27, 2021 at 9:46

1 Answer 1

1

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;
}```
Sign up to request clarification or add additional context in comments.

4 Comments

So simple.. thank you !
welcome.Please accept the solution :)
If you try to access the result before the AJAX request has completed (or if it errors) the value will still be undefined.
yeah, it will only give undefined if there is an error.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.