$.getJSON, Call back doesn't run - javascript

The Problem: The call back on my $.getJSON request doesn't run.
On page load, nothing is logged to the console or updated on the page, but when the function is pasted in to the console it executes correctly.
jQuery:
$(function() {
$.getJSON('http://freegeoip.net/json/', function(location, textStatus, jqXHR) {
console.log("callback running");
console.log(textStatus);
console.log(jqXHR);
$('#region-name').html(location.region_name);
});
});
console.log(typeof $ !== "undefined" && $ !== null);
console.log($.getJSON != null);
Both of the console logs after the function log true.
The above version is reduced for SO. Here is the full script.
#Geo.Coffee
$ ->
$.getJSON(
'http://freegeoip.net/json/?callback=?',
(location, textStatus, jqXHR) -> # example where I update content on the page.
console.log "callback running"
console.log textStatus
console.log jqXHR
$('#region-name').html location.region_name
$('#areacode').html location.areacode
$('#ip').html location.ip
$('#zipcode').html location.zipcode
$('#longitude').html location.longitude
$('#latitude').html location.latitude
$('#country-name').html location.country_name
$('#country-code').html location.country_code
$('#city').html location.city
$('#region-code').html location.region_code
$('container main content').append "<p>#{location.country_code}</p>"
localStorage['loc'] = location.country_code
if localStorage.loc is "US" then alert "Your From The US."
)#.fail(-> alert "fail").done( (loc) -> alert "done")
console.log localStorage.loc
console.log $?
console.log $.getJSON?
compiled js:
(function() {
$(function() {
$.getJSON('http://freegeoip.net/json/?callback=?', function(location, textStatus, jqXHR) {
console.log("callback running");
console.log(textStatus);
console.log(jqXHR);
$('#region-name').html(location.region_name);
$('#areacode').html(location.areacode);
$('#ip').html(location.ip);
$('#zipcode').html(location.zipcode);
$('#longitude').html(location.longitude);
$('#latitude').html(location.latitude);
$('#country-name').html(location.country_name);
$('#country-code').html(location.country_code);
$('#city').html(location.city);
$('#region-code').html(location.region_code);
localStorage['loc'] = location.country_code;
if (localStorage.loc === "US") {
return alert("Your From The US.");
}
});
return console.log(localStorage.loc);
});
console.log(typeof $ !== "undefined" && $ !== null);
console.log($.getJSON != null);
}).call(this);
html:
<p id="region-name"></p>
<p id="areacode"></p>
<p id="ip"></p>
<p id="zipcode"></p>
<p id="longitude"></p>
<p id="latitude"></p>
<p id="country-name"></p>
<p id="country-code"></p>
<p id="city"></p>
<p id="region-code"></p>
correct fiddle: http://jsfiddle.net/5DjEq/1/

Your element id is the problem remove the #
<p id="region-name"></p>
Demo: Fiddle
Or escape the id selector like $('#\\#region-name').html(location.region_name); - demo: Fiddle
Also since the remote resource supports jsonp I would recommend using it if you want to support IE <= 8 - now you are using CORS support provided by the remote resource
$(function () {
$.getJSON('http://freegeoip.net/json/?callback=?', function (location, textStatus, jqXHR) {
console.log("callback running");
console.log(textStatus);
console.log(jqXHR);
$('#region-name').html(location.region_name);
});
});
Demo: Fiddle
Looks like your coffeescript has a indentation problem
$ ->
$.getJSON(
'http://freegeoip.net/json/?callback=?',
(location, textStatus, jqXHR) -> # example where I update content on the page.
console.log "callback running"
console.log textStatus
console.log jqXHR
$('#region-name').html location.region_name
$('#areacode').html location.areacode
$('#ip').html location.ip
$('#zipcode').html location.zipcode
$('#longitude').html location.longitude
$('#latitude').html location.latitude
$('#country-name').html location.country_name
$('#country-code').html location.country_code
$('#city').html location.city
$('#region-code').html location.region_code
$('container main content').append "<p>#{location.country_code}</p>"
localStorage['loc'] = location.country_code
if localStorage.loc is "US" then alert "Your From The US."
)#.fail(-> alert "fail").done( (loc) -> alert "done")
Demo: Fiddle

you need to make jsonp request
$.getJSON('http://freegeoip.net/json/?callback=?',

I had the same problem. Turned out to be my addblocker. uBlock Origin blocked several ip services. After disabling it, everything worked fine.

Related

How to read a remote file with JQuery (and get a jqXHR readable error)

I'm trying to read a remote file ; I'm using the example on the jquery.get() documentation page :
var jqxhr = $.get( 'http://stackoverflow.com/feeds/question/10943544', function() {
alert( 'success' );
})
.done(function() {
alert( 'second success' );
})
.fail(function(jqXHR, textStatus, errorThrown) {
// alert( 'error' );
console.log('Error: (' + errorThrown + ')');
})
.always(function() {
alert( 'finished' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But it only triggers "fail" and "always" and I'd like to understand why ; My question is : How can I obtain a readable error? Currently, the console.log("Error: (" + errorThrown + ')'); only yields Error: ().
Bonus question: Why does it fail? How can I read a remote (RSS) file using JS/JQuery?
Your problem is one of the Same Origin Policy, which is present on most AJAX requests, and put in place as a security measure. If you look at jqXHR() you can see that readyState is 0, indicating this. Note that readyState will always be 0 when the request has failed, be it for policy restriction or a malformed request. The error message is blank because the restrictions are preventing the error message itself from triggering.
var jqxhr = $.get("http://stackoverflow.com/feeds/question/10943544", function(res) {
alert("success");
})
.done(function() {
alert("second success");
})
.fail(function(jqXHR, textStatus, errorThrown) {
// alert( "error" );
console.log("Error: (" + errorThrown + ')');
})
.always(function(jqXHR) {
console.log(jqXHR);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To get around this, there are a number of plugins, which are listed in this answer. It also states:
The best way to overcome this problem, is by creating your own proxy in the back-end, so that your proxy will point to the services in other domains, because in the back-end not exists the same origin policy restriction.
However, assuming you can't do that, the easiest way is to make use of CORS Anywhere proxy, as is shown in the following snippet (note that the result takes a while to come through):
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://stackoverflow.com/feeds/question/10943544',
function(response) {
console.log("> ", response);
$("#viewer").html(response);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this helps! :)

Jquery check if load success or fails

I would like to load content of external url into a div using JQUERY, I found that I should use the next command:
function loadMyContent(url){
$("#result").load('registration.html');
}
Now I would like to check if the load was successful print alert message ("success") and if the action was fails from some reason alert ("fails").
how can I add the success and fails triggers to the function?
does the solution will cover also 404 errors?
Thanks alot
Shai
Try this
var page = $("#result");
$.get("registration.html").success(
function(response, status, jqXhr){
alert("Success!");
page.empty().append(response);
}).error(function (response, status, jqXhr){
alert("Error.");
}).complete(function (response, status, jqXhr){
alert("Complete!");
});
He tried for get method but i saw you need use load if you wan't use load method try this (tested):
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});

Ajax post working but not callback message in Android browser

im implementing sign up with ajax on my site its working perfectly on desktop but causing problem in Android Browser The problem is after i click on signup button in android browser it post data to database but do not replace the html message.And alert native code error.
function postdata(){
var chkfrm = checkdata();
if(chkfrm == 0){
var url = '<?php echo base_url();?>index.php/Signup/signin';
$.ajax({
type: "POST",
url: url,
data: $("#formI").serialize(), // serializes the form's elements.
beforeSend:function(){
$("#signupdiv").html('<h1>Loadinng...........</h1>');
},
success:function(data)
{
$("#signupdiv").html(data);
},
error:function () {
alert(console.log);
}
});
e.preventDefault();
}
else {
$("#msgjava").html('<p>We need a little bit information from you.Please fill it.</p>');
return false;
}
You can't do e.preventDefault(); where you are because e is not passed into this function (thus it is undefined). This will cause an error and stop JS execution.
In what you posted, you are also missing a closing brace at the end of the postdata() function.
Your alert says "native code" because that's what this line of code:
alert(console.log)
will do. console.log is a native function so alerting a native function won't do anything useful. You need to make that alert a lot more useful. To see in more detail what error is coming back from the ajax function, change your error handler to something like this:
error: function(jqXHR, textStatus, errorThrown) {
alert("status = " + textStatus + ", errorThrown = " + errorThrown);
}
And, then see what it says.

$.ajax not working first time

I have a button in html page.
<input type="image" src="images/login_button.png" id="imageButton" onclick="LoginButtonClick();" />
I am calling this method on button click:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
alert ("Inside Ajax."); // This alert not executing first 1 or 2 times.
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
}
});
}
As I mentioned above $.ajax not working first 2 , 3 button click attempts.
In mozilla it throws an error "[Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: JQuery.js :: :: line 20" data: no]"
Is there any way to fix this issues..
I'm not sure why it is executing later. But here's the deal--you're placing the alert in the object literal that defines the parameters for the .ajax method. It doesn't belong there. Try putting the alert in your success and/or error handlers.
UPDATE
How long are you waiting? When you initiate an ajax request, it isn't going to hang the UI. It could be that you're seeing the result of the first click on your 3rd or 4th attempt and think that you're triggering it on that 3rd or 4th attempt.
The $.ajax() function receives as a parameter a set of key/value pairs that configure the Ajax request. I don't think that the syntax will be correct by placing the alert() in there.
Note - entering an absolute path isnt going to work if the domain is not the current one - it is against the Same Origin Policy that browsers adhere too - this might explain why nothing happens when its executed - i suggest you look in your browser debugger to verify.
You should be binding the click event like this :
$(document).ready(function() {
$('#imageButton').click(function() {
// code here
});
});
so your complete code will look like this :
HTML
<input type="image" src="images/login_button.png" id="imageButton" />
JavaScript
$(document).ready(function () {
$('#imageButton').click(function () {
alert("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function (response, status, xhr) {
if (response != "") {
alert("Response receive ");
} else {
alert("Invalid Data.");
}
}
});
});
});
I have removed the alert ("Inside Ajax."); line as this will not be executed - you pass an object {} of parameters not code to execute. If you want to execute before the ajax request is sent do this :
$.ajax({
beforeSend: function() {
alert('inside ajax');
}
// other options here
});
Docs for the $.ajax() function are here
I agree that you have the second alert in the wrong place, and dont know what pmamml.ajaxError function is but may be your call returns with error and therefore your success alerts are not firing. You can check with error and complete functions as follows:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: function(jqXHR, textStatus, errorThrown){
alert ("ajax call returns error: " + errorThrown);
},
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
},
complete:function(jqXHR, textStatus){
alert('completed with either success or fail');
}
});
}
You can test with Google Chrome's Developer tools -> Network tab, if a request is made and returned (https://developers.google.com/chrome-developer-tools/docs/network)

jquery xml exists

I want to use javascript / jquery to determine if an xml file exists.
I don't need to process it; I just need to know whether it's available or not,but I can't seem to find a simple check.
Here is what I've tried:
jQuery.noConflict();
jQuery(document).ready(function(){
var photo = '223';
var exists = false;
jQuery.load('/'+photo+'.xml', function (response, status, req) {
if (status == "success") {
exists = true;
}
});
});
Assuming you are talking about an xml file on the server, you could do a ajax request and then write a custom error handler to check the error response message. You'll need to know what the exact error message code is for a missing file (usually 404). You can use Firebug Console to check what the exact error message and code is.
$.ajax({
type: "GET",
url: "text.xml",
dataType: "xml",
success: function(xml) {
alert("great success");
},
error: function(xhr, status, error) {
if(xhr.status == 404)
{
alert("xml file not found");
} else {
//some other error occured, statusText will give you the error message
alert("error: " + xhr.statusText);
}
} //end error
}); //close $.ajax(
Your question isn't clear to me. If I understand, you want to verify whether a file (the XML) is present or not in the HTTP server.
That's correct? If so, you can just do:
$.get('url-to-file.xml', function(response, status, req) {
if (status == 'success') {
alert('exists');
}
});
EDITED: As pointed by #lzyy on comments, .get() only calls the callback upon success. However, I'd stick to the .load() using $(document) as selector. See:
$(document).load('url-to-file.xml', function(response, status, req) {
if (status == 'success') {
alert('exists');
} else if (status == 'error') {
alert('doesnt exist');
}
});

Categories