ASP.NET, AJAX - 403 forbidden - asp.net

I'm getting the error
**POST http://localhost:34169/createNew.aspx.cs/Confirm 403 (Forbidden) **
when I am trying to call a CodeBehind function with Jquery AJAX.
My code:
function CallConfirmMethod(str) {
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "createNew.aspx.cs/Confirm",
data: "{'smallPos': " + str + "}",
success: function (result) { alert("successful!"); }
});
}
And the CodeBehind function (doesnt actually do anything, just to test things out):
[System.Web.Services.WebMethod(BufferResponse = false)]
protected void Confirm(string str) {
// SKICKA SQL-QUERY
Response.Write("Funktionen kallas! " + str);
}

I think your mistake is in url createNew.aspx.cs/Confirm you should change it to createNew.aspx/Confirm. Also it's good article Calling ASP.Net WebMethod using jQuery AJAX

Maybe you get 500, because you haven't close Response
[System.Web.Services.WebMethod(BufferResponse = false)]
protected void Confirm(string str) {
// SKICKA SQL-QUERY
Response.Clear();
Response.ContentType = "application/text";
Response.StatusCode = 200;
Response.Write("Funktionen kallas! " + str);
Response.Flush();
Response.End();
}
if you want send response in json this is article AJAX to web method not returning JSON

Related

Calling C# collection using Ajax to GridView

Why i get error when i call this collection? All i need to to bind this collection to my Gridview control.....
C# Code:
[WebMethod]
public static List<Customer> GetAllCustomers()
{
using (masterEntities context = new masterEntities())
{
return context.Customer.ToList();
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("id");
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Rows.Add();
GridView1.DataSource = table;
GridView1.DataBind();
}
Ajax code:
function GetCustomers() {
$.ajax({
type: "POST",
url: "12.aspx/GetAllCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (data) {
alert(data.d);
}
});
function OnSuccess(data) {
for (var i = 0; i < data.d.length; i++) {
$("#GridView1").append("<tr><td>" + data.d[i].Id + "</td><td>" + data.d[i].Name + "</td><td>" + data.d[i].Age + "</td></tr>");
}
}
This is what i get when i call that collection
http://s22.postimg.org/6qv6tr8g1/aaaaaaaaaaaaaaaaa.jpg
The problem is with the $.ajax error handler:
error: function (data) {
alert(data.d);
}
Error hanlder written like this, gives you very little information on what happened with the failed request. A better way to write your error handler would be like this:
error: function (jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(jqXHR.responseText);
}
With error handler written this way you can look e.g. Chrome Developer Tools's console window and see the value of jqXHR.responseText which contains detailed error description of what went wrong.
Although be careful to replace console.log statements with more meaningful error messages when you deploy your web applications.
Here's a link to jQuery API documentation (look for error handler description): http://api.jquery.com/jQuery.ajax/
Hope this helps!
Regards,
Uros

WebMethod In Aspx Page Can Not Have access Allow-Origin

I have following code.It is not working for enabling CORS.Please help.I am not able to enable CORS in my Web Method on aspx page :
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Response.AppendHeader("access-control-allow-headers", "content-type");
}
[WebMethod]
[ScriptMethod]
public static string Get(string data)
{
System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
System.Web.HttpContext.Current.Response.AppendHeader("access-control-allow-headers", "content-type");
return data + " 123";
}
}
// Java Script
function GetData() {
window.jQuery.support.cors = true;
window.jQuery.ajax({
url: 'http://generalservices.prop.preview.gearhost.com//Default.aspx/Get',
contentType: "application/json; charset=utf-8",
dataType: "json",
type: 'post',
data: "{ data : '12'}",
success: function (d) {
},
error: function (d) {
}
});
error : in Access-Control-Allow-Origin not allowed
Page methods are supposed to be used only from the same page where they are defined.
If you need to fetch data from different pages, I would suggest you look into Asp.Net Web api. Or you could even create a simple Generic handler (.ashx file) which you call from your page(s). The handler could deserialize the Json data, process it and return the required response. In a generic handler you can specify any/all http headers that you need.

how to send consecutive messages from httphandler using json,ajax,jquery

I am trying to send two consecutive messages from httphandler file to client using JSON,AJAX and JQUERY. Howerver only the second message is displayed . What could be the reson? How do you display both the messages?
.ASHX
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
public class Gen_BLL : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string ename = JsonConvert.SerializeObject("Message1..");
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(ename);
ename = JsonConvert.SerializeObject("Message2..");
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(ename);
}
public bool IsReusable {
get {return false;}
}
}
.JS file:
function funGenAst(usro){
$.ajax({
type: "GET",
url: "Gen_BLL.ashx",
contentType: "application/json; charset=utf-8",
data: { "uso": usro },
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result){
alert("fail...');
}
Only one alert is displayed, ie "Message2.." . "Message1.." alert is not popped up at all. How do you get to alert both messages one after the other?
Thanks
bsc
You simple can not do that.
There is a protocol of http communication, and this is break it, from the moment you send some header and some content, there is not prediction to clear the header, and send a second (or new) message.
About Hypertext Transfer Protocol (HTTP): http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html
Alternative way: Merge your message to one response, or after you receive the first message, make new request to get the second one.

Cross Domain Access to ashx service using jQuery

I have an ASP.NET service that I'm access from a asxh file that returns a JSON string. The service works great except when accessed from our blog sub domain which is on a separate server. (blog.laptopmag.com)
Here is my jQuery
$.ajax({
type: "GET",
url: "http://www.laptopmag.com/scripts/service.ashx",
data: { "op": "get_products" },
dataType: "json",
success: function (data) {
alert(data);
}
});
and here is my ashx file
public class service : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string jsonStr = "{}";
string op = context.Request["op"];
// Process request
context.Response.ContentType = "application/json";
context.Response.Write(jsonStr);
}
public bool IsReusable {
get {
return false;
}
}
}
I've tried switching to a jsonp request, but must be doing something wrong because I can't get anything to pull back. Here is what I've tried.
and here is my jsonp attempt that doesn't seem to work when called from blog.laptopmag.com
$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=ProcessRequest&op=get_products', function(json) {
console.log(json);
});
OK, I figured out what the problem was with my JSONP request thanks to the following post:
Jquery success function not firing using JSONP
The problem was that the request wasn't getting a response back in the expected format.
Now, my ashx file now looks like this:
public void ProcessRequest (HttpContext context) {
string jsonStr = "{}";
string op = context.Request["op"];
string jsonp = context.Request["callback"];
// Do something here
if (!String.IsNullOrEmpty(jsonp))
{
jsonStr = jsonp + "(" + jsonStr + ")";
}
context.Response.ContentType = "application/json";
context.Response.Write(jsonStr);
}
and the jQuery ajax request looks like this:
$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=?&op=get_products', function(json) {
console.log(json);
});
Security restrictions prevent you from making cross-domain jquery ajax calls, but there are workarounds. IMO the easiest way is to create a page on your site that acts as a proxy and hit the page with your jquery request. In page_load of your proxy:
WebClient client = new WebClient ();
Response.Write (client.DownloadString ("your-webservice-url"));
Other solutions can be found by a quick Google search.

JqueryAjax Webservice and Crossdomain problem

i am having problem with my Jqueryajax call that will consume one of my web service method via cross domain. i have been trying all the possible way to accomplish but still no success. please help me with what i am doing wrong. may be i need to configure web server for some security settings? below is my code. please let me know if you have any question regarding with my code.
//Using Ajax Post
//Webservice will return JSON Format
//Doesn't work in both FF and IE when host to live server , work in local
//Error : Access is denined in xxxx.js in IE
//Http 403 Forbidden in FF , FF request header is OPTION
//this approach is the simplest and best way for me to use
var myID = $("myID").val();
$.ajax({
type: "POST",
url: "http://www.mywebsite.com/webservice/Webservice.asmx/getInfo",
data: "{myID:'"+ myID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
Dostuff(data);
},
error: FailureCallBack
});
My webservice will look like this
using System.Web.Script.Services;
[WebService(Namespace = "http://www.mywebsite.com/webservice/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class Webservice : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public object getInfo(string myID)
{
//Do stuff here
return getJSONDataFromDataSet(_DS);
}
}
//second Approch <br/>
//Using Ajax GET , webservice will return XML Format <br/>
//Doesn't work in both FF and IE when host to live <br/>
//Error : Access is denined in xxxx.js in IE <br/>
//returning XML data in FF but showing nothing in page <br/>
var myID = $("myID").val();
$.ajax({
type: "GET",
url: "http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID="myID"&callback=?",
success: function(data) {
Dostuff(data);
},
error: FailureCallBack
});
Webservice
public SerializableDictionary<string, object> getInfo(string myID)
{
//Do stuff here
SerializableDictionary<string, object> obj = getJSONFromDataTable(_DS);
return obj;
}
//third Approch
//Using normal GET , webservice will return XML Format
//same problem with second approch
var myID = $("myID").val();
var xmlhttprequest = createRequestObject();
var url = 'http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID='myID'';
xmlhttprequest.open("GET", url, true);
xmlhttprequest.onreadystatechange = getData;
xmlhttprequest.send(null);
function getData()
{
if ((xmlhttprequest.readyState == 4) &&( xmlhttprequest.status == 200))
{
var myXml = xmlhttprequest.responseXML;
Dostuff(myXml);
}
}
function createRequestObject()
{
if (window.XMLHttpRequest)
{
return xmlhttprequest = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
return xmlhttprequest = new ActiveXObject("Microsoft.XMLHTTP");
}
}
Webservice is same with second approach
EDIT:
now i am getting Access is denied , javascript error for both POST and GET request in IE.
in fiddler i can see Firefox returning the Xml data but nothing showing in page, so i put a alert box in getData
function, myXml variable value is always null, strange i only put 1 alert box and it show alert 3 times.
below is my code
var myID = $("myID").val();
var xmlhttprequest = createRequestObject();
var encodeUrl = escape(_utf8_encode("http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID="myID));
var url = 'http://www.mywebsite.com/webservice/proxy.aspx?url='+encodeUrl;
xmlhttprequest.open("GET", url, true); //**ACCESS IS DENIED HERE in this line!!!!**
xmlhttprequest.onreadystatechange = getData;
xmlhttprequest.send(null);
function getData()
{
var myXml = xmlhttprequest.responseXML;
alert(myXml); //ALWAYS NULL and show alert 3 times????
DoStuff(myXml);
}
Please help.
best regards
For security reasons, the ajax requests will not work cross domain. There are two solutions to this.
Make the request to the same server, and use a server based proxy mechanism to then make the request to the other domain.
Use "JSONP", which is an alternative cross way of making ajax like requests. jQuery supports this via the dataType: jsonp rather than json, and there is further explanation via their api docs. This blog entry may be useful - http://bloggingabout.net/blogs/adelkhalil/archive/2009/08/14/cross-domain-jsonp-with-jquery-call-step-by-step-guide.aspx
you will need to create proxy on your domain and pass through the request, explain here: http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/
thanks so much for all the reply and help.
i have solved the problem :D
solution is to use JSONP and Javascript dynamic injection to html page.
below is code
HTML
<body>
<script type="text/javascript">
var url = "http://www.mywebsite.com/Javascript/MYJS.js";
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
document.body.appendChild(script);
</body>
</script>
MYJS.js
var myID = $("#myID").val();
var url = "http://www.mywebsite.com/Webservice.aspx/getInfo?myID="+myID+"";
if (url.indexOf("?") > -1)
url += "&jsonp=" ;
else
url += "?jsonp=" ;
url += "ShowInfoCallback" + "&" ; //Important put ur callback function to capture the JSONP data
url += new Date().getTime().toString(); // prevent caching
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
document.body.appendChild(script);
function ShowInfoCallback(data)
{
DoWhateverYouWant(data);
}
Webservice.aspx.cs
using System.Web.Script.Serialization;
public partial class Webservice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["myID"]))
this.getInfo();
else
this.getInfoDetails();
}
public void getInfo()
{
string Callback = Request.QueryString["jsonp"];
string encryptedID = Request.QueryString["myID"];
//Dowhateveryouwanthere
object obj = getJSONFromDataTable(myDataSet.Tables[1]);
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(obj);
Response.Write(Callback + "( " + sJSON + " );");
Response.End();
}
public void getInfoDetails()
{
//Same as above
//returning 2 tables , Info and InfoDetails
Response.Write(Callback + "( { 'Info' : " + sJSONDetails +",'InfoDetails' : "+ sJSONService + " } );");
Response.End();
}
}
Thanks again

Resources