jQuery's ajax() does not work if jQuery is loaded dynamically

349
November 21, 2016, at 8:27 PM

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?

Answer 1

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);
    });
});
Rent Charter Buses Company
READ ALSO
What's the vanilla javascript version of jQuery's $var = ($var) statement?

What's the vanilla javascript version of jQuery's $var = ($var) statement?

I'm current looking to load images that I'm grabbing from the flickr API. The plain load out is ugly, so I'm waiting till they all load and then presenting them at the same time, using the second example on this page.

230
Jquery 1.5.2 substitute for .on() function

Jquery 1.5.2 substitute for .on() function

I's there any Jquery specialist to help me here?.

399
Hide Footer(Pagination Div) in jtable [closed]

Hide Footer(Pagination Div) in jtable [closed]

I just want to hide the pagination (footer) section from jtable. [nnn]Please help me to hide the section.

453
How to find out what JavaScript function triggered HTML change?

How to find out what JavaScript function triggered HTML change?

I am having a problem on a WordPress site. I have a function which slides down a certain <div>.

569