How to set false to ASP Button if Ajax result is success? - javascript

I am calling Ajax when user click the button. When calling ajax it will check the data with textbox whether the textbox value is already exist or not. If exist, then it should not return false, if the record is not found in database, jquery button should return true let it to save on database through server side.
Note:
My Ajax code is working. But when I the is exist and set return false this statement is not execute.
Here is my code:
$('#btnSaveFile').click(function () {
var fileNames = $('#txtFileName').val();
var flags = 'test';
alert('test='+flags);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'post',
async:false,
contentType: 'application/json',
data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
dataType: 'json',
success: function (data) {
if (data.d === 'dataExist') {
// it execute this loop, but after it execute it's going to server
$('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
return false;
}
else {
return true;
}
},
error: function (error) {
alert('Please Call Administrator');
}
});
});

I found result myself.
Ajax is an Asynchronous. We cannot do return false when the result is success.
So I declare one variable outside of ajax and with the certain condition in success I set return false in outside of ajax code
This is my Jquery code
$('#btnSaveFile').click(function () {
var fileNames = $('#txtFileName').val();
var flag = 'returnTrue';
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'post',
async: false,
contentType: 'application/json',
data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
dataType: 'json',
success: function (data) {
if (data.d === 'dataExist') {
flag = 'returnFalse';
$('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
}
else {
alert('else');
return true;
}
},
error: function (error) {
alert('Please Call Administrator');
}
});
if (flag === 'returnFalse') {
return false;
}
});

Related

Ajax. On Ajax success call same ajax function one more time

This is what i tried.
tjq.ajax({
type: 'POST',
url: '<?php echo base_url();?>getCmsHotel?t=<?php echo $traceId;?>',
dataType: 'JSON',
encoding:"UTF-8",
contentType: "application/json",
traditional: true,
async: true,
error: function (request, error) {
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
return false;
},
success: function (data) {
//alert(data.status);
if(data.status == 'FAILURE'){
//searchresults = data;
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
return false;
}else if(data.status == 'SUCCESS'){
var recalajx = '2';
if(recalajx =='2' && recalajx!=3){
recalajx ='3';
tjq.ajax(this);
}
alert(recalajx);
tjq('.searchresultsDiv').remove();
hotelsresults = data;
//hotelssearchObj.hotelsResults(data);
gblStartCount = 1;
gblHotelData = tjq.extend(true, {}, data);
gblHotelDisplayData = tjq.extend(true, {}, data);
hotelssearchObj.hotelsResults(gblHotelDisplayData);
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
tjq("div#divLoading").removeClass('show');
}
}
});
This code calling multiple times. Am trying to call tjq.ajax(this); only once after 1st ajax SUCCESS.
when tried to alert getting 3 but still axaj calling for multi times.
How to stop this can some help!
One solution is to put the Ajax call in a function, and check how many times it has been called with a counter. If the counter is less than 2, call the function again.
here's an example:
ajaxCall();
function ajaxCall(counter = 0) {
$.ajax({
type: 'POST',
success: function() {
counter++
if (counter < 2) {
ajaxCall(counter);
}
}
});
}

How can a guarantee one ajax call is complete before calling another?

I am working on a flask application and there is this javascript function associated with a form
function applyQueries() {
// does some things
if(currentCatalog != ''){
addCatalogFilters(currentCatalog);
}
$.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
})
}
The addCatalogFilters() function is also an ajax call. Both these calls change some variables in the python side of things. What I want to know is if the first ajax call (in addCatalogFilters), is guaranteed to execute and return before the second one. I am ending up with weird results that appear to be race conditions based on the order the ajax calls execute. Is this possible with code structured like this? Also if so, how can I fix it?
// Add user catalog filters
function addCatalogFilters() {
catalog = currentCatalog;
formData = new FormData(document.getElementById('catalogFilterForm'));
$.ajax({
type: 'POST',
url: "/addCatalogFilters",
data: formData,
processData: false,
contentType: false,
success: function (response){
document.getElementById(catalog + 'close').style.display = 'block';
document.getElementById(catalog + 'check').style.display = 'none';
addBtns = document.getElementsByClassName("addBtn");
removeBtns = document.getElementsByClassName("removeBtn");
for (i = 0; i < addBtns.length; i++) {
addBtns[i].style.display = "none";
removeBtns[i].style.display = "inline-block";
}
}
})
};
You can ensure with success function of ajax. First call a ajax (let's say ajax1) then call another ajax call within the success function of first ajax call (ajax1 success function).
addCatalogFilters(currentCatalog)
{
$.ajax({
type: 'POST',
url: "/the-post-usl",
success:function(response){
$.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
});
})
}
function applyQueries() {
// does some things
if(currentCatalog != ''){
addCatalogFilters(currentCatalog);
}
}
It may not be the optimum way. But guarantee one ajax call is complete before calling another.
You could try using async/await like this:
async function applyQueries() {
if(currentCatalog !== ''){
const filtersAdded = await addCatalogFilters(currentCatalog);
}
// Perform AJAX call
}
By usinc async/await, your code will wait until the addCatalogFilters() function has resolved. However, for this to work, the addCatalogFilters() function should be async with a return value. Something like this:
async function addCatalogFilters(catalog){
// Ajax call
$.ajax({
type: 'POST',
url: "foo",
contentType: "application/json",
success:function(response){
return true
})
}
Depending on how applyQueries is called, you may need to have an await or .then where you call it. Note that you can also use "result = await addCatalogFilters(currentCatalog)" to put the ajax result into a variable result that you can work with and pass to your $.ajax call in applyQueries. I don't know the nature of your code, so I can't make any direct suggestions.
async function applyQueries() {
// does some things
if(currentCatalog != ''){
// await on the returned Promise-like jqXHR (wait for ajax request to finish)
// recommend assigning awaited result to a variable and passing to next $.ajax
await addCatalogFilters(currentCatalog);
}
return $.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
})
}
// Add user catalog filters
function addCatalogFilters() {
catalog = currentCatalog;
formData = new FormData(document.getElementById('catalogFilterForm'));
// return the Promise-like jqXHR object: https://api.jquery.com/jQuery.ajax/#jqXHR
return $.ajax({
type: 'POST',
url: "/addCatalogFilters",
data: formData,
processData: false,
contentType: false,
success: function (response){
document.getElementById(catalog + 'close').style.display = 'block';
document.getElementById(catalog + 'check').style.display = 'none';
addBtns = document.getElementsByClassName("addBtn");
removeBtns = document.getElementsByClassName("removeBtn");
for (i = 0; i < addBtns.length; i++) {
addBtns[i].style.display = "none";
removeBtns[i].style.display = "inline-block";
}
}
})
};
You can use async/await. However, as no one has mentioned, I would like to demonstrate how you can accomplish this with Promise.
Lets define two functions:
function first_function(data) {
return new Promise((resolve, reject) => {
let dataSet = [[]];
let response;
$.ajax({
type: "POST",
url: 'example.com/xyz',
async: false,
data: data,
success: function (value) {
response = value;
dataSet = JSON.parse(response);
resolve(dataSet)
},
error: function (error) {
reject(error)
},
processData: false,
contentType: false
});
})
}
function second_function(data) {
return new Promise((resolve, reject) => {
let dataSet = [[]];
let response;
$.ajax({
type: "POST",
url: 'example.com/abc',
async: false,
data: data,
success: function (value) {
response = value;
dataSet = JSON.parse(response);
resolve(dataSet)
},
error: function (error) {
reject(error)
},
processData: false,
contentType: false
});
})
}
Now you can make sure that second_function() gets called only after the execution of ajax request in first_function() by following approach:
first_function(data)
.then(dataSet => {
//do other things
second_function(dataSet)
.then(dataSet2 => {
////do whatever you like with dataSet2
})
.catch(error => {
console.log(error);
});
});

Returning Bool to AJAX request

This must be a really simple answer, but i cannot see where I am going wrong.
Just typing a test AJAX request with c# code behind. I cannot get the c# to return a true/false statement, or I cannot get the AJAX to recognise it as true/false.
[WebMethod]
public static bool testme(int testnumber)
{
if (testnumber < 12)
{
return true; }
else
{
return false;
}
}
AJAX:
<script>
$(document).ready(function () {
$('#test').click(function () {
$.ajax({
type: "post",
url: "WebForm1/testme",
data: { testnumber: 13 },
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
if (data) {
console.log("true");
}
else {
console.log("false");
}
},
Error:function(error){
console.log("error");
}
});
});
})
</script>
Button:
<input type="button" id="test" value="click me"/>
The console.log is showing true, even though the number I am entering is greater than 12, which should return the "false" bool from the c# method.
your if(data) check is checking truthiness, data is going to be an object, so look at it's properties and you can find C#'s result.
If you're unfamiliar with JS truthiness, look it up for a better description: but each variable is considered to be truthy if it has a valid value, if it's null or undefined (or 0 or '') then it will not be considered truthy and will fail a boolean check.
When you get a response from a WebMethod like this you have to use a .d to reference the value. Your current code simply checks to see if you got a response, and most likely always evaluates to true.
<script>
$(document).ready(function () {
$('#test').click(function () {
$.ajax({
type: "post",
url: "WebForm1/testme",
data: { testnumber: 13 },
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
if (data.d) {
console.log("true");
}
else {
console.log("false");
}
},
Error:function(error){
console.log("error");
}
});
});
})
</script>
One pointer as well that can help you figure out what is going on would be to use the network tab of you browsers developer tools (F-12) to see the response format that is coming back from the server. It isn't just returning true or false it is returning d: true or d: false thus the change I mentioned.
Whenever I have to use Ajax, I return from the function JSON object.
For e.g:
return Json(new { result = true });
and in AJAX:
<script>
$(document).ready(function () {
$('#test').click(function () {
$.ajax({
type: "post",
url: "WebForm1/testme",
data: { testnumber: 13 },
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
if (data.result === true) {
console.log("true");
}
else {
console.log("false");
}
},
Error:function(error){
console.log("error");
}
});
});
})
</script>
So it turns out it was relativly simple, but not sure why it needs to be done. I got help from https://forums.asp.net/t/2023743.aspx?Ajax+Webmethod+not+firing+
I needed to change
//settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
to my RouteConfig.cs and then everything worked fine.
If anyone knows why this isn't automatically changed when you add the System.Web.Services; or what this means i would love to know, anyway, all working great now.

how to stop ajax request if another request exist

i'm trying to make infinite scrolling so when scrolling i make an ajax request to the server to get data but when scrolling a multiple ajax request is made and return the same data so how can i cancel ajax request before sending if there one already exist i tried like this
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
all my code
var lock_load = '1';
var activeAjaxConnections = 1;
var PageNumber = 2;
$(window).scroll(function () {
if ((Math.ceil($(window).scrollTop() - $(window).height()) * -1) <= getHeight() + 550) {
if (lock_load === '1') {
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
alert(errorThrown);
n }
});
}
}
});
but it give an error xhr is undefined pleas any help and many thanks in advance.
Try flags
Before making ajax call set flag to true and after ajax call is made set flag to false, finally on completion of ajax request again set flag to ture
var ready = true;
$(window).scroll(function(){
if(ready == true){
ready = false;
$.ajax({
url: "/pagination",
cache: false,
success: function (response){
//response
}
}).always(function () {
ready = true; //Reset the flag here
});
}
});
use the below code, use a simple flag variable that will be set to false by the defualt, that is to say that ajax call is not occuring once if condition is met then it will set to true to say that ajax call has started, once the success: or error: call back fires the variable will be set to false so that another ajax call can be made.
startedAjax = false;
if (lock_load === '1') {
startedAjax = true;
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
startedAjax = false //set is false
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
startedAjax = false;
alert(errorThrown);
}
});
}
}
});

How to return value in ajax call?

I want after keyup in input if data was 0 return is false if was not false return is true. but in my try always return is true in case data === 0:
$('input').live('keyup change', function () {
var result = true;
$.ajax({
type: 'POST',
dataType: 'json',
url: 'search_customer',
data: dataObj,
cache: false,
success: function (data) {
if (data == 0) {
alert('data is 0')
result = false;
} else {
alert('data is not 0')
}
}
})
//alert(result) this output always is 'true'
return result;
})
The .ajax() call returns at an arbitrary time in the future. The keyup and change handlers return (essentially) immediately.
Do the work in your success handler. Alternatively, you could set a global (or namespaced global) to the returned value, with the understanding that it would be invalid until the Ajax call completes.
You also need to make sure the data being returned is what you expect it to be, if the if statement itself isn't doing what you expect. That's a different issue than the return value from the event handler.
I see that you've selected async: false as your answer, but there is a better way - using a callback function.
$('input').live('keyup change', function () {
DoSomething(function(result) {
// this isn't blocking
});
})
function DoSomething(callback) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'search_customer',
data: dataObj,
cache: false,
success: function (data) {
var result = data !== 0;
if (typeof callback === 'function') {
callback(result);
}
}
});
}

Categories

Resources