Francesco Binucci
Francesco Binucci

Reputation: 11

How to use buttons generated using php and jquery

I have a page that sent an ajax request to another php page.

var link="http://...";
        $(document).ready(function(){
            $("input").click(function() {
                    dati = $("form").serialize();
                    $.ajax({
                      type: "POST",
                      url: link,
                      timeout:5000,
                      data: dati,
                      success: function(response)
                      {
                            console.log(dati);
                            $("#forms").append(response);
                    },
                    error: function(){
                        alert("Si e' verificato un errore con la chiamata Ajax, impossibile generare il grafico!");
                    },
                });
            });
        });

The php page called "Server.php" generate some contents and a button, like this:

echo("<input type=\"button\" value=\"Invia\"/>");

This content is appended into a div in the main page (the page of the ajax request).

I have to make this button usable to do another ajax call, but when i click on the button generated the ajax call doesn't start, why?

Upvotes: 0

Views: 39

Answers (1)

nicael
nicael

Reputation: 18995

Your code detects already existing inputs. Bind the handler like this, to detect the new inputs.

$("body").on("click","input",function() {...

The another approach would be to bind a function once you create the button (also - there's another type of quotes, don't forget :), i.e.:

echo("<input type='button' value='Invia' onclick='iclick()'/>");

And rewrite the code like this:

var link = "http://...";
$(document).ready(function () {
    $("input").click(function () {
        iclick();
    });

    function iclick() {
        dati = $("form").serialize();
        $.ajax({
            type: "POST",
            url: link,
            timeout: 5000,
            data: dati,
            success: function (response) {
                console.log(dati);
                $("#forms").append(response);
            },
            error: function () {
                alert("Si e' verificato un errore con la chiamata Ajax, impossibile generare il grafico!");
            },
        });
    };
})

Upvotes: 2

Related Questions