2

I'm trying to add XPATH evaluation into my form. When user fills XPATH, it's evaluated on a server using AJAX and then return true or false.

The problem is that this function seems to return undefined allways. I suppose it's because of asynchronious behaviour of JS so I used $.when but it didn't helped.

function evalXpath(xpath) {
    var test = $.post('/api/test-xpath/', {'xpath': xpath});
    test.done(function (data) {
        console.log('BEFORE RETURN '+Boolean(data['success']));
        return Boolean(data['success']);
    })
}

$(document).ready(function () {
    $('#id_xpath').on('change', function () {
        var xpath = $("#id_xpath").val();
        $.when(evalXpath(xpath)).done(function (evaluated) {
            console.log('RETURNED '+evaluated);
            $('#xpath-valid').text(evaluated ? 'VALID' : 'INVALID');
        });


    });

});

The console output (as you can see, it's still asynchronious):

enter image description here

Do you have any ideas?

0

1 Answer 1

3

You're really close. A couple of things:

  1. You forgot to return the promise out of evalXpath.

  2. To get proper promise value chaining (e.g., in order for your value from the callback inside evalXpath to then become the resolution value of the promise it returns), use then, not done.

  3. Then when using evalXpath, there's no need for $.when.

So:

function evalXpath(xpath) {
    var test = $.post('/api/test-xpath/', {'xpath': xpath});
    return test.then(function (data) {
//  ^^^^^^      ^^^^
        console.log('BEFORE RETURN '+Boolean(data['success']));
        return Boolean(data['success']);
    })
}

// ...
evalXpath(xpath).then(function (evaluated) {
//               ^^^^ (this one could be `done`, but let's be consistent)
Sign up to request clarification or add additional context in comments.

Comments

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.