Jquery disable button on a synchronous call - javascript

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);
}
})
}

Related

Bootstrap .popover() with ajax loaded data

I have the following setup, which makes the popover appear on the second hover event, since it is not yet been created. The data is called via ajax, and I need to somehow create the .popover() before this, yet activate it successfully afterwards.
$('.entry').on('mouseenter', function () {
var achievementId = $(this).attr('data-entry-achievement-id');
var entry = this;
var entryData = function(response) {
var result = response;
$(entry).popover({
html: true,
placement: 'top',
trigger: 'hover',
title: result.data.definition,
content: result.data.achieved_at
}, "show");
}
$.ajax({
type: "GET",
url: 'href here..',
datatype: "json",
success: entryData,
});
});
How can I achieve this?
This works, but then, due to server response or whatever reason, I get the following error:
$('.entry').popover();
$('.entry').hover( function () {
var achievementId = $(this).attr('data-entry-achievement-id');
var entry = this;
var entryData = function(response) {
var result = response;
$(entry).popover('destroy').popover({
html: true,
placement: 'top',
trigger: 'hover',
title: result.data.definition,
content: result.data.achieved_at
});
$(entry).popover("show");
}
$.ajax({
type: "GET",
url: '/bettleverse/get-achievement-info-for-hover/?achievement=' + achievementId,
datatype: "json",
success: entryData,
});
});
// Error shown in console:
tooltip.js:380 Uncaught TypeError: Cannot read property 'trigger' of null
at HTMLDivElement.complete (tooltip.js:380)
at HTMLDivElement.fn (jquery.js:4496)
at HTMLDivElement.handle (transition.js:54)
at HTMLDivElement.dispatch (jquery.js:4737)
at HTMLDivElement.elemData.handle (jquery.js:4549)
at Object.trigger (jquery.js:7807)
at HTMLDivElement.<anonymous> (jquery.js:7875)
at Function.each (jquery.js:365)
at jQuery.fn.init.each (jquery.js:137)
at jQuery.fn.init.trigger (jquery.js:7874)
You can add some loading message or spinner when popover is hover so that message will be shown and when response is recieve from ajax you can replace it .
Demo Code :
$('.entry').popover({
title: "Coming..",
placement: 'bottom',
trigger: 'hover',
html: true,
content: function() {
return "<i class='fa fa-spinner fa-pulse fa-2x fa-fw'></i>"
}
});
$('.entry').on('mouseenter', function() {
var achievementId = $(this).attr('data-entry-achievement-id');
var entry = this;
/* var entryData = function(response) {
var result = response;*/
setTimeout(function() { //this is just for demo to show effect after ajax success
//get div popover classs..find then popover content
$(entry).siblings(".popover:first").find(".popover-title").text("Done ..") //for title change
var popover = $(entry).siblings(".popover:first").find(".popover-content");
popover.text("YOUR NEW TEXT"); //for body change
}, 1000)
/*}
/*$.ajax({
type: "GET",
url: '',
success: entryData,
});*/
});
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<a data-entry-achievement-id="ss" class="entry" title="">Testlink1</a>

JS changes cursor only when js function is completed

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>

No response in html page call to web api

i am trying to call c# web api but there is no response in html page but i getting response in cshtml
WEB API CODE
namespace MvcApplication3.Controllers
{
public class StoreController : Controller
{
public string Get2()
{
return "response data";
}
}
}
HTML CODE
<html>
<head>
<script src="jquery-1.8.2.js">
</script>
<!--<script src="jquery-1.8.2.min.js">
</script>-->
<script type="text/javascript">
$(function () {
$(document).ready(function () {
$('body').on('click', '.test', function (e) {
alert('a');
jQuery.support.cors = true;
$.ajax({
// url: 'http://localhost:3595/api/values/5',
url: 'http://localhost:1152/Store/Get2',
type: 'GET',
dataType: "Jsonp",
success: function (data) {
alert(data);
}
});
});
});
});
</script>
<title>
</title>
</head>
<body>
<input type="button" value="submit" class="test"/>
</body>
</html>

AJAX Call Is Not Working With The Controller Action

Salaamun Alekum
My AJAX Call Is Not Calling The Controller Action In ASP.NET MVC Web Applicaiton Project
Bellow Is My AJAX Call In Javascript And Next Is Controller's Action
AJAX Call
var requestUrl = '/Home/GetCurrentUser';
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
The Controller Action
[SharePointContextFilter]
public JsonResult GetCurrentUser()
{
CurrentUserModel um = new CurrentUserModel();
try
{
Microsoft.SharePoint.Client.User spUser = null;
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
spUser = clientContext.Web.CurrentUser;
clientContext.Load(spUser, user => user.Title, user => user.Email, user => user.LoginName);
clientContext.ExecuteQuery();
um.Name = spUser.Title;
um.Email = spUser.Email;
um.LoginName = spUser.LoginName;
}
}
SharePointBoxOnline.Common.User u = UserManager.Instance.GetUserByEmail(um.Email);
if (u != null)
{
um.ClientId = u.FK_Client_ID;
um.UserId = u.User_ID;
}
}
catch (Exception e)
{
SharePointBoxOnlineAppWeb.Classes.LogsManager.LogException(e.Message, e.StackTrace, System.Web.HttpContext.Current.Request.Url.ToString(), "Added logging functionality to store the exception information in the Database", DateTime.Now);
}
return Json(um, JsonRequestBehavior.AllowGet);
}
Errors Results In AJAX Are
error.description
Invalid character
status
parsererror
xhr.responseText
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
<link href="/Content/css?v=MDbdFKJHBa_ctS5x4He1bMV0_RjRq8jpcIAvPpKiN6U1" rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>An unexpected error has occurred.</h2>
<p>Please try again by launching the app installed on your site.</p>
</div>
</div>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Internet Explorer","requestId":"673b269bf2c74e39a9496d69f3e0b62e"}
</script>
<script type="text/javascript" src="http://localhost:14069/4b2e31c8e2cf413facce9558ed0cb3ff/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
Thank You Stackoverflow And Members Of Stackoverflow Please Let Me Know If You Require Further Details
Thank You
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
});

jquery dialog external page events are not firing

I open an html page using jquery dialog.
var url = "Popup.htm";
$('<div id=DialogDiv>').dialog({
dialogClass: 'DynamicDialogStyle',
modal: true,
open: function () {
$(this).load(url);
},
close: function (e) {
$(this).empty();
$(this).dialog('destroy');
},
height: 350,
width: 540,
title: 'Lookup'
});
The above code opens Popup.htm in a modal dialog.The Popup.htm has got a button but the click event is not firing.Please help.
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.22/jquery-ui.min.js"></script>
<title>PopUpView</title>
<script type="text/javascript">
$(function () {
$("#btnSearch").click(function () {
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://localhost:3340/Service1.svc/FetchAllCompany",
dataType: "json",
success: function (data) {
alert('ok');
var div = $("#test").empty();
$(data.d).each(function (index, item) {
div.append(
$("<tr>").append($("<td>").html(item.COMP_CODE))
.append($("<td>").html(item.COMP_NAME))
.append($("<td>").html(item.COMP_FRZ_FLAG)));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
});
})
</script>
<body>
<div id="MainContentDiv">
<label>Search</label>
<input />
<button id="btnSearch">...</button>
<div>
<table id="test">
</table>
</div>
</div>
The click event for btnSearch is not firing

Categories

Resources