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);
}
Related
I am trying to pass the model from view to controller using ajax AND when I check the value in the JS debugger model has data but it's not binding with controller and the controller model is showing null.
function BulkUpdate()
{
debugger;
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'GET', //GET
data: JSON.stringify({model}),
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
//and my controller code is
public ActionResult BulkUpdate(List<Tag> tags)
{
ModelAccessor obj1 = new ModelAccessor();
obj1.updatedDatas = new List<UpdatedData>();
foreach (var item in tags)
{
var tag = db.Tags.Where(x => x.Id.Equals(item.Id)).FirstOrDefault();
if (tag.TagValue != item.TagValue)
{
UpdatedData changedRow = new UpdatedData {
OldTagValue=tag.TagValue,
NewTagValue=item.TagValue.Trim()
};
obj1.updatedDatas.Add(changedRow);
}
}
return PartialView("_UpdateConfirmationBulk", obj1);
}
I have a solution.
function BulkUpdate()
{
debugger;
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'GET', //GET
data: {'tags':JSON.stringify({model})},
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
Try this because your method expects a parameter named tags and this is missing in you ajax call.
Can you try the type by post?
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'POST', //GET
data: JSON.stringify({model}),
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
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;
}
});
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());
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);
},
});
});
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