Reputation: 239
I'm having trouble getting getjson success event to fire. When I'm calling $.getJSON on $(document).ready its working fine and when I put the same code under button click then it is not working.
Working 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>
Not Working (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>
Upvotes: 4
Views: 1474
Reputation: 25352
It didn't work becuase you put your button in form
<form>
<button id="btn1" >Execute</button>
</form>
It'll submit evertime you click in other sense it'll reload the page.
Just define type of button inside the form.
Try like this
<form>
<button type="button" id="btn1" >Execute</button>
</form>
Or just add return false in 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;
});
});
Upvotes: 2