Accessing Data in Httphandler sent using post request - asp.net

I have created a httphandler. Everything is working fine If you take the request type GET. But I really don't want GET request due to security reasons.
I am making a POST request using Jquery using following code:
$.ajax({
type: "POST",
async: false,
url: "SaveAccounts",
data: { a: "Sent Data" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(a) {
alert(a);
},
error: function OnError(request, status, error) {
alert('Error: ' + request + ' ' + status + ' ' + error);
},
complete: function () {
}
});
And the code for processing request is:
context.Response.ContentType = "application/json; charset=utf-8"
Dim s As String = context.Request.Params("a")
context.Response.Write(JsonConvert.SerializeObject(s))
This code is returning 'null' in javascript alert in client side.
Please note every thing is working fine when request type is changed to GET in $.ajax() function.
I have also tried to access posted data using context.Request.Form("a") and context.request.SserverVariables("a")
context.request.Params is a combined collection of 'Form', 'ServerVariables', 'Cookies' etc.
Please tell me where I am going wrong...??
Thanks for looking....

This is working by just removing contentType and dataType specification from the request.
Anything other than this will remain unchanged.

Try
data: { "a=Sent Data" },
e.g. from http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Also the HttpHandlers don't like JSON data so get rid of the contentType and the dataType.
Escaping it - a more complete example
var dataString = "{ 'first' : '" + escape($('#fname').val()) +
"', 'mail' : '" + escape($('#tbMail1').val()) +
"', 'mailinglist' : '" + $("input[name='ml']:checked").val() +
"' }";
/*alert(dataString.replace('\',','\',\n'));*/ // just for debugging ;)
$.ajax({
type: "POST",
url: "myAjaxHandler.asmx/ProcessSampleForm",
data: dataString,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(".loadingimg").fadeOut();
window.location.replace(msg.d);
},
error:function(xhr,err){
$(".loadingimg").fadeOut();
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
Taken from http://www.jphellemons.nl/post/JQuery-with-webform-input-validation-ajax-posting-json-to-aspnet-C.aspx

Related

XmlHttpRequest cannot load ajax call url. Origin domain is not allowed by Access-Control-Allow-Origin

I have two ajax call back function in my web page. There is a problem as you can see in the title. Here is my codes:
$.ajax({
type: "POST",
url: "http://....com/Ap.aspx/GetPriceList",
data: "{categoryId:" + categoryId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var priceList = JSON.parse(data.d);
$(function () {
$("#slider-range").slider({
range: true,
min: priceList[0],
max: priceList[1],
values: [priceList[0], priceList[1]],
slide: function (event, ui) {
$("#amount").val(ui.values[0] + " (TL)" + " - " + ui.values[1] + " (TL)");
},
change: function (event, ui) {
// alert(ui.values[0]);
// alert(ui.values[1]);
}
});
$("#amount").val($("#slider-range").slider("values", 0) + " (TL)" + " - " + $("#slider-range").slider("values", 1) + " (TL)");
$("#" + "<%=lblProductCount.ClientID %>").text("Listelenen ürün sayısı :" + priceList[2]);
var btnLoadMore = ' <input type="button" alt="Daha Fazla Ürün Yüklemek İçin Buraya Tıklayın" class="moreProduct" onclick="LoadMore();"/>';
$("#load").html(btnLoadMore);
});
}
});
I see this error in chrome developer's tools. XMLHtttpRequest cannot loadurl. Origin domain name is not allowed by Access-Control-Allow-Origin. I also try to write Response.AppendHeader("Access-Control-Allow-Origin", "*"); on my master page's page load event. Do you have any suggestion?
The server hosting GetPriceList needs to respond to your request with the Access-Control-Allow-Origin: * header. You sending it from the client does nothing.

Unable to find dynamically created control when JSON is used

I am calling JSON method on selected index changed of the drop down list which is as follows
function StepImplementationScript(SelectedValue,UniqueField) {
debugger;
$.ajax({
type: "POST",
url: "DynamicForm.aspx/StepImplementationScript",
data: "{strSelectedValue: " + SelectedValue + ", strUniqueField: '" + UniqueField + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(response) {
alert("OnSuccess" + response.d);
if (msg) {
msg.close();
}
},
error: function(jqXHR, exception) {
alert(jqXHR.responseText);
},
failure: function(response) {
//alert("Onfailure" + response.d);
}
});
}
In this 'StepImplementationScript' method of server side when i try to find dynamically created control, the controls are not getting find and coming as null.
Selected change event i have written in Jquery through which i have called the JSON method.
This is the same page (DynamicForm.aspx) on which controls are created dynamically.
Why this is so ? and how should i resolve this issue ???

.ajax not working

i am trying to make an ajax request it is not working properly
my code
function checkUserName() {
debugger
var userName = 'vipin jain';
$.ajax({
type: "POST",
url: "Default.aspx/isUserAvailable",
data: { userName: "+userName+" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
$(".successNotification").removeAttr('display');
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
}
can u tell me what is going wrong.
You really should notice what is going wrong, what error message you are receiving, what doesn't work as expected. From this I can see 2 possible things going wrong:
The debugger line, what is that about? Remove it and debug with Firebug in Firefox
data: { userName: "+userName+" }, This always gives '+userName+' as the username, I guess you need the username here? Do it like this: { userName: userName }.

JQuery and Ajax - Coming to Grips

I've read through several tutorials on the web about ajax posting with JQuery, all of them reference the response object from the web service as response / response.d -- This lead me to believe that this is the built in object for JQuery's response handler.
Code Snippet:
$('.submit').click(function () {
var theURL = document.location.hostname + ":" + document.location.port + "/LeadHandler.aspx/hello"; // this will change too
alert(theURL);
$.ajax({
type: "POST",
url: theURL,
data: "{'NameFirst':'" + $('#txtFirstName').val() + "'}", // again, change this
contentType: "applications/json; charset=utf-8",
dataType: "json",
success: alert("Success: " + response.d), // this will change
failure: function (response) {
alert("Failure: " + response.d);
}
});
});
however the code is returning "Uncaught ReferenceError: response is not defined" in Chrome's Javascript console. What assumptions am I making that I need to re-evaluate.
You need to supply success with a function to execute:
success: function(response) {
alert(response.d);
}
Success (Like Failure) need a function to pass the response object through.
$('.submit').click(function () {
var theURL = document.location.hostname + ":" + document.location.port + "/LeadHandler.aspx/hello"; // this will change too
alert(theURL);
$.ajax({
type: "POST",
url: theURL,
data: "{'NameFirst':'" + $('#txtFirstName').val() + "'}", // again, change this
contentType: "applications/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Success: " + response.d);
},
failure: function (response) {
alert("Failure: " + response.d);
}
});
});

Pass Multiple Parameters to jQuery ajax call

I have the following jquery code to call a webmethod in an aspx page
$.ajax({
type: "POST",
url: "popup.aspx/GetJewellerAssets",
contentType: "application/json; charset=utf-8",
data: '{"jewellerId":' + filter + '}',
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
and here is the web method signature
[WebMethod]
public static string GetJewellerAssets(int jewellerId)
{
This works fine.
But now I need to get two parameters passed to the web method
the new web method looks like this
[WebMethod]
public static string GetJewellerAssets(int jewellerId, string locale)
{
}
How do I change the client code to successfully call this new method signature ?
EDIT:
The following 2 syntaxes worked
data: '{ "jewellerId":' + filter + ', "locale":"en" }',
and
data: JSON.stringify({ jewellerId: filter, locale: locale }),
where filter and locale are local variables
Don't use string concatenation to pass parameters, just use a data hash:
$.ajax({
type: 'POST',
url: 'popup.aspx/GetJewellerAssets',
contentType: 'application/json; charset=utf-8',
data: { jewellerId: filter, locale: 'en-US' },
dataType: 'json',
success: AjaxSucceeded,
error: AjaxFailed
});
UPDATE:
As suggested by #Alex in the comments section, an ASP.NET PageMethod expects parameters to be JSON encoded in the request, so JSON.stringify should be applied on the data hash:
$.ajax({
type: 'POST',
url: 'popup.aspx/GetJewellerAssets',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ jewellerId: filter, locale: 'en-US' }),
dataType: 'json',
success: AjaxSucceeded,
error: AjaxFailed
});
data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}',
simply add as many properties as you need to the data object.
$.ajax({
type: "POST",
url: "popup.aspx/GetJewellerAssets",
contentType: "application/json; charset=utf-8",
data: {jewellerId: filter , foo: "bar", other: "otherValue"},
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
DO not use the below method to send the data using ajax call
data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}'
If by mistake user enter special character like single quote or double quote
the ajax call fails due to wrong string.
Use below method to call the Web service without any issue
var parameter = {
jewellerId: filter,
locale : locale
};
data: JSON.stringify(parameter)
In above parameter is the name of javascript object and stringify it when passing it to the data attribute of the ajax call.
$.ajax({
type: 'POST',
url: 'popup.aspx/GetJewellerAssets',
data: "jewellerId=" + filter+ "&locale=" + locale,
success: AjaxSucceeded,
error: AjaxFailed
});
Has anyone else noticed that the json string/object is invalid in all answers except for David Hedlund's? :)
JSON objects must be formatted in the following manner: {"key": ("value" | 0 | false)}. Also, writing it out as a string requires much less than stringifying the object...
var valueOfTextBox=$("#result").val();
var valueOfSelectedCheckbox=$("#radio:checked").val();
$.ajax({
url: 'result.php',
type: 'POST',
data: { forValue: valueOfTextBox, check : valueOfSelectedCheckbox } ,
beforeSend: function() {
$("#loader").show();
},
success: function (response) {
$("#loader").hide();
$("#answer").text(response);
},
error: function () {
//$("#loader").show();
alert("error occured");
}
});
Just to add on [This line perfectly work in Asp.net& find web-control Fields in jason Eg:<%Fieldname%>]
data: "{LocationName:'" + document.getElementById('<%=txtLocationName.ClientID%>').value + "',AreaID:'" + document.getElementById('<%=DropDownArea.ClientID%>').value + "'}",
Its all about data which you pass; has to properly formatted string.
If you are passing empty data then data: {} will work.
However with multiple parameters it has to be properly formatted
e.g.
var dataParam = '{' + '"data1Variable": "' + data1Value+ '", "data2Variable": "' + data2Value+ '"' + '}';
....
data : dataParam
...
Best way to understand is have error handler with proper message parameter, so as to know the detailed errors.
I successfully passed multiple parameters using json
data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",
data: JSON.stringify({ "objectnameOFcontroller": data, "Sel": $(th).val() }),
controller object name

Resources