Can not set value to element - javascript

Im trying to set a value to element (id ctl30_txtTextBox) in javascript.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "IndexMask.aspx/AttachBarcodeFile",
dataType: "json",
data: params,
success: function() {
$("#<%= DummyPostbackButton.ClientID %>").click();
var someOtherName = "abc";
var element = document.getElementById("ctl30_txtTextBox");
element.Value = someOtherName;
alert(element.value.toString());
},
error: function(request, status, error) {
alert("Error attaching barcode file.");
}
});
Im getting the element, but the value is never set.
If i set a value on the page the alert is displayed with the correct value.
What am i doing wrong?

Javascript is case-sensitive, so it should be:
var element = document.getElementById("ctl30_txtTextBox");
element.value = someOtherName;

element.Value
that
v
is in lowercase. Javascript Value method name is .value method not .Value

You can use jQuery to do it:
$('#ctl30_txtTextBox').val(someOtherName);
It should work.

Related

ASP.NET - Set DropDownList's value and text attributes using JS

I have a Dropdownlist control in one of my ASCX page.
<asp:DropDownList ID="demoddl" runat="server" onchange="apply(this.options[this.selectedIndex].value,event)" onclick="borderColorChange(this.id, 'Click')" onblur="borderColorChange(this.id)" CssClass="dropDownBox" DataTextField="EmpName" DataValueField="EmpID">
My objective is to fill this Dropdownlist with 'EmpID' as value attribute and 'EmpName' as text attribute.
JS code to fetch these 'EmpName' and 'EmpID' values are as follows :
$(document).ready(function ()
{
loadSavedFreeTextSearchCombo();
}
function loadSavedFreeTextSearchCombo() {
var params = {
loginID: $('#loginID').val()
};
var paramsJSON = $.toJSON(params);
$.ajax({
type: "POST",
url: _WebRoot() + "/Ajax/EmpDetails.asmx/GetEmp",
data: paramsJSON,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#demoddl').empty();
$('#demoddl').append($("<option></option>").val(0).html("--Employee Names --"));
$.each(data.d, function (index, value) {
$('#demoddl').append($("<option></option>").val(value.EmpID).html(value.EmpName));
});
},
error: function () {
showError("Failed to load Saved Search Data!");
}
});
}
Although the entire code runs without any error (the EmpDetails.asmx method returns the valid data successfully), the dropdwonlist doesn't get filled with the required data returned.
What am I doing wrong? I guess somehting's wrong at my 'success' event code
Since you're intended to use DropDownList server control ID as selector, it is necessary to set ClientIDMode="Static", especially if you're using <asp:ContentPlaceHolder> or <asp:Content> to prevent ASPX engine creating <select> element with id attribute containing dropdown's placeholder name:
<asp:DropDownList ID="demoddl" runat="server" ClientIDMode="Static"
onchange="apply(this.options[this.selectedIndex].value,event)"
onclick="borderColorChange(this.id, 'Click')"
onblur="borderColorChange(this.id)"
CssClass="dropDownBox" DataTextField="EmpName" DataValueField="EmpID">
If you cannot use ClientIDMode="Static" attribute for certain reasons (e.g. avoiding multiple <select> elements with same ID), use ClientID property of the control as selector, i.e. <%= demoddl.ClientID %>:
$.ajax({
type: "POST",
url: _WebRoot() + "/Ajax/EmpDetails.asmx/GetEmp",
data: paramsJSON,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#<%= demoddl.ClientID %>').empty();
$('#<%= demoddl.ClientID %>').append($("<option></option>").val(0).html("--Employee Names --"));
// recommended to check against undefined here
$.each(data.d, function (index, value) {
$('#<%= demoddl.ClientID %>').append($("<option></option>").val(value.EmpID).html(value.EmpName));
});
},
error: function () {
showError("Failed to load Saved Search Data!");
}
});

Changes done in ajax success not loading in page without refreshing

I have an ajax block in javascript, which does a few operations, and then changes a text box in my page.
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
var content_id = "count_" + count_id;
var votes = $(content_id ).val();
$(upvotes_id).html(votes);
//window.location.reload();
}
});
The content value is reflected only after I refresh the page. I tried setting cache parameter as false and alse the same in ajaxSetup when document is ready. Still the changes arent getting reflected. Please help.
It looks like your return variable 'data' isn't being referenced in the success function. As pointed out elsewhere, also missing an id or class reference. Try this (or any other relevant variables):
var content_id = "#count_" + data.count_id;
add hash to get value like
var votes = $('#'+content_id ).val();
i think you forgot add "#" before the id
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
var content_id = "count_" + count_id;
var votes = $('#'+content_id ).val(); // add hash for id or . for class
$(upvotes_id).html(votes);
//window.location.reload();
}
});
I am assuming upvotes_id is either id or class. Use $("#upvotes_id").html(votes) or $(".upvotes_id").html(votes) instead.same in the case of "content_id" .
I can see few issues with your code like- no '#' for referring an element.
corrections:
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
**var content_id = "#count_" + count_id;**
var votes = $(content_id ).val();
$(upvotes_id).html(votes);
//window.location.reload();
}
});
Also you have not mentioned how you are getting upvotes_id. Use # there too. You are not using the response returned in success method. Is it intended?

Image does not update when appending newly inserted row using jquery ajax

I want to insert data using ajax and show that newly inserted data in a div, but the record (i.e. image and name ) does not get updated it.
I don't want to reload page, the newly entered record should be shown without page reload, but it shows only the initial name and image.
I can't understand whats the problem. Please help. Following is the code i am using static data which is stored in a variable as an example:
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
d = new Date();
var img_name='amit.png'+'?'+d.getTime();
var s_name='Ashish';
$('#main').prepend('<img alt="client" id="p_img"><h1>'+s_name+'</h1>');
$('#p_img').attr("src", "image/Amit.png");
},
error: function (error)
{
}
});
Shouldn't the src attribute use the response/variable/generated file name?
Like this:
$('#p_img').attr("src", '/image/' + img_name);
Instead of this:
$('#p_img').attr("src", "image/Amit.png");
It can be two reasons :
the image you are prepending to the DOM is not yet in the DOM when you are trying to add the src
or the src is not existing (should be an absolute or relative path)
Try to prepend the image with the src
$('#main').prepend('<img alt="client" src="ABSOLUTE_OR_RELATIVE_PATH/image/Amit.png"><h1>Amit</h1>');
Also there is no need to create a variable s_name which you only use once.
you can done it easily by returing List of data and populating the div with ajax success result.
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
// in data you are getting your result ...
// now for ease split json format data and store in list
// m not sure about your formate so m assuming at first index it
//should be image URL so..
var res = data.split(",");
var imgSrc = res[0];
$('#main').prepend('<img alt="client" id="p_img"/>');
$('#p_img').attr("src", imgSrc);
},
error: function (error)
{
}
});

Can AJAX update a button argument?

Using AJAX, I'm able to extract a data value from a button click, but is it possible to ensure this value is passed on to an argument within another button on the same page?
test.html:
Activate
Fader
test.js:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
}
});
}
The php file connects to the database and extracts the most recent image number - it works fine and the alert box displays the correct value. So what would be the next step to ensure the "image_number" argument is updated with this 'data' value?
Cheers.
make a global variable like
windows.image_number = 0;
for AJAX function.
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
//update the global variable
windows.image_number = data;
}
});
}
Assuming that the image_number variable that you are passing to the function is a globally defined variable, you simply need to set the variable in your success callback:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
// Assuming data holds the image number you want to use for next click
image_number = data;
}
});
}

Javascript String Var + jQuery Textbox Val

Anyone know why the following code doesn't seem to work? I'm trying to append whatever is in the textbox to the URL string.
$.ajax({
type: 'POST',
url: 'http://myurl.com/something.php?myname='+$('#myname').val(),
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20;
chart.series[0].addPoint(point[0], true, shift);
chart.series[1].addPoint(point[1], true, shift);
setTimeout(requestData, 5000);
},
cache: false
});
You did not let us know what is not working. $('#myname').val() should work if you really have a myname object.
However, I could not help noticing that you are requesting via POST, but at the same time you are building a query string. Try changing the type to GET and see how it goes.
May be the value of the element contains characters that can alter the meaning of query strings, e.g. if the value begins with &asdf, the url becomes http://myurl.com/something.php?myname=&asdf. If so, try this:
$.ajax({
type: 'POST',
url: 'http://myurl.com/something.php?myname=' + encodeURIComponent($('#myname').val()), // pass via GET
// I assume there is no data to pass -- uncomment otherwise
// data: {
// name1: value1,
// name2: value2,
// },
success:
.
.
.
I would recommend using a variable instead of doing it inline like so:
<script type="text/javascript>
$(document).ready(function(){
var name = $("#myname").val();
//any validation would occur here
var posturl = "http://myurl.com/something.php?myname" + name;
$.ajax({
type: 'POST',
url: posturl,
data: data,
success: success
dataType: dataType
});
});
</script>
<body>
<input id="myname" value="John Doe" />
</body>

Categories