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 );
}
});
Related
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! :)
I am performing an ajax request cross domain. I have been trying to use functions that return the headers in an array only to find that I get Undefined Index even though I can return their values in my ajax request and print them the screen.
I have found some posts on SO that said I should be using $_SERVER globals. So I switched to that method only to get the same results.
Here is my jQuery:
setTimeout(function() {
jQuery.ajax({
url: 'http://something.com',
type:"POST",
dataType:"json",
crossDomain:true,
contentType:"application/json",
data: jsonData,
processData:false,
cache:false,
beforeSend: function( xhr ) {
xhr.setRequestHeader("Authorization",api_key[index]);
xhr.setRequestHeader("Action","PUSH");
},
success: function(data) {
alert(data.action);
alert(data.platform + ' : ' + data.message + ' : ' + data.app_name );
if(data.message == 'success')
{
jQuery('#hollmanPNs_send_push div#hollmanPNs_progressbar' + index).progressbar("value",100);
//add message to the paragraph for app name
jQuery('#hollmanPNs_send_push p#hollmanPNs_paragraph' + index).append(': Complete');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert( 'We had an error: ' + textStatus + errorThrown );
}
}).fail(function() {
alert( 'We had a failed AJAX call.');
});//end ajax
}, index * 5000);//end timeout function
And here is what I am using for PHP:
if($_SERVER['HTTP_ACTION'] != '')
{
//Do Something
}
I have tried switching to:
xhr.setRequestHeader("X-Action","PUSH");
and
$_SERVER['HTTP_X_ACTION']
with the same results. Only I was not able to return them to my ajax request.
I am using PHP 5.3.3.
I am also using this function which I change depending on the different headers I am trying at the time:
header('Access-Control-Allow-Headers: Action, Authorization, Content-Type');
You'll want to get the headers a different way like so:
$headers = getallheaders();
if(array_key_exists('Action', $headers) && $headers['Action'] != '')
{
//Do Something
}
I am working with .load function in jQuery to load a html page into a div with ajax but I have problem since server always doesn't send a html, sometimes it send a json and I want to get that json with .load.
I thought it would be a response in callback function in .load but it return undefined and just put that json into the div so how can I get that json with .load.
The server send this json :
{ok : false}
Here is my jQuery code:
$( "#div").load( "url", function( response, status, xhr ) {
////how can I get the false result here response.ok return nothing!!!
console.log(response.ok);
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#div" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
i think you have to do something like this:
$("#div").load( "url", function( response, status, xhr ) {
var responseAsObject = $.parseJSON(response);
console.log(responseAsObject.ok);
});
Using response to replace #div html content :
$("#div").load("url", function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success") {
var responseAsObject = $.parseJSON(response);
$(this).html( responseAsObject.response );
}
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
This question already has answers here:
What's the best way to retry an AJAX request on failure using jQuery?
(9 answers)
Closed 8 years ago.
I am having an ajax call that needs to run and if it fails then it should reinitialze the same ajax. As i have gone through some post there is failure function under where we can tell user that ajax call failed and follow some set of function.
But i wish to reintialiaze the same ajax call in failure or somewhere else so that when that ajax fails so in fails it intilized again.
deleteImage : function(objId,thumburl,original,ev){
jQuery('#imageBlocksDiv').append(jQuery("#confirmboxtmp").html());
setToCenterOfParent( $('#confirmbox'), document.body, false, true );
jQuery("#confirmbox").fadeIn().css({top:-210,position:'fixed'}).animate({top:50}, 100, function() {});
jQuery('#deleteconfirmbox').click(function(){
jQuery(this).text('Deleting..');
if(typeof objId!='undefined'){
var iputadatatologdelete = {
"media_image_objectId": objId,
"action" : "deleted"
};
iputadatatologdelete.company_objectId = jQuery('#cid').val();
iputadatatologdelete.edited_by_user_objectId = jQuery('#uid').val();
var inputData = {
'id' : objId,
'imgurl' : original,
'thumburl' : thumburl
}
jQuery.ajax({
'type':'POST',
'url': '#####/a###pi/###/####/#####',
'data' : inputData,
success : function(response){ //console.log(response)
jQuery('#'+objId).parents().eq(2).remove();
console.log(objId);
jQuery('#confirmbox').hide();
jQuery('#deleteconfirmbox').text('Delete');
pinterest(undefined);
logdata("sc_media_image_edited_log", iputadatatologdelete)
}
});
}
The function is something like this if i go to make function for every kind of ajax that i am calling then that will be bunch of codes. As i have already made loads of ajax with diffrent urls and type.
error : function(xhr, textStatus, errorThrown ) {
//try again
$.ajax(this);
return;
}
Will this work in case of reinitializing the same query.
You can do something like this:
function doAjax() {
$.ajax({
url: ...
success: ...
error: doAjax
});
}
doAjax();
Note, that in case of continuous failure, this will infinitely loop unless you implement a protection mechanism (e.g. a counter and a condition to stop the loop after a number of failed attampts).
To call exactly the same ajax, you can make it recursively, something like this:
function callAjax(){
$.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
callAjax();
})
.always(function() {
alert( "complete" );
});
}
Otherwise you can control it with a "control variable", like this:
function callAjax(){
var control = 0;
while (control === 0){
$.ajax( "example.php" )
.done(function() {
alert( "success" );
control = 1;
})
.fail(function() {
alert( "fail" );
})
.always(function() {
alert( "complete" );
});
}
}
I hope it helps you.
In error callback , call the the same ajax request method
Try below code:
$(document).ready(function(){
(function callAjax(){
$.ajax({
url: url,
success: function(res){ },
complete: callAjax
});
})();
})
You can use "complete" function for that because you either get success or error complete function will call in each case.. http://api.jquery.com/jquery.ajax/
As in the failure function we can reset the same ajax call by below lines .
error : function(xhr, textStatus, errorThrown ) {
jQuery.ajax(this);
return;
},
If i am some where wrong please give the feedbacks on the same
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.