I am calling live('click') function in which i call ajax method and do some server side functionality.
But before ajax call i need to check for valid data.
Am bit confused how to call it
// Depend on this condition i have to start process my ajax function.
function validData()
{
if ($('.edt').val() == "")
{
return false;
}
var maxtxtvalue = $('edt3').val();
var mintxtvalue = $('edt4').val();
// alert(maxtxtvalue > mintxtvalue);
if(parseInt(maxtxtvalue) > parseInt(mintxtvalue))
{
return true;
}
else
{
$('input:text[id$="txtmaxctc"]').val('');
$('input:text[id$="txtminctc"]').val('');
alert("Max ctc must be greater then Min ctc.");
return false;
}
}
$("img[class^='sav_']").live('click', function (event) {
if( return false )
{
}
else{
//start process
$.ajax({
type: "POST",
url: "ajax_function/updatefn.asmx/upajx",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
} });
}
});
// Depend on this condition i have to start process my ajax function.
can't you do like this..
function validData()
{
if ($('.edt').val() == "")
{
return false;
}
var maxtxtvalue = $('edt3').val();
var mintxtvalue = $('edt4').val();
// alert(maxtxtvalue > mintxtvalue);
if(parseInt(maxtxtvalue) > parseInt(mintxtvalue))
{
return true;
}
else
{
$('input:text[id$="txtmaxctc"]').val('');
$('input:text[id$="txtminctc"]').val('');
alert("Max ctc must be greater then Min ctc.");
return false;
}
}
$("img[class^='sav_']").live('click', function (event) {
if(validData() )
{
}
else{
//start process
$.ajax({
type: "POST",
url: "ajax_function/updatefn.asmx/upajx",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
} });
}
});
Related
The below method returns 401 error on server. As I don't see any errors in this. Please suggest why its coming as 401 error
function loadSPANByMZ() {
try {
showLoading();
var OperationType = "";
if (R4GStateSelected != "Select") {
if ($(mzoneid).val() != "Select") {
if ($(activitytypeid).val() != "Select") {
//call CurrentGroupName UMS variable
var UserType = CurrentGroupName;
var SpanType = $(spantypeid + ' option:selected').val().toUpperCase();
var MZone = $(mzoneid + ' option:selected').val();
OperationType = $(activitytypeid + ' option:selected').val();
var Values = { "USERTYPE": UserType, "SPANTYPE": SpanType, "MZONE": MZone, "OPERATIONTYPE": OperationType.toUpperCase() };
//$(gridSpanlisttable).empty();
$.ajax({
type: "POST",
url: AppConfig.PrefixURL + "App/GetSPANList",
data: JSON.stringify(Values),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
displaySpanList(response, SpanType, MZone, OperationType);
//hideLoading();
},
error: function (response) {
hideLoading();
$(dataContent).hide();
},
complete : function(response)
{
hideLoading();
}
});
}
}
}
//},
}
catch (e) {
hideLoading();
$(dataContent).show();
}
}
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);
}
}
});
}
I have a javascript function that is executed onClick via jquery. Within this function I am calling a Web Service "getTestConnection" which returns a True or False and I have confirmed it is working but keeps returning variable undefined.
$("#btnNext2").click(function() {
var postData = {}; {
postData['user'] = user;
postData['password'] = password;
postData['serviceurl'] = serviceurl;
postData['datasource'] = datasource;
};
//Converts object to string and formats to JSON
var json = JSON.stringify(postData);
//connTest keeps getting returned as 'Undefined'
var connTest = getTestConnection(json);
});
< script type = "text/javascript" >
function getDocType(json, rowcount) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/GetDocTypes",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//*****************************************************************************
//This is being called immediately after getTestConnection is executed
//******************************************************************************
for (i = 0; i < data.d.length; i++) {
$('#SelectDocType' + rowcount + '')
.append($("<option></option>")
.attr("value", data.d[i].docTypeID)
.text(data.d[i].docTypeName));
}
var firstDocTypeID = data.d[0].docTypeID;
var jsonUnstringify = JSON.parse(json);
var postDataNew = {}; {
postDataNew['user'] = jsonUnstringify.user;
postDataNew['password'] = jsonUnstringify.password;
postDataNew['serviceurl'] = jsonUnstringify.serviceurl;
postDataNew['datasource'] = jsonUnstringify.datasource;
postDataNew['docTypeID'] = firstDocTypeID;
};
var jsonnew = JSON.stringify(postDataNew);
getKeywords(jsonnew, rowcount);
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
//Test Connection Web Service
function getTestConnection(json) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/TestConnection",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
}
< /script>
You have multiples errors:
You have a <script type = "text/javascript"> tag inside another <script> tag
You define a new function inside another function:
function getDocType(json, rowcount) {
$.ajax({
.....
});
function getTestConnection(json) {
....
}
}
which should be
function getDocType(json, rowcount) {
$.ajax({
.....
});
}
function getTestConnection(json) {
....
}
You forgot to get returned data from the AJAX call in your getTestConnection function :
$.ajax({
type: "POST",
url: "http://localhost...",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
....
}
});
Here's my code:
First the execution of the program comes here:
refreshTree(function() {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh();
}
});
});
Here's the definition of refreshTree():
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
if (data == 'True') {
isOk = false;
}
callback();
}
});
}
And here's the refresh() method:
function refresh() {
if (isOk) {
//do something
}
}
The problem is, I don't know how to get the isOk variable in refresh(). Is there some way to send the variable to refresh(), without it being a global variable?
You capture it in a closure here:
refreshTree(function(isOk) {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh(isOk);
}
});
});
And pass it in here:
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
if (data == 'True') {
isOk = false;
}
callback(isOk);
}
});
}
and here:
function refresh(isOk) {
if (isOk) {
//do something
}
}
Simply Pass it as parameter:
refreshTree(function(status) {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh(status);
}
});
});
refreshTree() function:
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
var isOk=true;
if (data == 'True') {
isOk = false;
}
callback(isOk);
}
});
}
Refresh() method:
function refresh(status) {
if (status) {
//do something
}
}
Here is the situation. I have an application in phonegap/jquerymobile. I want to change the page according to the json data.
When a user starts the app but the current version is not the latest version it needs to change content. This is a fragment of code from the start.html page.
<script type="text/javascript" charset="utf-8">
var versionValue = ServerSettings.versionCheck();
if(versionValue == true){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}
else{
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
</script>
The function ServerSettings.versionCheck() is below.
versionCheck : function() {
var localAppVersion = 0.8;
var response = false;
$.ajax({
async: false,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
if(localAppVersion == currentAppVersion){
response = true;
}
else{
response = false;
}
}
});
return response;
}
I have verified the response of the json call with a toast. It does get correct response.(version: 0.9) I am pretty sure i make the most dumbest mistake ever but i cannot seem to find it.
You are attempting to be synchronous, but the config parameter is evaluating to true because it's a string
async: "false"
Change it to async: false, but I'd recommend to switch to asynchronous to avoid blocking the UI.
Also your success callback doesn't return to the outer method, so you'll always get undefined.
versionCheck : function() {
var localAppVersion = 0.8;
var response = false;
$.ajax({
// WARNING: I don't recommend setting this to false in production code
// While the browser is waiting for the response the page/browser will not respond!!
async: false,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
response = localAppVersion == currentAppVersion;
}
});
return response;
}
To make it asynchronous (Recommended approach)
versionCheck : function(checkCompleteCallback) {
var localAppVersion = 0.8;
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
checkCompleteCallback(localAppVersion == currentAppVersion);
}
});
}
// Now the check accepts a callback function that executes when the request completes without blocking the UI
ServerSettings.versionCheck(function(versionValue) {
if(versionValue){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}
else {
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
});
It is due to you trying to access a value that has not been returned yet from the server as your are using asynchronus.
You could refactor you version check to take a callback argument like so.
<script type="text/javascript" charset="utf-8">
var localAppVersion = 0.8,
versionValue =false;
var versionValue = ServerSettings.versionCheck(function(jsonData){
var currentAppVersion = jsonData.version;
if(localAppVersion == currentAppVersion){
versionValue = true;
}
else{
versionValue = false;
}
if(versionValue == true){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}else{
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
});
versionCheck : function(callback) {
var localAppVersion = 0.8;
var response = false;
$.ajax({
async: "false",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: callback
});
}
Version check is an asynchronous call. So, it will not return true or false. Your versionValue will not be true or false. It is better use promises for asynchronous calls.
Change your versionCheck function like this
versionCheck : function() {
var localAppVersion = 0.8;
var response = false;
$.ajax({
async: "false",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
if(localAppVersion == currentAppVersion){
return true;
}
else{
return false;
}
}
}).done(function(){
if(versionValue == true){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}
else{
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
});
}
jQuery.promise is available in version > 1.6
Ajax works asynchronously, so when you do the check the response actually is not arrived yet. Put the logic that depends from that value inside the ajax callback.
versionCheck : function() {
var localAppVersion = 0.8;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://xxx/service/version.php",
success: function(jsonData) {
var currentAppVersion = jsonData.version;
if(localAppVersion == currentAppVersion){
$("#loginPage").removeClass("hidden");
$("#updatePage").addClass("hidden");
}
else {
$("#loginPage").addClass("hidden");
$("#updatePage").removeClass("hidden");
}
}
});
}