Unable to find dynamically created control when JSON is used - asp.net

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 ???

Related

Calling ajax request from html page inside asp.net project

I cannot get a simple ajax example to work from an html page inside my visual studio project. It works fine from a webform (aspx):
...
webform1.aspx and form1.html
...
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: bob }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}
...
webform1.aspx and form1.html
...
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime()" />
...
json.aspx
...
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
If I put the code in webform1.aspx, it works fine. If I put it on form1.html, nothing comes back from json.aspx. I am running the project in debug mode from my machine using vs2013. Any help would be appreciated.
Update #1
I checked fiddler and the server is returning the following result (500):
{"Message":"Invalid JSON primitive: bob.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at ...
Your json is malformed. Strings need to be in quotes. Put bob in quotes and you should be good. I'm unsure why it's working on the ASP.NET page though, unless it has the quotes there.
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: \"bob\" }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}

Accessing Data in Httphandler sent using post request

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

ASP.Net Dynamic Data with Xml or Alternative

I have to display data in a web application with the ability to filter. The data is ported via FTP as XML. Can I use Dynamic Data to handle this or is there an alternative way. I do know I can manually linq to the xml and display in datagrid or some other control but the Dynamic Data Template seems to offer all the Data management functionality.
ya use JSON and JQUERY
here is code from which i filter account no,
$(function () {
var search = $("#<%=txtAccountNo.ClientID%>");
search.watermark('Enter Account No');
search.autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/") %>AutoCompleteService.asmx/GetAccountNo',
data: "{ 'prefixText': '" + search.val() + "', 'count' : '10','contextKey':''}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d != null) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
}
},
error: function (XMLHttpRequest, textStatus, error) {
//alert(textStatus);
}
});
},
minLength: 1
});
});

page hanged when web method is executes

I am working on an ajax-webmethod (using json) to save data in a database and select it when needed. Now whenever I call the webmethod, while the method is processed the whole page hangs and nothing can be done with the page.
I want to enable everything while the web method is called from ajax, for example showing a loading image until the web method finishes.
My code is below:
function getvalues(id, tab, pageNo) {
$.ajax({
type: "POST",
url: "default.aspx/LoadData",
data: "{'id':'" + id + "','tab':'" + tab + "','pageNo':'" + pageNo + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d.length > 0) {
var dvComment = document.getElementById("Comments");
dvComment.innerHTML += msg.d;
}
},
async: true,
error: function(xhr, status, error) {
// alert(xhr.statusText);
}
});
}
So now when it renders the html into the DIV the whole time the page hangs.
To show loading image you can use ajaxStart method like this:
$("#loading").ajaxStart(function(){
$(this).show();
});
Where #loading is:
<img id="loading" src="images/ajaxload.gif" alt="loading..." style="display:none"/>
To hide loading image:
$("#loading").ajaxComplete(function(){
$(this).hide();
});

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);
}
});
});

Resources