jQuery ajax call doesn't seem to do anything at all - c#

I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`

Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }

if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.

Related

Adding a script to a page on exit using Ajax. The script loads, but doesn't work through the ajax method?

When the users try to exit the page, I want to load a new script into my page.
The script successfully gets adding to the page, but it simply doesn't work properly. Now, if I just put the script into my page from the get-go, not using ajax, it does work. To me, this makes absolutely no sense, but something in my method/jQuery is clearly screwing the script up.
Lines from the JS file which Ajax doesn't seem to like:
document.write('<div id="' + token + '"></div>');
that.div.style.position = 'relative';
Error includes
Uncaught TypeError: Cannot read property 'style' of null
I'm assuming it's related to the script not being loaded onload? :S
This is my code
My Web Method.
[WebMethod]
public string webcamLink(string cat)
{
string script = "<script src=\"thescipt.js\"></script>";
return script;
}
This is my jQuery.
setTimeout(() => {
$(document).on("mouseout", evt => {
if (evt.toElement === null && evt.relatedTarget === null) {
$(evt.currentTarget).off("mouseout");
// An intent to exit has happened
$("#myNav").css("display", "block");
var cat = "cat";
var t = JSON.stringify({
'cat': cat
});
$.ajax({
type: "POST",
url: '/webServices/pop-up.asmx/webcamLink',
data: t,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError,
timeout: 15000,
async: true
});
}
});
}, 5000);
function OnSuccess(data) {
$('#cams').html(data.d);
};
And my HTML:
<div id="cams" class="container-fluid"></div>
Does anybody have any idea what I'm doing wrong? I apologise if I'm being silly, quite new to this.

How to call or is it possible to call WebMethod that is in the master page in asp.net c#

Lets say,
I have MasterPage which has a function in the .Master file.
function ajaxer65612282013() {
var data = "";
jQuery.ajax({
url: 'UserMaster.Master/ay_scl',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#msd").html((data.d));
},
error: function (result) {
console.log(result.responseText);
}
});
}
now in the code behind file of the master page i have a function like below
[WebMethod]
public static string ay_scl()
{
DataTable dt= BAL.getDataForSideBar();
string retHtml = "";
return retHtml;
}
it is giving me error like below
HTTP Error 404.0 - Not Found
The resource you are looking for has
been removed, had its name changed, or is temporarily unavailable.
it seems to me it is not possible but i may be wrong.
so im here to clarify my doubt.
if it is possible how to do it? and whats wrong with my code?

jquery postback using c# and asp.net returns null

I am attempting to use jquery to call a c# function when a button is clicked. What happens is the return variable (msg) is null.
The button code:
<button id="test1" runat="server">Get Text</button>
The JQuery code:
$(document).ready(function() {
$("#test1").click(function() {
$.ajax({
type: "POST",
url: "ServiceDirectoryAdd.aspx/GetCurrentDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
});
The C# function:
[WebMethod]
public static string GetCurrentDate()
{
return "foo";
}
As I said, the return variable, msg, returns null. Is there something I'm doing wrong?
EDIT: After placing a breakpoint in the C# function, it seems that the program is not entering the function.
Did you added script manager to page. If you not added it. Please add it and then script manager "EnablePageMethod" property to true.
Here is the link for that.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
try with indexing the msg
alert(msg[0]); or alert(msg.d);
Have you tried a GET?
$.get("ServiceDirectoryAdd.aspx/GetCurrentDate", function(data){
alert(data || data.d);
});
And edit the webmethod to accept get
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string GetCurrentDate()
{
return "foo";
}

Calling ServerSide Method using Jquery in .Net1.1

I am using .net1.1 and trying to call a server side method using Jquery on click of browser Close button.My code is not working.I am posting my code below.Will anybody Guide me where did i go wrong?
<body MS_POSITIONING="GridLayout" onbeforeunload="javascript:return test()" >
Ceci est une page cachée. Elle est utilisée pour la gestion du multi-fenétrage.
</body>
function test()
{
debugger;
$(document).ready(function() {
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("success");
},
error: function(msg) {
alert("Error! Try again...");
}
});
return false;
})
}
In Code behind
==================
[WebMethod()]
public DateTime GetServerTime()
{
return DateTime.Now;
}
}
The control does not go to this web method,I am not able to debug,COntrol goes to ' $(document).ready(function() ' after that whole block runs.It is not showing any type of error,but alerts are not showing.If I use any other return type instead of DateTime,It is still not working
**When I am Calling this method test on onload,It is showing alert of error Conditon.But I have to call it when broswer is closed.In any Case it is not going to web method.
$(document).ready(function() { ... }) doesn't execute a function but registers a functoin to be executed when the document is loaded.
$(document).ready(function() { ... }) register a function for the load event of the document. You register this function in onbeforeunload event, this function will never be executed. Because when you register the function in onbeforeunload event, the document has already been loaded and is being unloaded.
If you want to call a method in onbeforeunload , just write the JS code to call WebMethod without $(document).ready
function test()
{
// $(document).ready(function() { //delete this
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) { alert("success"); },
error: function(msg) { alert("Error! Try again..."); }
});
return false;
}
Unfortunately, you cannot specifically check for a browser close. Using onbeforeunload will fire when someone is redirected from this page also. Try binding your event using jQuery on DOM load.
$(document).ready(function() {
$(window).unload(function(e) {
e.preventDefault();
test();
});
});
I can't say exactly why your code doesn't because you haven't provided any error information.
Calling web method from script
You need to take a look at your web service, you need to tell it you'll be calling it from script and as the other guy rightly says, you cannot implicitly serialize a DateTime so the laziest way to get this is to just return a string instead.
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string GetServerTime()
{
return DateTime.Now.ToString();
}

Calling a c# methode from javascript/jquery and get the result

I have a dialog in an ASP.Net,c# application.This dialog has a textbox.When I choose save I want to call a function from C# who makes some verifications in the database and then to get the result in javascript/jquery.If the inserted value is true I want to close the dialog other way to remain opened,but I can't succed to close the dialog box after i receive true from c# function.Below is the code:
ascx :
<div id="popup" title="Choose Delegate">
<label>Delegate<label><input type="textbox" value="" name="inputD" id=="inputD"/>
</div>
Javascript:
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
$(this).dialog("close");
},
failure: function () {alert("FAIL"); }}); }
});
}
C#:
[WebMethode]
public static Boolean check(string delegate)
{
.....
return true;
}
C# methode returns corect value.
I try also this :
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
var rez ;
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
},
failure: function () {alert("FAIL"); }
});
if (rez="OK")
$(this).dialog("close");
}
});
But it doesn't see the rez value in this case.
Thanks !
You can use an Ajax Call in your "save":function(e) and just check the returned value if true close dialog, else remain opened
Ajax calls are really simple to implement, I let you search that :)
You need a web-service on the server side. (preferably REST)
http://restsharp.org/ is an easy to use library for that.
Take a look at this question for more info.
In the front end you make an ajax call to you're REST api (I see you use jquery so it won't be that hard ;))

Categories