rihekopo
rihekopo

Reputation: 3350

Cant call jQuery POST request from Javascript's addEventListener method

I have a Javascript file that handles a button click on my html page. It works well and detects the button tap, however I can't make the POST request work inside the addEventListener method. I get no errors in the console of my browser, it just simply doesn't work. My question is that what is missing? Based on the POST requests I checked this implementation should work fine.

// my .js file:

(function(){
const btnSignUp = document.getElementById('btnSignUp');
const txtEmail= document.getElementById('txtEmail');

btnSignUp.addEventListener('click', e => {

    const email = txtEmail.value;
    console.log('test log');

    if (email.length < 4) {
          $.ajax({
          type: "POST",
          contentType: "application/json",
          url: "/signup/",
          data: JSON.stringify({title: email}),
          success: function (data) {
            console.log(data.title);
          },
          dataType: "json"
        });
    }
});
}());

Upvotes: 0

Views: 103

Answers (1)

Lee Brindley
Lee Brindley

Reputation: 6482

Remove the alert call from your object, that’s a syntax error, thus your snippet will not run because of that.

Also, unsure if this will make a difference but you could either replace the self executing function (IIFE) with jquery onload function, both provide an encapsulated scope... example below

(function () {

//...

})();

Becomes

$(function () {

//...

});

Where

//...

Is your code.

I would also add an error field to your jquery Ajax call, that way you can log any error.

error: function (err) {

    console.log(err);

} 

That’s about all I can advise, given you have a syntax error in your question.

Become friends with the browser development tools, specifically the console and network tabs, console tab would pick up your syntax error, and network tab will yield the answers you’re looking for, when asking “is the endpoint being hit”, and “what response is the endpoint giving”.

Lastly, I’d add any else statement, after your if, which checks for the length of the email, a simple log will do, could be that you’re fetching the wrong email field, or it isn’t long enough.

Upvotes: 1

Related Questions