Ajax Success event does not fire when calling service - c#

I am using JQuery to make a AJAX to a local service. My local service is a HttpHandler (e.g., Request.ashx). Within Request.ashx, it's responsiblity is to make a call to an external website (e.g., CallExternalWebsite()). CallExternalWebsite() uses .NET's System.Net.WebRequest() to initiate a request. When the external website is accessed, neither the success or error events are fired. (NOTE: I have also tried this a WCF service hosted in IIS. I am seeing the same results)
Here are two scenarios:
This scenario works:
In ProcessRequest(), comment out callExternalWebsite().
For object o, intialize with data to simulate results.
Click on myButton
The success event fires on the client.
In Fiddler, I can see the header info. I see Json result, etc.
This scenario does not work:
In ProcessRequest(), enable the call for callExternalWebsite().
For object o, callExternalWebsite() will return an appropriate object.
Click on myButton
The success event does not fires on the client.
In Fiddler, I can see the header info. I see Json result, etc.
I know the callExternalWebsite() is working because I have it sending results to my phone.
To sum it up, the external http call within the HttpHandler is effecting the Ajax success event.
Here is a snippet from AJAX call:
(I was trying different interations)
$(document).ready(function () {
$("#myButton").click(function (event) {
$.ajax({
cache: false,
type: "POST",
url: "http://localhost/Service/Request.ashx",
data: '{"id" : "053252f3"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 20000,
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
In the HttpHandler Request.ashx,
public Void ProcessRequest(httpContent context)
{
// Do some stuff....
// Make call to external web site
object o = callExternalWebsite (Uri, Data, "POST");
// Return results from callOtherWebsite
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(o);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
Any thoughts?
Thanks.
Steve

What happens if you do this, msg vs msg.d:
$(document).ready(function () {
$("#myButton").click(function (event) {
$.ajax({
cache: false,
type: "POST",
url: "http://localhost/Service/Request.ashx",
data: '{"id" : "053252f3"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 20000,
success: function (msg) {
AjaxSucceeded(msg.d);
},
error: AjaxFailed
});
});
});

Related

ajax call is not working for the c# method

i want to call the unlock method on closing or redirecting other page, so i have used ajax call. but the method unlock is not firing. please let me know what i am doing
[WebMethod]
public void Unlock()
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}
function HandleOnclose() {
$.ajax({
type: "POST",
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
window.onbeforeunload = HandleOnclose;
Where you passing project_id in your ajax call???
pass project_id in your method
[WebMethod]
public void Unlock(string project_id)
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}
and then rewrite ajax call as
function HandleOnclose() {
$.ajax({
type: "POST",
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
data : "{project_id:'1234'}",
dataType: "json"
});
}
window.onbeforeunload = HandleOnclose;
There's a couple of issues. Firstly your WebMethod expects a querystring parameter, yet you're sending a POST request and you also don't send any data in the request. You should provide project_id as a parameter in an object to the data property of the AJAX request.
Also note that sending an AJAX request in the onbeforeunload event is one of the very few legitimate cases where you need to use async: false to stop the page from being closed before the AJAX request completes. Try this:
[WebMethod]
public void Unlock(string projectId)
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(projectId), "");
}
function HandleOnclose() {
$.ajax({
type: "POST",
async: false, // only due to running the code in onbeforeunload. Never us it otherwise!
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { projectId: '1234' }
});
}
window.onbeforeunload = HandleOnclose;
Also note that depending on the browser you may be restricted from sending an AJAX request in the onbeforeunload event at all. See this question for more details.

Ajax Webmethod not being called

I make a total of four Ajax calls in my .NET application. Three of them work without a hitch except the last one.
Note: I HAVE to use .aspx for these calls and not mypage.aspx/mymethod because of our architectural constraints.
Ajax call that works:
$.ajax({
type: "POST",
url: "myaddress/GenerateOpinionHTML.aspx",
data: JSON.stringify({ id: featureId, pageNumber: pageNumberIndex }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
SOME PROCESSING (IT WORKS)
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log(err);
}
});
and
[WebMethod]
public static string GenerateOpinionHTML(int id, int pageNumber)
{
// ...
}
Ajax call that does not work:
console.log("SUBMITOPINIONCLICK");
var param = " ";
$.ajax({
type: "POST",
url: "myaddress/SaveOpinion.aspx",
data: JSON.stringify({ parameter: param}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SAVE OPINION SUCCESSFUL");
console.log(msg.d);
CloseLB('GiveOpinionLB');
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log("ERROR " + "STATUS: " + status);
}
});
and
[WebMethod]
public static string SaveOpinion(string parameter)
{
// ...
}
The web method SaveOpinion is never called according to the logs. Do you have any ideas or suggestions? I tried adding parameters, without parameters, checking my web.config file (though I shouldn't have since the other calls work)...
The error I get on the browser console is a "parseerror". I'm certain I wouldn't be getting an error if the method was called.
I think your URL should be like
url: "Your FolderName/PageName/Function Name",
Like
url: "myaddress/SaveOpinion.aspx/SaveOpinion"
but in your code this is different so that please check.
Have you checked if method SaveOption return something to the client?
If you specify dataType as json, you should return (at least): {}
Ok so we "solved" it. We just found a very dirty band-aid workaround that works.
We made a custom handler (.ashx) that we defined in our architecture as a SaveOpinion.aspx page.
We then called this custom handler page with jQuery and voilĂ  it works, we had to obviously pass all necessary parameters manually, ie. fetching all values from textBoxes etc with jQuery and not from the context as we did before.
Since this is run in some sort of thread (I don't really know the details) we had to configure it so that it simulates the same user authentification.
Anyway I hope this provides some measure of guidance for those with this kind of obscure problems.

Pnotify Post message via webservice

I'm fairly new to the programming world of Jquery.
I am trying to get data from a web service to be viewed on a notification via Pnotify.
However, on each page load the script does not view the notification bar. I really don't understand what I'm doing wrong. Hope you can help.
NOTE: the web service does retrieve the data correctly in JSON format.
UPDATED: I am able to do a msg.d but it retrieves the JSON but does not parse the information how I would like it to.
<script type="text/javascript">
$(function () {
$.ajax({ //DATA REQUEST
type: 'POST',
url: 'WebServices.asmx/getNote',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (msg) {
$.pnotify({ //CALL PNotify
title: msg.NoteTitle,
text: msg.NoteText
});
}
});
});
</script>
I reviewed your code and if you do the following you should be able to get the data you need.
You need to be aware that object that always need to be parsed before passing the array to a view.
In your case you didn't do that.
success: function (msg) {
var Obj= eval(msg["d"]); or // $.parseJSON(msg["d"]) Method to evaluate Json
$.pnotify({ //CALL PNotify
title: Obj["0"].NotificationText, // The pared arrays
text: Obj["0"].NotificationDescription

JQuery ajax call to ASP.NET handler always returns error

I'm writing a client for an asp.net handler that processes and sends notifications to the polling clients. I make ajax calls with jquery every 10 seconds waiting for the notifications. The problem is every time I send a response back to the client it always calls the error callback. With fiddler I see the json response arriving to the client with status 200 but in firebug the request keeps waiting.
Client:
function poll(){
$.ajax({
url: "http://localhost:53914/NotificationChecker.ashx",
data: { userName: "ggyimesi" },
type: 'POST',
success: function(data){
alert("asd");
$('div#mydiv').text(data.Text);
},
complete: poll,
error: function(data){alert(data.status);},
timeout: 15000 });
}
$(document).ready(function(){
poll();}
);
Server:
Response response = new Response();
response.Text = this.MessageText;
response.User = Result.AsyncState.ToString();
string json = JsonHelper.JsonSerializer<Response>(response);
Result.Context.Response.ContentType = "application/json";
Result.Context.Response.Write(json);
I actually found the problem. The problem was that I started the client html from my local machine not hosted on the web server and that caused the problem. After adding it to the local web server the original code worked as it is.
I think your ajax call is missing the following:
dataType: 'json',
contentType: "application/json; charset=uft-8",
Try this:
$.ajax({
url: "/NotificationChecker.ashx",
dataType: 'json',
contentType: "application/json; charset=uft-8",
data: { userName: "ggyimesi" },
type: 'POST',
success: function(data){
alert("asd");
$('div#mydiv').text(data.Text);
},
complete: poll,
error: function(data){alert(data.status);},
timeout: 15000 });
}
I think your problem is that you pass your username like this
data: { userName: "ggyimesi" }
I think you should do it like this
data: '{userName:"' + ggyimesi + '"}'
and you can add more like this
type: "POST",
url: "NotificationChecker.ashx",
contentType: "application/json; charset=utf-8",
dataType: 'json',

Data Format Jquery Ajax Post Cross Domain Call Asp.Net MVC method

I am trying $.ajax post MVC call from http to https cross domain.
Client Side
enter code here
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: '{name:"John"}',
dataType: "json",
success: function (data) { pdata = data; }
});
Server Side
[RequireHttps]
[HttpPost]
public string VerifyEmail(string name){
return "got it"
}
I have added Access-Control-Allow-Origin to web.config so the call can be established fine. Now the problem is on server side I got variable name = null
I have also checked debugging and found the data has actually been send to server
HttpContext.Request.Form
{%7bname%3a%22hello%22%7d}
[System.Web.HttpValueCollection]: {%7bname%3a%22hello%22%7d}
The question is how I could retrieve it from the web method?
%7bname%3a%22hello%22%7d This is HTML entity String please Decode the String then parse for JSON.
I think you can change your call to
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: 'John',
dataType: "text",
success: function (data) { pdata = data; }
});

Categories

Resources