Why my text() function doesn't work in my script? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I write a script that call a method which return count of some data, and then change the text of a 'P' tag (by id=count) to returned value.
my script :
$(document).ready(function () {
$("#count").text(function () {
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetCountUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
return (response.d);
},
});
});
});
What is the problem?

If your response is a json,then you need to parse it like below.And if your response is not in json,you can directly assign value to .text(response)
$(document).ready(function () {
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetCountUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
var result=parseJSON(response)
$("#count").text(result.d)
},
});
});
});

You have a bug relating to how AJAX works - your function isn't returning anything. Your success callback is invoked after the function has returned because AJAX is asynchronous.
To make this work, you would have to start with the AJAX call, and then, in it success handler, set the text of the <p>:
$.ajax({
...
success: function (result) {
$("#count").text(result.d);
}
})

try:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetCountUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#count").text(response.d);
},
});
});

$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetCountUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
$("#count").val(response["id"]); // in case of input tag
$("#count").html(response["id"]); // in case of span/p/div
},
});

You need to set $("#count").text() in the success callback...
$(document).ready(function () {
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetCountUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
$("#count").text(response.d);
}
});
}

The $.ajax function doesn't return anything. Try something like this:
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetCountUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
$("#count").text(response.d);
},
});

It doesn't work because of the way asynchronous operations work. Basically you are telling $('#count').text() to immediately set the text to whatever the anonymous function returns. But that function will just return undefined after firing the ajax event. You must place the text call inside the final callback; which is not executed until later:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetCountUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
$("#count").text(response.d);
},
});
});

Related

Passing data with ajax and read it with Request.Form[""]

I try to pass parameters into aspx.cs page from js script. When I omit:
contentType: "application/json; charset=utf-8"
in ajax request I get by Request.Form["ORDER"] sth like {%7b%22ORDER_ID%22%3a126333%7d}. It means that this data comes to aspx.cs, but it is not decoded.
When I add contentType I get nothing in request.
Below I attach request.
It is important to read parameters from Request.Form["ORDER"] in aspx.cs;
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ORDER_ID: orderKeyId }),
dataType: "json",
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});
According to #Rory McCrossan comment, below ajax state worked:
$.ajax({
type: 'POST',
contentType: "application/x-www-form-urlencoded",
data: "ORDER_ID=" + encodeURIComponent(orderKeyId),
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});

reusable ajax and javascript function in CSHTML(RAZOR)

Im new in js and razor,part of my code should be repeated and this imposed more lines of code to my project,it could be nice if i can make it reusable,for example Ajax,where should i create a ajax to a specific URL to just call it when i need?in a separated razor file?in the following code,i have two click events and my ajax call and url is repeating,i want to get rid of this repeat:
function seriesClick(e) {
var _clicketBarChart = e.series.categoryField;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "name": _clicketBarChart }),
success: function (result) {
faultstatChart(result);
}
});
function changeEvent(e) {
var _clicketCellGrid = e.categoryCell;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"name": _clicketCellGrid }),
success: function (result) {
faultstatChart(result);
}
});
}
You have to create single method that can handle two situations, please refer to this example (based on your):
var ajaxHandler = function(targetName) {
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"name": _clicketCellGrid }),
success: function (result) {
faultstatChart(result);
}
});
}
var seriesClick = function(e) {
var targetName = e.series.categoryField;
ajaxHandler(targetName);
}
var changeEvent = function(e) {
var targetName = e.categoryCell;
ajaxHandler(targetName);
}

Ajax method to a webmethod in asmx is not firing

I have a strange problem with the below AJAX jQuery method to call a webmethod in an asmx service. It's not firing when I try to call it, but the moment I uncomment any of the alert in code to debug, it works all of sudden.
It confuses me, what would be the problem? Am I missing something here..
Code:
var endXsession = function() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msge) {
//alert(msge.d);
fwdURL = msge.d;
},
error: function(response) {
//alert(response.responseText);
fwdURL = response.responseText;
}
});
//alert(fwdURL);
return fwdURL;
};
response.responseText is undefined ... it's response.statusText ..
function endXsession() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msge) {
// alert(msge.d);
fwdURL = msge.d;
}
,
error: function (response) {
// alert(response.statusText);
fwdURL = response.statusText;
}
});
// alert(fwdURL);
return fwdURL;
}
console.log(endXsession());

How to get return value in a function with inside Ajax call - JQuery

this may sound very easy to few of you, but i am not able to figure out why I am not able to get the return value, even after chceking many posts :(
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
Now if I call var count = getMessageCount();
it gives me undefinted :(
while inside the method count is coming correct, i.e. service is working fine.
I agree with the first line by ahren that
'That's because the $.ajax() call is asynchronous.'
you could try adding a setting - async:false
which is true by default. This makes the call synchronous.
you can edit your code as :
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
That's because the $.ajax() call is asynchronous.
If you edit your code to something like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if(typeof callback === "function") callback(count);
} //success
});
}
Then when you call it:
getMessageCount(function(count){
console.log(count);
});
use a callback:
call function like:
getMessageCount(function(result) {
//result is what you put in the callback. Count in your case
});
and the other like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if (callback) {
callback(count);
}
} //success
});
}
Why you don't just pass it to a function?
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
countMessages(count);
} //success
});
}
function countMessages(counted) {var counted = counted; console.log(counted);}
function ajax_call(url,data){
return $.ajax({ type: "POST",
url: url,
data: data,
async:false,
success: function(status){
}
}).responseText;
}
Now you will get the response text from server side via ajax call

Can't access element inside success ajax

I'm putting an ajax call inside an ajax call, but in the second, the element is not being recognized, example:
$.ajax({
url: 'controleFatAcoes.php',
type: 'post',
dataType: 'html',
data: {
acao: 'validaenviofat',
id_cliente: cli.id_cliente,
dt_fat: cli.id_fat
},
success: function(data) {
$.ajax({
url: 'controleFatAcoes.php',
data: {id_cliente: cli.id_cliente,
id_fat: cli.id_fat, acao: 'getdadosnf'},
type: 'post',
dataType: 'json',
success: function(dados) {
**$('#templateEmpresa').html(dados.empresa);**
}
)};
});
When I run a console.log($('#templateEmpresa')), I get:
[context: document, selector: "#templateEmpresa", constructor: function, init: function, selector: ""…]
Try this code out:
Might be a problem of scope given that you are executing the second ajax call inside the success function of the first ajax call.
var firstajaxsuccess = 0;
$.ajax({
url: 'controleFatAcoes.php',
type: 'post',
dataType: 'html',
data: {
acao: 'validaenviofat',
id_cliente: cli.id_cliente,
dt_fat: cli.id_fat
},
success: function(data) {
firstajaxsuccess = 1;
}
});
if(firstajaxsuccess){
$.ajax({
url: 'controleFatAcoes.php',
data: {id_cliente: cli.id_cliente,
id_fat: cli.id_fat, acao: 'getdadosnf'},
type: 'post',
dataType: 'json',
success: function(dados) {
**$('#templateEmpresa').html(dados.empresa);**
}
)};
}

Categories

Resources