I have a link redirecting to an intranet direction:
Go
Only users in intranet can access, otherwise they get a 404 error. I want to know if the the url is valid before redirecting, this way users out of intranet won't get the 404 error but a message saying 'You don't have access'. How can I do this with jquery or javascript?.
EDIT:
Well, thank you very much, but unfortunately any method does not work for me. Sorry, I didn't mention that website and intranet url are in differente domain.
Finally I had to validate user IP in codebehind and write or not the intranet url.
You could make an ajax request first, something like:
$.ajax({
url: "http://10.2.68/name/",
context: document.body,
success: function(){
window.location = "http://10.2.68/name/";
}
});
That could be run by binding to the click event on the link.
Not sure if it will work due to cross origin stuff, but might be a good place to start.
You can use this jQuery plugin to make a head request to the remote file, if it comes back with something it is good (and you can display it for instance) otherwise don't show it
Plugin:
http://binarykitten.me.uk/dev/jq-plugins/88-jquery-plugin-ajax-head-request.html
Perhaps use an htaccess file to detect the internal network instead?
The best answer would be to disable the link if it's inactive, before the user tries to click it (why make them try?).
jQuery(function($) { // make sure dom is ready
$.ajax( {
url: url,
//dataType: 'JSONP', //might need this?
complete: function(xhr) { // use complete so it fires on error OR success
if( xhr.status == 200 || xhr.status == 304 ) {
$('#link').addClass('valid');
}
else {
$('#link').addClass('invalid').click(function() { return false; });
}
}
});
});
But if you don't want the call because there are going to be thousands of users looking at the page every minute...
jQuery(function($) { // make sure dom is ready
$('#link').click(function() {
$.ajax( {
url: url,
//dataType: 'JSONP', //might need this?
success: function() {
window.location = url;
},
error: function() {
// does this work with JSONP? be sure to check!
window.alert('could not connect');
}
}
});
});
Assuming your anchor has an ID:
<a id="lnkGo" href="http://10.2.68/name/">Go</a>
And your jQuery code might look like this:
$("#lnkGo").bind("click", function() {
var $that = $(this);
$.ajax({
url: $that.attr("href"),
statusCode: {
200: function() {
window.location = $that.attr("href")
},
404: function () {
alert("Sorry, page is unavailable...");
}
}
});
return false;
});
Also, please keep mind that this won't work on cross-domain issue. The url has to be same as the current domain.
Related
I tried searching all over the Internet and found no simple answer, which I believe exists for two problems I'm having. My Jquery UI Autocomplete is below:
$('#moviename').autocomplete({
// URL is parsed by my framework
source:"<?=URL::route('MovieAutocomplete')?>",
minLength:2,
dataType:"json",
select:function(event,ui){
// set artist id
$('#movieid').val(ui.item.id);
$('#moviename').prop('disabled',true);
$('#moviedetails').prop('disabled',false);
$('#movieclear').html('Clear');
$('#moviehint').toggle();
}
});
This code works. However, I am looking at the performance. I have two questions:
My controller cancels the request if it sees a blank term. However, I would like to check this condition even before the request is sent. I have played with beforeSend, but it doesn't work somehow. Can someone help me accomplish this one?
I would also like to fire the AJAX request only when the user stops typing, say give it a time of 500ms to wait before it can send request to the server. Is there any easy way to do this? I am guessing "call autocomplete inside a keyup event which will be bound to the field I want". Please help me.
It would be great if someone can look into this one for me.
I recently have been working with the jQuery UI autocomplete. This is the logic I used & it works well.
onKeydownMethod: function(event) {
if ($(this).val().length >= App.autocompleteMinLength)
{
if ($(this).val().length >= YOUR_MIN_LENGTH) {
$('selector').autocomplete({
minLength: YOUR_MIN_LENGTH, // min number of chars before request is made.
delay: YOUR_DELAY, // mum of miliseconds to wait before making request.
source: function(request, callback) {
$.ajax({
type: 'get',
contentType: 'application/json',
url: 'YOUR_URL' + ANY_PARAMS,
dataType: 'json',
timeout: 50000
}).done(function(response) {
callback(response); // I used a callback to send data back to the parent function. Handle the response however you like here.
}).fail(function(error) {
switch (error.statusText)
{
case 'OK':
// handle response.
break;
default:
// handle response
break;
}
});
}
});
}
}
Very new to code in general so apologies in advance if i dont explain myself properly,
But I have a form, that actions a piece of JavaScript on submit.
If the form validates successfully then it calls a php file for server side processing.
Once the server side processing is complete the php file returns some data (a url) which the user is then redirected to (client side)
This all works fine on desktop (chrome, IE, FF) and via modern mobile devices, however the redirect is not working on some devices (blackberry for one), and a i assume other older devices. Instead of the redirect URL going straight into the address bar, it is being placed after the url of the original page - as such causing the user to be redirected to a page that of course doesnt exist.
Below is the script that is called on submit. Again apologies if none of the above makes sense...I am very new to all this:
$(function () {
$('#wait').hide();
$('form#leads_form').on('submit', function (e) {
if (validateFrm()) {
$(":submit", this).attr("disabled", true);
$('#wait').show();
var jqxhr = $.ajax({
type: 'post',
timeout: 300000,
url: 'sell-save-leads.php',
cache: false,
data: $('form').serialize(),
success: function (data) {
//alert("Submit success: " + data);
window.top.location.href = data;
}
});
} else {
//alert("validation errors");
$('#wait').hide();
}
e.preventDefault();
});
});
If anyone is able to help or offer some advice that would be great.
As your form is located in an iFrame I suggest you to use this jQuery plugin to send messages from an iframe to its parent:
http://benalman.com/projects/jquery-postmessage-plugin/
With this you could send a message from inside your success function, containing the new url, and catch it in the parent window.
You can also use
window.top.location.assign(data);
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window.location
Is it possible to check the Availability of a page before loading it?
I have a form, running on mobile device using wireless connection. The problem is: not always this connection is available and I would like to alert the user when is doing a submit or an unload of the page.
The problem is that the page contains elements doing redirect like this:
<input type="button" value="MyText" onClick="script1;script2;...window.location='mylocation'" />
If the user click on this button and the server is not achievable, i will receive some undesirable errors.
Also if I want to generalize my script i do not know the value of "mylocation" previously.
The page contains elements to submit the Form also:
<input type="submit" name="SUBMIT" value="MyValue" onClick="return eval('validationForm()')" />
For the submitting I'm using the ajaxForm plugin and it works quite well.
to navigate back easily use this instead:
<input type="button" value="Back" onClick="window.location='history.go(-1);" >
where -1 means previous page. If you want to reload the current page use 0 instead, to navigate forward, use 1, etc.
If you use ajax from jquery, it sould handle it by itself... http://api.jquery.com/jQuery.ajax/
$.ajax({
///... need argument here...
timeout: 5000, // in milliseconds
success: function(data) {
//Do something success
},
error: function(request, status, err) {
if(status == "timeout") {
alert("can't reach the server");
}
}
});
EDIT AFTER COMMENTS:
You can check How do I check if file exists in jQuery or JavaScript?
in your case this sould work as expected:
//Initialize the var as global so you can use it in the function below
var goto_url = "http://www.mywebsites.com/foo.html";
$.ajax({
url:goto_url;
type:'HEAD',
error: function()
{
//do something if the gile is not found
},
success: function()
{
document.location = goto_url; //docuemnt.location will redirect the user to the specified value.
}
});
this will actually check if the file exist.. If it can't connect to the file it will not be able to find it..
If he can find the file, he obviouly was able to connect, so either case you win.
cheers!
Thanks to your answer I found the solution to the problem.
This check if the server is achievable before launching a script and redirect.
That's the code:
function checkConnection(u,s){
$.ajax({
url:u,
cache:false,
timeout:3000,
error: function(jqXHR, textStatus)
{
alert("Request failed: " + textStatus );
},
success: function()
{
eval(s);
}
});
}
$(document).ready(function() {
// part of the function that checks buttons with redirect
// for any button that contain a redirect on onClick attribute ("window.locarion=")
$("input[type=button]").each(function(){
var script = $(this).attr("onClick");
var url = "my_url";
var position = script.indexOf("window.location") ;
if (position >= 0) { // case of redirect
url = "\'"+url+"\'"; // that's my url
script = "\""+script+"\""; // that's the complete script
$(this).attr("onClick","checkConnection("+url+","+script+")");
}
});
// part of the function that checks the submit buttons (using ajaxForm plugin)
var options = {
error: function() {
alert("Message Error");
},
target: window.document,
replaceTarget: false,
timeout: 3000
};
$("form").ajaxForm(options);
});
I hope that this will be usefull.
You should use the callback of the jQuery Ajax function to catch the problem of a server not available.
You cant check the servers' availibility without making a request to it.
You're trying to see if there is a connection. AFAIK the only way for actually checking if a server is reachable is making a request to that server.
Set a timeout of a reasonably small amount of time (let's say 3s) and make a request. If you get a timeout error, then there is no connection, else you're good to send the form.
I am serving my website from mywebsite.com. I host images on flickr so all images are loaded in the user's browser via get requests to flickr. Many of my websites users access mywebsite.com from corporate networks, which block access to flickr.com. This means users get very annoying blank placeholders instead of the images. I get the same problem with the Facebook like button. This makes my site look very unattractive to such users.
Is there a way I can run a client side script which will check if flickr.com, facebook.com, etc. are accessible. If not I could change the href attribute of the image to load from an alternate source, or replace with a standard image explaining that their network is blocking access. I could also remove the Facebook like button.
I thought an XML http request would do the trick, but then I'd hit cross domain issues I think. I guess I could also set up a proxy to serve the images, but I don't want to do that; the idea of this is that flickr takes the bandwidth hit.
TLDR: How do I determine if flickr.com is accessible from a user's browser, using client side technology.
You could try this...
var image = new Image();
image.onerror = function() {
var images = document
.getElementById('flicker-images')
.getElementsByTagName('img');
for (var i = 0, imagesLength = images.length; i < imagesLength; i++) {
images[i].src = 'images/flickr_is_blocked.gif';
}
};
image.src = 'http://flickr.com/favicon.ico';
Hacky, but it seems to work. However it relies that the favicon.ico 404ing means the main site is.
jsFiddle.
Working example: http://jsfiddle.net/peeter/pW5wB/
JS:
$(document).ready(function() {
var callbackOnSuccess = function(src) {
alert("Successfully loaded " + src);
return false;
};
var callbackOnFailure = function(src) {
alert("Failed loading " + src);
// Here you can do whatever you want with your flickr images. Lets change the src and alt tags
$(".flickr").attr("src", "flickr_is_blocked.gif");
$(".flickr").attr("alt", "Flicker is blocked");
// Lets change the parents href to #
$(".flickr").parent().removeAttr("href");
return false;
};
checkAvailability("http://flickr.com/favicon.ico", callbackOnSuccess, callbackOnFailure);
});
function checkAvailability(src, callbackSuccess, callbackFailure) {
$("<img/>").attr("src", src).load(function() {
callbackSuccess(src);
}).error(function() {
callbackFailure(src);
});
}
HTML:
<a href="http://flickr.com/favicon.ico">
<img class="flickr" src="http://flickr.com/favicon.ico" alt="Flickr"/>
</a>
For facebook you can simply include the Facebook JS API and then test if one of the objects/functions it exports exists.
It would be better if you did not (ab-)use external hosts for your stuff. If you want a CDN, better use a real one...
Flickr and Facebook both have APIs that support JSONP, so cross-domain isn't an issue.
i.e. Here's a request that just echoes some dummy data from flickr's API.
$.ajax({
url: "http://www.flickr.com/services/rest/?jsoncallback=?",
dataType: 'json',
data: {method: "fickr.test.echo", format: "json", api_key: "02de950d65ec54a7a057af0e992de790"},
success: callback
});
You can't reliably set error handlers on a jsonp reqest, so show a "loading" image until that success callback gets called. Set some timeout that will show an error message if the response doesn't come back fast enough.
This works, but timeout must be set!
$.ajax({
url: "http://example.com/ping.html",
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
timeout: 1000,
cache: false,
success: function(response) {
console.log("SERVER UP!");
},
error: function(e) {
console.log("SERVER DOWN!");
}
});
ping.html should return:
jsonCallback({response:'PONG'});
I need for a php file to process when the user click a link/go back/exits a page. Its part of a saving user info process. if i do a jquery unload how would I fire the php file to load and process.
jQuery(window).bind("unload", function() {
// what should i add?
});
$(document).ready(function() {
$(':input',document.myForm).bind("change", function() {
setConfirmUnload(true);
}); // Prevent accidental navigation away
});
function setConfirmUnload(on) {
// To avoid IE7 and prior jQuery version issues
// we are directly using window.onbeforeunload event
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
if(Confirm('You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.')) {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
}
Make sure you have upgraded version of jQuery. jQuery version 1.3.2 had a bug:
Ticket #4418: beforeunload doenst work correctly
Or use native function:
window.onbeforeunload = function() {....}
I'm guessing a synchronous AJAX call might work.
$.ajax({
async: true,
url: '/foo/',
success: function(data) {
// Finished.
}
});
Of course, keep in mind there's no guarantee any of this will ever happen. My browser may crash. My computer may even power down. And of course I may disable JavaScript. So you'll definitely need a server-side way of handling this in case the convenient JavaScript technique doesn't actually work.
You should use the beforeunload event. You can fire a synchronised ajax request in there.
$(window).bind('beforeunload', function() {
$.ajax({
url: 'foo',
async: false,
// ...
});
});
Be aware that onbeforeunload is not supported by some older browsers. Even if this technique works, I'm not sure how long you can (should?) block this event. Would be a pretty bad user experience if that request would block a few seconds.
A good trade-off is probably to tell the user that something has changed what was not saved yet. Do this with a few boolean checks and finally return a string value in the onbeforeunload request. The browser will then gracefully ask the user if he really wants to leave your site, also showing the string you provided.