How to make texbox to null after I got success in jQuery AJAX method - asp.net

I am strangling when I added my comments with AJAX method of jQuery, after stressful, I want to make this textbox to null
my Ajax method like this :
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var comment = $("#" + this.id).val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$("#" + this.id).val("");
//alert(response.d);
}
});
}
});
}
what I want is on Success, I want make current textbox to NULL
$("#" + this.id).val("");

This is a scoping issue. this in the success handler holds a reference to the window object, not the input the keypress fired on. You just need to cache the input in a variable you can use in the success handler. Try this:
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var $input = $(this);
var comment = $input.val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$input.val("");
//alert(response.d);
}
});
}
});
}

you can't access this in jquery ajax do it like this save your object in any variable
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var Element=this;
var comment = $("#" + this.id).val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$(Element).val("");
//alert(response.d);
}
});
}
});
}

Your success function is in another context, you can't use this, you have to send the id on the json response and do something like:
success: function (response) {
$('#'+response.div_id).val("");
}
and your json response should include the div_id that's passed on the ajax request

Related

JSON is undefined in IE7

It works fine in chrome, firefox and IE8. But comes up an error on IE7. Here is my jquery onchange event.
$('select#NationId').change(function () {
var nationId = $(this).val();
$.ajax({
url: 'LoadAreas',
type: 'POST',
data: JSON.stringify({ nationId: nationId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('select#AreaId').get(0).options.length = 0;
$('select#AreaId').append('<option value="0">Select All</option>');
$.each(data, function (val, Areas) {
$('select#AreaId').append('<option value="' + Areas.Id + '">' + Areas.Name + '</option>');
});
}
});
});
controller
[HttpPost]
public ActionResult LoadAreas(int nationId)
{
var _Areas = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Area" && c.ParentChannelGroupId == nationId
select new AreaName() { Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);
if (_Areas == null)
return Json(null);
List<AreaName> managers = (List<AreaName>)_Areas.ToList();
return Json(managers);
}
The issue is that the JSON object is not available in IE 7. You'll want to include JSON2.js on your page for IE < 8 users.
If the browser doesn't implement the JSON object, you can always use a third-party library to provide it for you. If I recall correctly, this particular implementation is widely used and defers to the browser, so you just need to drop it in, no tweaking required.
Shouldn't
data: { "nationId": nationId },
just work?
$('select#NationId').change(function () {
var nationId = $(this).val();
var data = '{"nationId": "' + nationId + '"}';
$.ajax({
url: 'LoadAreas',
type: 'POST',
data: data ,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('select#AreaId').get(0).options.length = 0;
$('select#AreaId').append('<option value="0">Select All</option>');
$.each(data, function (val, Areas) {
$('select#AreaId').append('<option value="' + Areas.Id + '">' + Areas.Name + '</option>');
});
}
});
});

Jquery Cascading Drop Down how to trigger the change event for all the dropdowns in the chain Sequencially

I have the following jQuery code in my application that drives four cascading dropdowns. I have seen numerous examples online that force the user to select a value by adding a '--Select a Value---' option. However, what I am trying to do is, for the dropdowns, update automatically in the order if one of them changes.
update 2,3,4 if 1 changes and 3,4 if 2 changes, etc.
Dropdown1 Center Dropdown2 Geo Dropdown3 Sup Dropdown4 Emp
This is the jQuery code I have:
$(function() {
$('#divParentaccordion').accordion({ autoHeight: false }).accordion({ collapsible: true });
$('#divGenericaccordion').accordion({ autoHeight: false }).accordion({ collapsible: true });
$('#<% =ddCenter.ClientID %>').change(getGeo());
$('#<% =ddGeo.ClientID %>').change(getSup());
$('#<% =ddSup.ClientID %>').change(getEmp());
// Statements i assume should call the function when the event triggers
})
function getGeo() {
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetGeoList",
data: "{center: '" + $('#<% =ddCenter.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var geos = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddGeo.ClientID %>').removeOption(/./);
for (var i = 0; i < geos.length; i++) {
var val = geos[i].Code;
var text = geos[i].Description;
$('#<% =ddGeo.ClientID %>').addOption(val, text);
}
}
})
}
function getSup() {
var center = $('#<% =ddCenter.ClientID %>').val();
var geo = $('#<% =ddGeo.ClientID %>').val();
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetSupList",
data: "{center:'" + center + "',geo:'" + geo + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var sups = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddSup.ClientID %>').removeOption(/./);
for (var i = 0; i < sups.length; i++) {
var val = sups[i].SOPId;
var text = sups[i].Name;
$('#<% =ddSup.ClientID %>').addOption(val, text);
}
}
})
}
function getEmp() {
var center = $('#<% =ddCenter.ClientID %>').val();
var geo = $('#<% =ddGeo.ClientID %>').val();
var sup = $('#<% =ddSup.ClientID %>').val();
$.ajax({
type: "POST",
url: "ObservationsReport.aspx/GetEmpList",
data: "{center:'" + center + "',geo:'" + geo + "',sup:'" + sup + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var emps = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddEmp.ClientID %>').removeOption(/./);
for (var i = 0; i < emps.length; i++) {
var val = emps[i].Sop_Id;
var text = emps[i].Name;
$('#<% =ddEmp.ClientID %>').addOption(val, text);
}
}
})
}
What am I doing wrong? I have recently started programming in jQuery; still not completely familiar with how it handles the events and when. Please, any help will be appreciated.
I think your issue is that you're expecting the population of a box from the ajax call to trigger that select's onchange. This is not the case. Changes through javascript do not fire onchange. You will need to fire the onchange yourself.
For example, try changing getGeo to this:
function getGeo() {
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetGeoList",
data: "{center: '" + $('#<% =ddCenter.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var geos = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddGeo.ClientID %>').removeOption(/./);
for (var i = 0; i < geos.length; i++) {
var val = geos[i].Code;
var text = geos[i].Description;
$('#<% =ddGeo.ClientID %>').addOption(val, text);
}
// *** CALL getSup directly ***
getSup() ;
}
})
}
The key here is the explicit call to getSup as it will not be triggered onchange.

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

Put id in input hidden, working with jTemplate?

I'm working with jquery.ajax() I'm getting a object and I use jTemplate to write the html. My problem is now that I need to place the id of the object in a input hidden. I have no idea how I should do this. I tried to do a <script> in the template.htm with jquery to place the id in hidden but with no luck.
Any suggestions?
this is my jTemplate html file
<div style="background-color: #ccc">
{$T.Email}
</div>
<div style="background-color: #ddd">
{$T.Password}
</div>
This is my jquery
$('a').live('click', function(evt) {
evt.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: "POST",
url: "GetUserWeb.asmx/GetUser",
data: "{'value': '" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
ApplyTemplate(msg);
},
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
});
function ApplyTemplate(msg) {
$('#Container').setTemplateURL('template.htm');
$('#Container').processTemplate(msg.d);
}
If you place the id in a JavaScript variable outside the function then you can access it in the template simply by putting {ItHere} in the template.
So do var id outside the function, and set it within the function.
var id;
$('a').live('click', function(evt) {
evt.preventDefault();
id = $(this).attr('id');
$.ajax({
type: "POST",
url: "GetUserWeb.asmx/GetUser",
data: "{'value': '" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
ApplyTemplate(msg);
},
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
});
function ApplyTemplate(msg) {
$('#Container').setTemplateURL('template.htm');
$('#Container').processTemplate(msg.d);
}
Then you can add the id in the template like this:
<img src="HelloWorld.jpg" id="{id}"/>

passing multiple values from multiple textboxes in jquery

Below is the jquery script that takes one input value from textBox1 and pass it to a web method then returns the name of the person and displays it in textBox2. The web method only takes one parameter, the user initials.
<script type="text/javascript" >
$('#textBox1').live('keydown', function(e) {
var keyCode = e.keycode || e.which;
if (keyCode == 9) {
e.preventDefault();
$.ajax({
type: "POST",
url: "Default.aspx/GetName",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"value1":"' + $('#textBox1').val() + ' " }',
success: function(data) {
$('#textBox2').val(data.d);
}
});
}
});
</script>
I want to be able to pass two values from two textboxes for a web method that requires two parameters. how can I modify the jquery code above to accomplish that?
You add the parameters to the data object, which by the way should be an object:
data: { value1: $('#textBox1').val(), value2: $('#textBox2').val() },
Is this what you mean?
<script type="text/javascript" >
$('#textBox1').live('keydown', function(e) {
var keyCode = e.keycode || e.which;
if (keyCode == 9) {
e.preventDefault();
$.ajax({
type: "POST",
url: "Default.aspx/GetName",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"value1":"' + $('#textBox1').val() + '", "value2":"' + $('#textBox2').val() + '" }',
success: function(data) {
$('#textBox2').val(data.d);
}
});
}
});
</script>
I'd use something like jQuery Json

Resources