Error calling ajax function

Asked

Viewed 62 times

1

I have gotten an error calling an ajax function contained in a file. js separate from my .html. file The same does not occur when I insert this javascript function into my html file. The function is triggered when I click on a button containing the call to the function, as shown below:

HTML component:

<button type="button" class="btn btn-primary" id="modalAddPessoa" onclick="adicionarPessoa()">Incluir</button>

Javascript function

let requestVerificationToken = $("input[name='__RequestVerificationToken']").val();

function adicionarPessoa() {
    $("#incluirPessoas").attr("disabled", true);
    var pessoa = new Object();

    $.ajax({
        type: "POST",
        data: pessoa,
        url: '/PontoAtendimento/IncluirPessoaPontoAtendimento',
        headers: {
            "RequestVerificationToken": requestVerificationToken
        }
    })
    .done(function (pessoa, statusText, xhdr) {
        $('#incluirPessoas').modal('hide');
        $('#tablePessoas').append(pessoa);
    })
    .fail(function (xhdr, statusText, errorText) {
        console.log("Failed: " + errorText);
    });
}

When debugging, I got the following error in the browser:

inserir a descrição da imagem aqui

How to solve this problem?

  • 2

    __Requestverificationtoken probably doesn’t exist yet when the js file is being loaded. Try to put this line inside the function.

  • Apparently that’s right. I put the javascript function inside a $(Document). ready(Function () { }); and the problem was solved.

1 answer

1

Replace the head tag of your HTML file with the following tag

<head Access-Control-Allow-Origin: *>

For requests without credentials, the server can specify "*" as a wildcard, thus allowing any source to access the resource.

To allow https://developerrr.mozilla.org access your resource, you can specify:

<head Access-Control-Allow-Origin: https://developer.mozilla.org>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.