How can I call a C# method using jQuery? - c#

I want a C# code behind to be run every second. After googling, I wrote these codes:
<script type="text/javascript">
var myVar = setInterval(function () { start() }, 1000);
function start() {
time2 = 5;
//alert("Hello");
$.ajax({
type: "POST",
url: "WebForm1.aspx/refresh",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Hello");
},
failure: function () {
alert("Error");
}
});
}
</script>
And the code behind is:
[System.Web.Services.WebMethod]
public static void refresh()
{
//some code
}
But nothing happens. What's wrong?
UPDATE: I installed Firebug and observed that it is reporting "500 Internal Server Error". What does it mean ?

Everything looks good. But i assume you are not calling the JavaScript function.
<script type="text/javascript">
var myVar = setInterval(function () { start() }, 1000);
function start() {
alert('hi');
time2 = 5;
//alert("Hello");
$.ajax({
type: "POST",
url: "default.aspx/refresh",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Hello");
},
failure: function () {
alert("Error");
}
});
}
myVar; //------------------> Call the function
</script>
just call the function by calling myVar;

Related

ASP.net MVC unable to get value back from Controller

in my ASP.net MVC application, I have a button that call a controller action which takes longer (>60 mins) to complete. To keep my session alive I am using setInterval function.
reference: http://www.dotnetcurry.com/ShowArticle.aspx?ID=453&AspxAutoDetectCookieSupport=1
view looks like:
#Html.DevExpress().Button(settings =>
{
settings.Name = "LoadData";
settings.Text = "Load Data";
settings.ClientSideEvents.Click = string.Format("function(s, e) {{ OnButtonClick(s, e, '{0}', '{1}'); }}", Url.Action("Start", "ImportData", null), Url.Action("alive", "ImportData", null));
settings.UseSubmitBehavior = false;
}).GetHtml()
my OnButtonClick Function looks:
function OnButtonClick(s, e, startUrl, progressUrl) {
//debugger;
StartActionOnServer(startUrl);
setInterval(keepalive, 600000); //every 10 minutes.
}
Keep Alive looks like:
function keepalive()
{
console.log("I am alive");
$.ajax({
type: 'POST',
url: '/ImportData/alive',
dataType: "text",
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (msg) {
debugger;
console.log("pinging");
},
Error: function (xhr) {
debugger;
alert(xhr)
},
});
}
my issue is that code is not hitting my Controller function, as result I never get result back in my success block.
success: function (msg) {
debugger;
console.log("pinging");
},
Controller action function:
[HttpPost]
public ActionResult alive()
{
var result = "Still Alive";
return Content(result);
}
Instead of me hardcoding: console.log("I am alive"); I would like Controller to return this.
my console.log looks like attached screeshot
Any idea how to get value from Controller ?What am I doing wrong here.
Thanks.
This solved my issue:
function keepalive()
{
console.log("I am alive");
$.ajax({
type: 'POST',
url: '/ImportData/alive',
dataType: "text",
contentType: "text",
success: function (msg) {
console.log(msg);
},
Error: function (xhr) {
alert(xhr)
},
});
}

JQuery button is not triggering service call via ajax

I have a JSON service and i am trying to execute this service via ajax call through jquery in webpage. When i have created button and trying to execute click event but i am not able to get any alert message as well as service call also not triggering that means click event itself is not firing at all . please help!
below is code
<title></title>
<script src="JavaScript.js"></script>
<script type="text/javascript">
$(document).ready(function () { });
$('#buttonnew').click(function () {
alert("Hi");
$.ajax({
url: 'service2.svc/GetRestriction',
method: 'post',
contentType: 'application/json',
data: ({ property: '99883', code: 1 }),
dataType: 'json',
success: function (DATA) {
alert("hi");
},
error: function (err) {
alert(err);
}
});
});
</script>
You need to wire up the click event when the DOM has been loaded.
$(document).ready(function(e) {
$('#buttonnew').click(function () {
alert("Hi");
$.ajax({
url: 'service2.svc/GetRestriction',
method: 'post',
contentType: 'application/json',
data: ({ property: '99883', code: 1 }),
dataType: 'json',
success: function (DATA) {
alert("hi");
},
error: function (err) {
alert(err);
}
});
});
});
I think the only error you have in your code is that you are asigning tht click event on the button before document is ready. So you can just Try this :
<title></title>
<script src="JavaScript.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#buttonnew').click(function () {
alert("Hi");
$.ajax({
url: 'service2.svc/GetRestriction',
method: 'post',
contentType: 'application/json',
data: ({ property: '99883', code: 1 }),
dataType: 'json',
success: function (DATA) {
alert("hi");
},
error: function (err) {
alert(err);
}
});
});
});
</script>
I've tested it with Jquery 2.2.2.
I hope it helps !

JSON data html parameter

why JSON doesn't work with html text (var text_html = '<p></p><t></t>'; ) but this will be work correct (var text_html = 'example';)
doesn't work
var text_html = JSON.parse('<p></p><t></t>');
Problem:
function Save() {
var text_html = '<p></p><t></t>';
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
My_Text: text_html
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
public JsonResult DodajTematSave(string My_Text)
{
return Json(new { Success = true});
}
also this doesn`t work
var dom_string = '<div>xxx<div>yyy</div></div>';
var text_html = dom_string.innerText();
also this doesn`t work
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
try this:
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
and use ajaxSetup to instruct JQuery how to handle the data type
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Because those are escaping characters in JSON. You will have to parse html in a way to make it JSON friendly if you wanted it passed through JSON.
For this people who have problem with this I can show another way to fix this problem but very ugly click here

How to make javascript execute after using jQuery to dynamically load user control to div?

I have a Web User Control with javascript and css blocks. I'm using jQuery to dynamically load it into the main page. How do I make the alert('haha') to execute when the user control is loaded into the div called "divTable"?
In my .ascx file, I have
<script type="text/javascript">
function pageLoad(sender, args) {
alert('haha');
}
</script>
In the .aspx file, I have
<script type="text/javascript">
$(function () {
$('button').click(GetTable);
});
function GetTable() {
debugger;
var id_1 = $('#txtID1').val();
var id_2 = $('#txtID2').val();
$.ajax({
url: 'Services/Data.svc/RenderUC',
data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger;
$('#divTable').html(data);
},
error: function showError(xhr, status, exc) {
debugger;
alert('error');
}
});
}
</script>
In the .svc file, I have
[OperationContract]
public string RenderUC(string path, string id1, string id2)
{
Page pageHolder = new Page();
var viewControl = (ParameterizedTableControl)pageHolder.LoadControl(path);
viewControl.ID1= id1
viewControl.ID2 = id2;
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, true);
return output.ToString();
}
Any javascript that you want to run once the ajax operation is complete should go in the success handler.
function GetTable() {
debugger;
var id_1 = $('#txtID1').val();
var id_2 = $('#txtID2').val();
$.ajax({
url: 'Services/Data.svc/RenderUC',
data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger;
$('#divTable').html(data);
//
// insert whatever you want here
//
},
error: function showError(xhr, status, exc) {
debugger;
alert('error');
}
});
}
You can call your function inside your <script> block in the ascx control like this:
<script type="text/javascript">
function pageLoad(sender, args) {
alert('haha');
}
pageLoad();
</script>
This will make your script run when the browser renders your script tag.

Target the same control that initiated a jQuery AJAX POST on postback

function pageLoad() {
$(".VoteUp").live("click", function () {
var Id = $(this).attr("index");
d = JSON.stringify({ "Id": Id })
$.ajax({
type: 'POST',
url: '../API/Services.asmx/LikeId',
data: d,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: testFunc,
error: errFunc
});
$(".VoteUp").each(function () {
$(this).attr("disabled", "disabled");
});
});
function testFunc(result, userContext, methodName) {
if (result.d[0] == "true") {
TheVoteUpControl.val("added");
}
else {
TheVoteUpControl.val("deleted");
}
$(".VoteUp").each(function () {
$(this).removeAttr("disabled");
});
}
function errFunc() {
alert('error');
}
How can I change the value of that same .VoteUp control on success? I can't seem to figure out how to target that same control who initiated the event. $(".VoteUp")
Suggestions?
the only way i can think of is cache the element in the global variable and catch it in the success callback. also i have moved the enabling and disabling of the $(".VoteUp") in the complete and beforeSend callbacks respectively
$(".VoteUp").live("click", function (e) {
e.preventDefault();
$this=$(this); <-- cache this in the global variable
var Id = $(this).attr("index");
d = JSON.stringify({ "Id": Id })
$.ajax({
beforeSend:function(){
$(".VoteUp").attr("disabled", "disabled");
},
type: 'POST',
url: '../API/Services.asmx/LikeId',
data: d,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: testFunc,
error: errFunc
complete:function(){
$(".VoteUp").removeAttr("disabled");
}
});
});
function testFunc(result, userContext, methodName) {
if (result.d[0] == "true") {
$this.val("added");
}
else {
$this.val("deleted");
}
}

Categories

Resources