I need to call a handler (ashx) file from jQuery to fetch some data at runtime.
My jQuery function looks like:
var pID = 3;
var tID = 6;
$("#Button1").click(function() {
var urlToHandler = "Controller/TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: "{'pID':'" + pID + "', 'tID':'" + tID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
My handler code:
<%# WebHandler Language="C#" Class="TestHandler" %>
using System;
using System.Web;
public class TestHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
String pID = context.Request.Params["pID"];
String tID = context.Request.Params["tID"];
context.Response.ContentType = "text/plain";
context.Response.Write(pID + " " + tID);
}
public bool IsReusable
{
get {
return false;
}
}
}
The problem is the code execution doesn't reach to the handler code.
I can call other web forms (aspx) files from the same jQuery function from the same directory, where the handler file is residing. So it isn't any path issue.
I am new to this handler file concept. I googled a lot but couldn't find anything wrong in my code.
It worked after changing the way I was passing the json data (as suggested by #DRAKO) and removing the contentType from the ajax post back call. Also corrected the path.
$("#Button1").click(function() {
var urlToHandler = "TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: { pID: pID, tID: tID },
dataType: "json",
success: function(msg) {
//do something with the msg here...
}
});
});
I think the way you are passing the json data to the handler is incorrect.
Also make sure the path to the handler is correct and write a line to the console in the handler to check if it is getting called. Try this code out
$("#Button1").click(function(){
$.ajax({
type: "POST",
url: "/Controller/TestHandler.ashx",
data: {pID:pID, tID:tID},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(){
alert("Error");
}
});
});
Related
I have used the JavaScript code to call a method in the c# class (method provided in code). When is does a post back I get an error 500, I would like to know how I can fix this so that I call the method.
JavaScript to call c# class method
$.ajax({
type: "post",
url: "TestChapter.aspx/timeFinished",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//
}
});
Method in C# class testchapter.aspx:
[System.Web.Services.WebMethod]
public void timeFinished() {
// my code is here
}
Try this method in C# class testchapter.aspx, it might work:
[System.Web.Services.WebMethod]
public static void timeFinished() {
// my code is here
}
Have a look at this post
One thing is that you certainly missed the / char in your ajax method url, it should be:
url: "/TestChapter.aspx/timeFinished",
The other thing is that you should log the error to the console, it's easier that way:
$.ajax({
type: "post",
url: "/TestChapter.aspx/timeFinished",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// do something
},
error: function (data) { // handle your error loging in here
var errorDetails = data.responseText.replace("{", "").split(',');
var errorMessage = "";
for (var i = 0; i < errorDetails.length; i++) {
if (errorDetails[i].split(':')[0] == "\"Message\"") {
errorMessage = errorDetails[i].split(':')[1];
}
}
alert("Error:" + errorMessage);
});
It will write all errors in the debugger console, it's a lot easier to find errors.
I have a website www.arabadukkan.com
I have cascading comboboxes at the top (araç türü->marka->model etc)
I am calling a webmethod to return the results but the result is the html of entire page.
This code works great in my local
WebMethod code :
public static string GetMarkas(string selectedId)
{
var items = Service.DS.GetMarkas().WithCategoryId(selectedId.SayiVer());
string donen = "<option value=''>Tüm Markalar...</option>";
foreach (var item in items) donen += string.Format("<option value='{0}'>{1}</option>", item.id, item.Title);
return donen;
}
I couldnt find any solution. When i look the network tab in chrome i see the GetMarkas response header is "Content-Type:text/html; charset=utf-8"
My script is :
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: $.toJSON(veriler),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
Try below code I guess u don't require json here..
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: { selectedId : veriler},
dataType: 'html',
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
You may want to make sure that you've added necessary web.config entries, specifically httpModules section. Please go through this
I want to read data which is posted in JSON in my c#.net application? I am very new with this JSON and POST method?
Can anyone please help me?
I am posting data from page1. to other page2 (smsstaus.aspx in my case) for testing purspoe.
I want to read that JSON posted data in PageLoad of Page2.
Sample code.....
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
You could define a WebMethod in your smsstatus.aspx (SendStatus for example)
An implementation could look something like this (from the top of my head)
[WebMethod]
public static void SendStatus(string sid, string status)
{
// retrieve status
}
Now you can create a request to consume this method, like this:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx/SendStatus",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
.NET wil deserialize the json string to and pass them as arguments to SendStatus
when you are using Jquery and you throw JSON in the data thingy it will change in a normal Post but what you are now doing is gonna give problems change the code to:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: {"SmsSid":$("#<%= txtSmsSid.ClientID%>").val(),"SmsStaus": $("#<%= txtSmsStaus.ClientID%>").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
and you can use the normal POST but if you want to play with JSON in C# see this aritcle
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
Do not change the contentType if you want to request the aspx (WebForm) and not the WebMethod. (When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded").
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
dataType: "json", // The type of data that you're expecting back from the server.
success: function (msg) {
alert(msg.d);
},
error: function () { }
});
Receive data from the Page_Load handler,
//Read Form data
string testData = Request["SmsSid"] + " " + Request["SmsStaus"];
//Prepare Json string - output
Response.Clear();
Response.ContentType = "application/json";
Response.Write("{ \"d\": \"" + testData +"\" }");
Response.Flush();
Response.End();
So here's the problem. I have three pages that make web service calls. The first time I land on the page and make the call it works fine, however if I switch to the second page it tries to make a web service call to the wrong service. Here's some info:
pages:
Page1.aspx - has Page1.js
Page2.aspx - has Page2.js
js files:
Page1.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page1List").html(html);
}
Page2.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page2List").html(html);
}
So both have the same calls and the same information and the only real difference is that the results are different and they make a web service call to different web services that get different data.
Now each time that I switch between I get a new js file which is
jQuery-1.7.1.min.js/eval/seq/1
jQuery-1.7.1.min.js/eval/seq/2
jQuery-1.7.1.min.js/eval/seq/3
jQuery-1.7.1.min.js/eval/seq/4
depending on how many times I switch back an forth. Is there any way to stop the eval or is there something in my code that is causing the jQuery to store evals of the code I am using and what can I do to resolve it?
So the problem was that I was loading page transitions from jquery mobile. What was happening was that jquery mobile appends new page data to the DOM instead of forcing a page load. This was causing both javascript files to be loaded simultaneously meaning that which ever js file was loaded last was the primary and because both js files were calling functions with the same name it would load them multiple times.
Resolution
remove the $.mobile.load() event and force the click event to append the pathname to the url
$("#GoPage1").on("click", function () { window.location = "/dir/Page1.aspx"; });
$("#GoPage2").on("click", function () { window.location = "/dir/Page2.aspx"; });
I am getting a problem in calling a webmethod inside my http handler. The jquery.js file opens up at some random place and gives a prompt "Invalid Argument"
Code is as follows:
JS:
var src = "MyHandler.axd";
var id = "1234566";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: src + "/MyMethod?key=" + id,
success: function (msgObj) {
var msg = msgObj.d;
},
error: function (e) {
alert("Error");
}
});
C#
[System.Web.Services.WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string MyMethod(string key)
{
return someLogic;
}
And because of which the ProcessRequest method is being called for the ajax call.
Even tried it with following
Removed httpget and responseformat from c# code.
JS
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: src + "/MyMethod",
data: "{ 'key':'"+ id +"'}",
dataType: "json",
success: function (msgObj) {
debugger;
var msg = msgObj.d;
},
error: function (e) {
debugger;
}
});
Well, not able to find any solution or reason why this behavior!
Kept the same webmethod in a page and its working fine. So added logic to handle the ajax call in process request only. works like a charm.