My ASPX code generated some html files where I just put link for paging like
First |
Next |
Previous |
Last
say if user currently on second page when it press Next moves to 3rd page ...
now issue is when user clicking Next button several times and system is in progress to generate let say 5th page it will show error page.
Is there any way to check from html via javascript to check whether file is present or not?
Kindly help me to pull out from this show stopper issue
You can use ajax for check file exists or not
Using Jquery
$.ajax({
url:'http://www.example.com/3.html',
error: function()
{
alert('file does not exists');
},
success: function()
{
alert('file exists');
}
});
Using Javascript
function checkIfRemoteFileExists(fileToCheck)
{
var tmp=new Image;
tmp.src=fileToCheck;
if(tmp.complete)
alert(fileToCheck+" is available");
else
alert(fileToCheck+" is not available");
}
Now to check if file exists or not call js function like this
checkIfRemoteFileExists('http://www.yoursite.com/abc.html');
i like to use this type of script
function CheckFileExist(fileToCheck: string) {
return new Promise((resolve, reject) => {
fetch(fileToCheck).then(res => {
if (res.status == 404) resolve(false);
if (res.status == 200) resolve(true);
return res.text()
})
})
}
and use it
var exists = await CheckFileExist(link);
There is an issue with #Sibu's solution: it actually downloads the file (it can be potentionally big, wasting traffic)
In the 2021, one should not use jQuery in new projects
native Promises and Fetch are the way to go today
<output id="output"></output>
<script>
// create a non-cached HTTP HEAD request
const fileExists = file =>
fetch(file, {method: 'HEAD', cache: 'no-store'})
.then(r => r.status==200);
// check the file existence on the server
// and place the link asynchronously after the response is given
const placeNext = file => fileExists(file).then(yes => output.innerHTML =
(yes ? `Next` : '')
);
// place the "next" link in the output if "3.html" exists on the server
placeNext('3.html');
</script>
Related
I have a registration form, the user is being redirected to home.php after success (works)
But also all the 'alerts/errors' which are echos in PHP, after submit, will redirect to register.php and show the error in blank white page.
(How do i display them to <div class="msg"> position?)
<script>
document.querySelector(".register form").addEventListener("submit", async (e) => {
e.preventDefault()
const form = e.target
const body = new FormData(form)
// fetch is much easier to use than XHR
const res = await fetch(form.action, {
method: "POST",
headers: {accept: "application/json", // let PHP know what type of response we want},
body})
const data = await res.json()
if (res.ok) {
location.href = data.location
} else if (res.status === 400) {
document.querySelector('.msg').textContent = data.message
// also do something with data.errors maybe
}
})
</script>
<body>
<div class="msg"></div> <!--position for error/ wrong pass etc-->
register.php
Based off that, please provide a correct code snippet in order to mark this as resolved.
It would probably make your life quite a bit easier if you always returned JSON from your PHP, rather than sometimes HTML as well.
For examples, when checking the errors at the top of register.php, you should return JSON objects --- e.g.
{error: "Email is not valid!"}
rather than their HTML equivilents.
This means that in your fetch, you'll now always be able to get the JSON content (currently, you'd probably get an error in your browser's debug console if one of those messages came back, as it's not valid JSON). Then, in your JavaScript, you can just detect this and switch however you want:
if (data.error) { // If there is an error
document.querySelector(".msg").textContent = data.error;
}
else if (data.location) { // If we want to redirect the user somewhere
window.location.href = "./" + data.location;
}
I am very new to javascripting and html.
I have built a web page that is mostly used to load either txt or other html pages using tag.
But I am trying to create a validation statement to check if the source file exists and load the iframe or if it doesn't to display a message.
I have tried the below code, but it just doesn't work.
Can anyone please help me?
<script>
var url = checkfile('../folder/test.html');
if (url.exists()){
<iframe id = "allviewer" src = "../folder/test.html"> < /iframe>
} else {
< p > This file does not exist < /p>
}
</script>
You should already avoid adding the iframe in the script tag, if you want to check if the file exists you can use ajax but the ajax already allows you to see the content so the iframe is no longer really necessary
<script type="text/javascript">
function url_exists(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest;
xhr.open("GET", url, false);
xhr.send();
if (xhr.status == 200) resolve(xhr);
else reject(xhr.status);
})
}
const file = '../folder/test.html';
url_exists(file).then(t => {
console.log(t.response); // show file content in the console
ouputNode.innerHTML = `<iframe id="allviewer" src="${file}"></iframe>`;
}).catch(e => {
// on error
});
</script>
<div id="ouputNode"></div>
I want to load the js file after redirect to destination in drupal. I have created a custom module with a hook_user_login.I have redirect a page in successful login and want to load a js file after redirect.now file loads in between login success and until redirect.
function one_time_popup_user_login(&$edit, $account){
$userName='test';
if(!isset($_COOKIE[$userName])){
$count=1;
if($count==1)
{
drupal_add_js(array('one_time_popup' => array('aniv' => $anniversaryCount,'userName'=>$userName,'celeType'=>'Anniversary')), array('type' => 'setting'));
drupal_add_js(drupal_get_path('module', 'one_time_popup') . '/celebrationPopup.js','file');
$settings=variable_get('one_time_popup_effects',unserialize(ONE_TIME_POPUP_DEFAULT));
drupal_add_js(array('onetimepopupmenu'=>$settings),'settings');
setcookie($userName, '1', time()+(24 *3600));
}
if (!isset($_GET['destination'])) {
$_GET['destination'] = drupal_get_destination(); //get the current url
}
}
}
I think you need to have the JS in your destination page. And tell that page when to run it. Or add it in a hook that targets that particular page.
First I would include some extra validation in your hook so the redirect doesn't happen when a user is trying to recover the password.
See how I am checking for the 'user_pass_reset' form id in the following exampes:
Firing the JS using another JS function
function one_time_popup_user_login(&$edit, $account) {
if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
$_GET['destination'] = 'your/custom/path#celebrationpopup';
}
}
Notice how I've added a hash (#celebrationpopup) to the destination url.
We will use this later in our destination page to run the JS function that we need.
Example jQuery code you need to place in the destination page. For this to work you need to have the function one_time_popup() already loaded in your code. This is just an example.
$(document).ready(function() {
//Get hash from URL
var hash = location.hash;
if (hash == '#celebrationpopup') {
one_time_popup();
}
});
Another option: Using a hook
If your destination page is a node you can use:
function one_time_popup_user_login(&$edit, $account) {
if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
$_GET['destination'] = 'your/custom/path?celebrationpopup=true';
}
}
function one_time_popup_node_view($node, $viewmode, $langcode) {
if($node->type == 'some_type' && isset ($_GET["celebrationpopup"])) // You can also use a node ID.
{
drupal_add_js(array('one_time_popup' => array('aniv' => $anniversaryCount,'userName'=>$userName,'celeType'=>'Anniversary')), array('type' => 'setting'));
$node->content['#attached']['js'][] = array
(
'type' => 'file',
'data' => drupal_get_path('module', 'one_time_popup') . 'js/celebrationPopup.js',
);
}
}
You might as well use a page preprocess function.
Hope this is clear.
I have the following code in my main Dancer app .pm:
package Deadlands;
use Dancer ':syntax';
use Dice;
our $VERSION = '0.1';
get '/' => sub {
my ($dieQty, $dieType, $bonus);
my $button = param('button');
$dieQty = param('dieQty');
$dieType = param('dieType');
$bonus = param('bonus');
if (defined $dieQty && defined $dieType) {
return Dice::Dice->new(dieType => $dieType, dieQty => $dieQty, bonus => $bonus)->getStandardResult();
}
template 'index';
};
true;
Here is my JavaScript:
$(document).ready(function() {
$('#standardRoll').click(function() {
$.get("/lib/Deadlands.pm", { button: '1', dieType: $("#dieType").val(), dieQty: $("#dieQty").val(), bonus: $("#bonus").val() }, processData);
function processData(data) {
$("#result").html(data);
}
});
});
I have a div in my web page called result that I want to be updated with the die roll result from Perl. Dancer keeps coming back with a 404 error in the command window when I push the submit button.
/lib/Deadlands.pm needs to be the URL of your route (probably / in this case), not the filesystem path of your Perl module.
Your AJAX request needs to point to a URL that actually exists, not a filename that has nothing to do with the web. Looks like $.get('/', ...) would do in this case.
I'm using a framework called PartialJS that follows a MVC architecture to build a webApp that will verify a user's input and make a request to an API and render the API response.
I'm not sure how to redirect the user to the rendered page after verification and API call has finished. Where should the page redirect and API calls be made?
Here's a quick breakdown of what the user will see with 'bullet' marks denoting what happens in the backend:
User presented with a form and fills information
exports.onValidation() called via a serialized JSON to verify that
all fields completed accurately (triggered by a button), done without
a page refresh.
API call is made with user's information, will not return until response is received and parsed
Form rendered with decoded JSON response from external API
I have tried using this in the 'view.html' page but the page redirects before verification.
<buttononclick="window.location='http://www.CaliCoder.com/results';">Submit</button>
<script type="text/javascript">
$(document).ready(function() {
$('button').bind('click', function() {
$.post('/', $('#f').serialize(), function(d) {
var err = $('#error');
if (d instanceof Array) {
err.empty();
d.forEach(function(o) {
err.append('<div>' + o.error + '</div>');
});
err.show();
return;
};
$('#f').trigger('reset');
err.empty();
err.show().html('SUCCESS! Please wait while the request is being made')
});
});
});
</script>
Here's what happens in the 'controller.js' end of things.
function json_form() {
var self = this;
var error = self.validate(self.post, ['intersection', 'hours', 'minutes', 'phone'])
if (error.hasError()) {
self.json(error);
return;
}
// save to database
var db = self.database('forms');
db.insert(self.post);
self.json({ r: true });
}
function get_routes(hours, minutes, intersection) {
//The following code makes a call that returns an array with data to be rendered by another view controller.
var stops = this.module('cumtd').GetStopsBySearch('springfied busey');
}
Thanks for reading! Sorry for sounding confusing, I'm new to JS and Node programming. :(
You have problem in clide-side JavaScript, solution:
HTML:
<button>Submit</button>
JavaScript:
$(document).ready(function() {
$('button').bind('click', function() {
$.post('/', $('#f').serialize(), function(d) {
var err = $('#error');
if (d instanceof Array) {
err.empty();
d.forEach(function(o) {
err.append('<div>' + o.error + '</div>');
});
err.show();
return;
};
$('#f').trigger('reset');
err.empty();
err.show().html('SUCCESS! Please wait while the request is being made');
// HERE REDIRECT:
setTimeout(function() {
window.location.href = 'http://www.CaliCoder.com/results';
}, 3000);
});
});
});