JQuery getJson success function runs when a button is clicked

I'm having trouble triggering getjson success event. When I call $ .getJSON on $ (document). Already works, and when I put the same code when I click the button, it does not work.

Works fine (under $ (document) .ready)

<html>
<head>
<title>API Logger</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
    <script>
        "use strict";
        $(document).ready(function(){
                var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
                $.getJSON( flickerAPI, 
                {
                    tags: "mount everest",
                    tagmode: "any",
                    format: "json"
                },
                function(data)
                {
                    alert("success");

                });
        });
    </script>
</head>
    <body>
        <form>
            <button id="btn1" >Execute</button>
        </form>
    </body>

Doesn't work (under $ ('# btn1'). On ('click', function ()

<html>
<head>
<title>API Logger</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
    <script>
        "use strict";
        $(document).ready(function(){
            $('#btn1').on('click', function() {

                var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
                $.getJSON( flickerAPI, 
                {
                    tags: "mount everest",
                    tagmode: "any",
                    format: "json"
                },
                function(data)
                {
                    alert("success");

                });

            });
        });
    </script>
</head>
    <body>
        <form>
            <button id="btn1" >Execute</button>
        </form>
    </body>

+4
source share
1 answer

This did not work because you put your button in the form

<form>
    <button id="btn1" >Execute</button>
</form>

It will send an evertime that you click, in another sense, it will reload the page.

Just specify the type of button inside the form.

try it

<form>
    <button type="button" id="btn1" >Execute</button>
</form>

JSFIDDLE

Or just add return false to the click event

$(document).ready(function () {
    $('#btn1').on('click', function () {
        var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
        $.getJSON(flickerAPI, {
            tags: "mount everest",
            tagmode: "any",
            format: "json"
        }, function (data) {
            alert("success");
        });
        return false;
    });
});

JSFIDDLE

+2

Source: https://habr.com/ru/post/1617253/


All Articles