0

I am trying to use jQuery's post() and get() but they are not working. I do not have HTML so I am loading jQuery this way:

var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js';
document.head.appendChild(script);

Seems like it is successfully loaded. Checked using window.jQuery in the console.

Right after I create a button:

var btn = document.createElement("button");
btn.id = 'gogogo';
var txt = document.createTextNode("Go");
btn.appendChild(txt);
document.body.insertBefore(btn, document.body.childNodes[0]);

Button successfully created.

Right after this I have the desired post():

$("#gogogo").click(function () {
    var txt = '123';
    $.post("/users", {qwe: txt}, function(result){
            alert(result);
    });
});

But nothing happens at all. NET section in FireBug remains empty while clicking on the button.

Somebody knows what I am doing wrong?

3

1 Answer 1

2

Use .on event of jQuery, As you are dynamically creating element i.e event delegation.

For ex.

$(document).on("click","#gogogo",function () {
    alert("Inside #gogogo event handler");
    var txt = '123';
    $.post("/users", {qwe: txt}, function(result){
            alert(result);
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

what you see on console? Put a alert updated in my answer to see are you inside the event handler or not.
The console is empty and nothing happens.
did the alert show up alert("Inside #gogogo event handler");
it should work. check if DOM has button with id.remove post call. just see if the handler alert or console.log is getting printed or not. put console.log also. sometimes alert doesn't show up.

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.