JS changes cursor only when js function is completed - javascript

I have the following code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body style="background-color:yellow;width:100%;height:100%;">
test
<script>
function test() {
$("body").css("cursor","wait"); //cursor must be changed here
$.ajax(...);
}
</script>
</body>
</html>
The problem with this code is that cursor changes from default to wait in browser only when function test() is completed, but I need it to change in certain point of function. I tried in FF 58 on Ubuntu 14 and in Opera in Windows 7. I've read many posts about it and tried also this solution
$(document).ajaxStart(function() {
$(document.body).css({'cursor' : 'wait'});
}).ajaxStop(function() {
//$(document.body).css({'cursor' : 'default'});
});
but without success. How to fix it? Any ideas?

I found the answer. I had in my ajax async:false -
$.ajax({ ...
async: false,
...
});
When I changed to
$.ajax({ ...
async: true,
...
});
everything started to work as expected.

$(document).ajaxStart(function (event, jqxhr, settings) {
$(document.body).css({ 'cursor': 'wait' });
});
$(document).ajaxComplete(function (event, jqxhr, settings) {
$(document.body).css({ 'cursor': 'normal' });
});
$(document).ajaxError(function (event, request, settings) {
$(document.body).css({ 'cursor': 'normal' });
});
function AjaxCall() {
$.ajax({
type: "POST",
url: '/home/AjaxURL',
contentType: "application/json; charset=utf-8",
global: true,// this makes sure ajax set up ajaxStart/ajaxComplete/ajaxerror will triggered
dataType: "json",
success: function () { },
error: function () { }
});
}
$(document).ready(function () {
AjaxCall();
});
Note- Setting the cursor to document.body as you did means it will only apply in document and did not apply in other dom elements like anchor, textbox etc

You can use before send like this:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......`enter code here`
});
OR use when and timeout:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ajaxready() {
setTimeout(function() {
$.ajax({
url: "https://www.w3schools.com/jquery/demo_test.txt",
beforesend: function() {},
success: function(result) {
$("#div1").html(result);
$("body").css("cursor", "");
}
});
}, 500);
}
function loading() {
$("body").css("cursor", "wait"); //cursor must be changed here
}
$(document).ready(function() {
$("button").click(function() {
$.when(loading()).done(function() {
ajaxready();
});
});
});
</script>
<style>
button {
cursor: inherit
}
</style>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<span></span>
<button>Get External Content</button>
</body>
</html>

Related

Jquery disable button on a synchronous call

I am trying to disable a button to prevent multiple click in a synchronous ajax call. My code is as follows.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <!-- optional font -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
var test = false;
$(document).on('click', '#test', function(e){
console.log(test);
if (test) {
return;
}
test = true;
ajax_call();
});
function ajax_call() {
$.ajax({
contentType: 'application/json;charset=utf-8',
type: 'POST',
url: 'https://validdomain',
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: JSON.stringify({'test' : 'test'}),
success: function(data, textStatus, jqXHR) {
console.log(data);test =false;
copypaste();
test = false;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
test = false;
},
async: false,
});
}
function copypaste() {
var tempInput = document.createElement("textarea");
tempInput.setAttribute('id', 'copyid');
tempInput.style = "position: absolute; left: -1000px; top: -1000px";
tempInput.value = 'Text Copied';
console.log(tempInput);
document.body.appendChild(tempInput);
tempInput.select();
var result = document.execCommand('copy');
document.body.removeChild(tempInput);
if (result) {
alert('copied');
}
else {
alert('not copied');
}
return result;
}
});
</script>
</head>
<body>
<input type="submit" id="test"/>
</body>
</html>
But my button is not disabled on the second click(I am getting alert twice.). If I make the ajax request as an asynchronous call then button is disabled. Is there any way that I can disable my button during a synchronous call?
Thanks in advance!
I added the necessary statement but you could put it to another place for example inside the ajax callback function. Also I changed async: false
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <!-- optional font -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
var test = false;
$(document).on('click', '#test', function(e){
console.log(test);
if (test) {
return;
}
test = true;
ajax_call();
//Try adding this statement you can add wherever you want
$(document).off('click', '#test');
});
function ajax_call() {
$.ajax({
contentType: 'application/json;charset=utf-8',
type: 'POST',
url: 'https://validdomain',
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: JSON.stringify({'test' : 'test'}),
success: function(data, textStatus, jqXHR) {
console.log(data);test =false;
copypaste();
test = false;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
test = false;
},
async: true,
});
}
function copypaste() {
var tempInput = document.createElement("textarea");
tempInput.setAttribute('id', 'copyid');
tempInput.style = "position: absolute; left: -1000px; top: -1000px";
tempInput.value = 'Text Copied';
console.log(tempInput);
document.body.appendChild(tempInput);
tempInput.select();
var result = document.execCommand('copy');
document.body.removeChild(tempInput);
if (result) {
alert('copied');
}
else {
alert('not copied');
}
return result;
}
});
</script>
</head>
<body>
<input type="submit" id="test"/>
</body>
</html>
Why not simply disable the button and re-enable it instead of declaring a global variable like $("#test").attr('disabled','disabled') ? Variable scopes can get tricky in javascript.
You happen to be looking for something simple like this?
PS: You have to enter the details for the ajax call yourself.
html
<button id="button">Button</button>
jQuery/js
$("#button").click(function(){
console.log("clicked");
// deactivate button
$("#button").attr("disabled", true);
ajaxCall();
});
function ajaxCall(){
$.ajax({
//...ajax call here,
complete: function(){
// reactivate button after you receive any reply from ajax
$("#button").attr("disabled", false);
}
})
}

ajax with json how to

I try AJAX and JSON.
I have got this very simple scripts. Could you help me to get it work?
html file
<div class="esemeny">
<h2>Event</h2>
<p></p>
<button>click</button>
</div>
json file, I call it eventresult.json
{name: whatever,
}
and the javascript file
$(function(){
$('button').on('click', function(){
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
Thank you
You didn't tell what did want to do exactly, anyway I think, this what you want to do:
JSON:
{
name: "whatever"
}
JS:
$(function(){
$('button').on('click', function(){
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
type: 'GET' // you want to get content
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
Hope that helps a bit
I guess your JSON should look like
{
name: "whatever"
}
Mind the double quotes and the unnecessary comma.
Well,you actually didn't descripte the question clearly.You can have a debug that can be seen from your firebug console,like this:
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
}).fail(function(jqXHR, textStatus, errorThrown){console.log(textStatus+':'+ errorThrown)})
Here are some suggestions that should make it work:
Make sure you include the necessary script files in your html file:
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>
<div class="esemeny">
<h2>Event</h2>
<p></p>
<button>click</button>
</div>
<script src="javascript.js"></script>
Make sure you use valid json in the json file
{
"name": "whatever"
}
Use .click() function in your javascript:
$(function() {
$('button').click(function() {
$.ajax('/trials/eventresult.json', {
dataType: 'json',
success: function(result) {
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});

window.location.reload(); is working only when used with alert();

I am using this code to reload my page on on checkbbox click-
<script type="text/javascript">
function showInactive(cb){
$.get('showInactive', function(data) { }, 'json');
alert();
location.reload();
}
function hideInactive(cb){
$.get('hideInactive', function(data) { }, 'json');
alert();
location.reload();
}
</script>
This is working fine but when I remove the alert(); this code doesn't work.
Your mistake is how you call $.get. Look in to API https://api.jquery.com/jQuery.get/
And I guess your location.reload() should be in callback.
<script type="text/javascript">
var url = 'http://google.com';
function showInactive(cb){
$.get(url, function(data) {
location.reload();
}, 'json');
}
function hideInactive(cb){
$.get(url, function(data) {
location.reload();
}, 'json');
}
</script>
May be this is helpful for you
<script type="text/javascript">
function showInactive(cb){
$.get('Use path of your file', function(data) {}, 'json');
window.location.reload();
}
function hideInactive(cb){
$.get('Use path of your file', function(data) {}, 'json');
window.location.reload();
}
</script>

Submit unresponsive after ajax call + fadeIn()

Good day, fellow programmers.
There's this index.php that does an Ajax call to login.php and appends the DOM elements and some javascript from inside this into the body of the index. This login.php consists out of a a single div that contains a form and a submit button, which fadeIn() as soon as it is all appended.
However: the submit button is unresponsive!
I did find, after a while, that this does not happen when you directly access login.php via URL (.../.../login.php) instead. This means it's the fact that the index appends the whole, which makes them unresponsive.
(Also: in light of this, I've added a $(document).ready(function(){ ... }); around the entire script in the login.php, but that did not seem to help at all. Instead it caused all functions to return errors...)
I'm out of ideas. Perhaps some of you might have had any experience with these matters?
As always, thank you for the time!
Here's the (simplified) code:
index.php
$('#logInButton').click(function(){
loadContent('/login/login.php', 'body');
});
loadContent();
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
}
});
}
}
login.php (deleted some styling. If you want some specific info, just ask!)
<style>
// some styling
</style>
<div id="loginBlack">
<div class="login" style="z-index:9999;">
<form id="myform1" name="myform1">
<div>
<img src="images/inputEmail.png" />
<div id="emailOverlay">
<input id="email" type="text"/>
</div>
</div>
<input id="iets" name="iets" type="submit"/>
</form>
</div>
</div>
<script type="text/javascript">
// $(document).ready(function(){ // <-- been trying this out.
$('#loginBlack').fadeIn(t)
// some functions pertaining to logging in and registering
// });
</script>
Use jquery on() instead of click()
$('body').on('click', '#logInButton' ,function(){
loadContent('/login/login.php', 'body');
});
That should make the elements behave properly
Note: you can also replace body selector with something nearer to the click button ( its nearest parent )
EDIT::
With this you can have the styling in your normal css file. Put it outside of the login.php
And your js goes into into the success handlers. So just leave the php with the actual html
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
}
});
}
}

JQuery callback not executed?

I want to have a progressbar that take data from server, so I created 2 servlets the first one (process) starts the process and when it ends return the result; the second one (GetEvent) gets progress information from session every 500ms..
All of this works normally and the progress information is displayed correctly, but the
process Servlet's callback never executes.
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
process();
$("#progressbar").progressbar({ value: 0 });
$("#progressStatus").html("");
getEvent();
});
function process()
{
$.getJSON("process", function(result){
//never executed
alert( "Result: " );
});
}
function getEvent()
{
$.getJSON("GetProgressEvent", function(data) {
$.each(data.ProgressEvents, function(){
$("#progressbar").progressbar({ value: this.progress });
$("#progressStatus").html(this.status);
});
});
setTimeout(getEvent, 500);
}
</script>
</head>
<body style="font-size:62.5%;">
<div id="progressbar"></div>
<div id ="progressStatus"></div>
</body>
</html>
I just started with JQuery and I don't know what's wrong with this code.
you are calling $.getJSON with a url "process"
this function has no error handling if there is problem with the response or invalid JSON is returned then the callback will not be called.
http://api.jquery.com/jQuery.getJSON/
jQuery.getJSON( url, [data], [success(data, textStatus, jqXHR)] )
url A string containing the URL to which the request is sent.
data A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR)A callback function that is executed if the request succeeds.
Try adding a valid url in place of "process" and if that fails use the
$.ajax method as follows
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: $.param( $("Element or Expression") ),
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});

Categories

Resources