Cannot invoke ashx inside the function - javascript

I am having jquery code to invoke ashx file. Its perfectly working while page load. When i call the function from another function means not working.I have place the two codes here.
Please check and help me.
<script type="text/javascript">
$(document).ready(function () {
try {
$("#submit").click(function () {
var user = $("#login").val();
var pass = $("#password").val();
CallLoginHandler(user, pass);
}
}catch(ex){
}
</script>
<script type="text/javascript">
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.length > 0) {
alert(response[0]["FLD_ID"]);
//successCallback(response);
} else {
alert(response[0]["FLD_ID"]);
}
}
});
}
</script>

I think you are missing the proper jquery syntax . Try the following modified code :-
<script type="text/javascript">
$(document).ready(function () {
try {
$("#submit").click(function () {
var user = $("#login").val();
var pass = $("#password").val();
CallLoginHandler(user, pass);
});
} catch (ex) {
}
});
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.length > 0) {
alert(response[0]["FLD_ID"]);
//successCallback(response);
} else {
alert(response[0]["FLD_ID"]);
}
}
});
}
</script>

Related

Loading finishing before everything has loaded from multiple functions

I'm sure this is going to be something really simple, but I am having a problem when calling a function which needs to do various different function calls via ajax to a .net code behind and I want to show a loader over the page until everything has finished, but its not happening.
function expand(ID, user) {
$('.loadingBlackSml, .loadingSml').fadeIn(1000);
checkSession();
expand2(ID, user);
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
Which calls
function checkSession() {
return $.ajax({
type: "POST",
url: "/Test.aspx/checkForSession",
//data: "{}",
data: "{'idleTime':'" + clickedDT + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (sessionCheck) {
sessionActive = JSON.stringify(sessionCheck.d);
}
}).done(function () {
//if session comes back as dead, redirect to restart session
if (sessionActive == "\"false\"") {
var url = "/Error.aspx?RefreshNeeded=true&page=" + window.location.pathname;
$(location).attr('href', url);
}
//if page has gone past timeout length, try and reload it
else if (sessionActive == "\"timeout\"") {
var urlTO = window.location.pathname;
$(location).attr('href', urlTO);
}
});
}
and
function expand2(ID, user) {
return $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/Test.aspx/markExpanded',
data: "{'ID':'" + ID + "', 'user':'" + user + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
}).done(function () {
});
}
But the loading overlays are disappearing before it is finishing doing what its doing? I've seen something about using $.when for my calls but I'm not sure how to get this working properly?
Any advice would be great. Thanks
Try to hide loading in expand2 or checkSession function on finish request. Like this
... .done(function () {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
});
So loader will be hidden after everything will have finished.
To be sure that everything is over, you can set "flag". For example check = 2. And do
check--; check||$('.loadingBlackSml, .loadingSml').fadeOut(1000);
edited 10.04.17
Example with flag (check) for requests
var check = 0; // count pending requests
function expand(ID, user) {
$('.loadingBlackSml, .loadingSml').fadeIn(1000);
count = 2;
checkSession();
expand2(ID, user);
}
function checkSession() {
return $.ajax({
type: "POST",
url: "/Test.aspx/checkForSession",
//data: "{}",
data: "{'idleTime':'" + clickedDT + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (sessionCheck) {
sessionActive = JSON.stringify(sessionCheck.d);
}
}).done(function () {
//if session comes back as dead, redirect to restart session
if (sessionActive == "\"false\"") {
var url = "/Error.aspx?RefreshNeeded=true&page=" + window.location.pathname;
$(location).attr('href', url);
}
//if page has gone past timeout length, try and reload it
else if (sessionActive == "\"timeout\"") {
var urlTO = window.location.pathname;
$(location).attr('href', urlTO);
}
count--;
if (count === 0) { // check. are all requests finished
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
});
}
function expand2(ID, user) {
return $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/Test.aspx/markExpanded',
data: "{'ID':'" + ID + "', 'user':'" + user + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
}).done(function () {
count--;
if (count === 0) {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
});
}
Of course, you can move
count--;
if (count === 0) {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
to separate function

How to change url of ajax function depending the return value of beforesend() function?

I want to run a function inside beforesend() in jquery ajax. Depending on the return value of that function I want to change the URL of ajax request. For an example refer below.
If myFunction() returns a value grater than 1, I want to run url1 otherwise I want to run url2. How to achieve that?
myFunction() gives a value grater than 1. But always ajax runs the url2.
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
myFunction($('#com').val())
},
url: (myFunction($('#com').val()) > 1) ? url1 : url2,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
try this
$.ajaxSetup({
beforeSend: function(jqXHR, settings) {
settings.url ="new Url";
}
});
Create a global variable something like:
var urlToSend;
and then assign it in beforeSend
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
urlToSend=myFunction($('#com').val()) > 1 ? url1 : url2;
},
url: urlToSend,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
url = myFunction(parseInt($('#com').val())) > 1 ? url1 : url2;
},
url: url,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});

How to work with jQuery UI auto-complete extender for text searching

I'm working with jQuery UI Auto Complete extenders for populating list.
Here i include this article for more reference of my code detail.
Here I modify method for auto complete. In article this calls from css class and I want from the ID of the control.
This is my jQuery script :
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#<%=txt_reason.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Raise_Ticket.aspx/SearchReasons",
data: "{'prefixText':'" + $("#<%=txt_reason.ClientID %>").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
And this is my method:
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
[System.Web.Services.WebMethod]
public static List<string> SearchReasons(string prefixText)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = db.Reasons.Where(r => r.ReasonText.Contains(prefixText)).Select(r => r).ToList();
List<string> reasons = new List<string>();
foreach (var item in query)
{
reasons.Add(item.ReasonText.ToString());
}
return reasons;
}
}
The problem is not detecting this textbox not displaying result.
Use this
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#txt_reason").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Raise_Ticket.aspx/SearchReasons",
data: "{'prefixText':'" + $("#txt_reason").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
Using this you can also try
$(document).ready(function () {
$("#textbox").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (retrieveddata) {
if (retrieveddata.length > 0) {
}
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
Take Tern Variable in Code

Ajax doesn't execute success function

My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});

Load up javascript files after ajax call

Hi how do i go about loading up my javascript files after an ajax call has been made, reason being it seems once i click submit, some javascript functions do not end up working. I tried using "$getscript" however it was a bit buggy especially in google chrome? This is what my call looks like;
function InsertStatus() {
var fStatus1 = document.getElementById('<%=txtStatus.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebServices/UserList.asmx/InsertUserStatus",
data: "{ 'fStatus': '" + fStatus1 + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d == "Successful") {
$("#col-3").load(location.href + " #col-3>*", "");
$.getScript('scripts/script.js', function () {
});
}
else {
alert("its false");
$.getScript('scripts/script.js', function () {
});
}
}
});
};
Replace $.getScript('scripts/script.js', function () {});
With:
$.ajax({
dataType: 'script',
url: 'scripts/script.js',
crossDomain:true,
success: function(response)
{
//Whatever
}
});

Categories