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.
Related
I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.
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;
}
});
}
});
}
}
I am pretty new to html5 web development
I have created a page with login and password on it and have a submit button.
On submit , I send a rest request to the server which has a url
THE RRQUEST IS SOMETHING LIKE THIS
<USERNAME>
abc
</USERNAME>
<PASSWORD>loooik
</PASSWORD>
which is in js file as var data...
This request is set as
var parameters=JSON.stringify(data);
I use the following code for establishing connection
xmlHttp.open("post",url,true);
XmlHttp.setRequestHeader("Content-type","application/json);
xmlHttp.send(parameters);
xmlHttp.onreadystatechange=function X()
{
if(xmlHttp.readyState==4)
{
alert(xmlHttp.responseText);
}
}
return true;
}
I need to add a loading element and want to display the next screen between request and the response. How can I achieve it?
In tag I have used submit input type where onClick attribute calls return sendPost() method which has the request to be called
How should I proceed for the same... having loading screen and getting the response ... suppose just the name to be displayed on next html screen
First of all see basic jQuery example. This will guide you through how jQuery works and help a lot in the solution I'm going to suggest.
http://learn.jquery.com/about-jquery/how-jquery-works/
jQuery has it's own AJAX method and further shorthand called $.post
Now you can write something like this -
function requestNetwork() {
// Code for loading screen
$.ajax({
url: "yourURL",
data: "yourData"
}).done(function(data) {
alert(xmlHttp.responseText);
// Code for dismissing loading screen
}).fail(function(data) {
// Code when call fails
}).always(function() {
// This code will always run
});
}
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
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.