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?

gaekaete
  • 97
  • 1
  • 4
  • 1
    possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – D4V1D Sep 28 '15 at 13:21
  • Event delegation is required. Best way to set up events to dynamic elements. – IonDen Sep 28 '15 at 13:21
  • http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on learn here – Sterling Archer Sep 28 '15 at 13:22

1 Answers1

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);
    });
});
Akki619
  • 2,224
  • 2
  • 22
  • 45
  • what you see on console? Put a alert updated in my answer to see are you inside the event handler or not. – Akki619 Sep 28 '15 at 13:37
  • The console is empty and nothing happens. – gaekaete Sep 28 '15 at 13:42
  • did the alert show up alert("Inside #gogogo event handler"); – Akki619 Sep 28 '15 at 13:43
  • 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. – Akki619 Sep 28 '15 at 13:48