I'm trying to call a server side method, using jquery, on the textchange event of a textbox which is generated dynamically on the clientside (I dont know how to fetch the id of this). Can somebody help me to do this stuff? The script im using is as follows:
<script type="text/javascript">
$(init);
function init() {
$('#test').droppable( //Div Control where i'll be dropping items
{
drop: handleDropEvent
});
$('a').each(function(idx, item) {
$(item).draggable({ cursor: 'move', helper: 'clone' })
});
}
function handleDropEvent(event, ui) {
var draggable = ui.draggable;
document.getElementById('test').innerHTML += addColumn(draggable.attr('text')) + '<br>';
}
$('.textChangeClass').live('change', function() {
/* Evokes on the text change event for the entire textboxes of class .textChangeClass. Is it possible to specify the dynamic textbox generated # clientside here? (like for e.g. : $('#mytextbox').click(function () ) */
$.ajax({
type: "POST",
url: "Webtop.aspx/ServerSideMethod", //This is not getting called at all.
data: "{'param1': AssignedToID}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
alert("From Server");
}
})
});
});
function addColumn(column) {
var iHtml;
//This is how i'm generating the textboxes along with a checkbox bound by a div.
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input class="textChangeClass" type="text" id="aln' + column + '"> </div>';
return iHtml
}
</script>
I think you have an extra "});" although this probably isn't the problem.
What is "AssignedToID"? Try adding single quotes around that. I seem to remember having a weird problem a couple years ago related to quoting in the json.
Can you see the request in Fiddler/firebug/etc? Is the content correct?
You should be careful of your use of inferred semi-colons too. If you ever minify your javascript (yeah, I know this is embedded, but I'd like to hope that one day it will be moved to a seperate js file) you're eventually going to have a problem. Imagine some other developer comes along, does some refactoring and needs to add a return value after the ajax call.
$.ajax({...})return foo}
EDIT
Fiddler/Firebug Net panel are your friends... They will allow you to inspect the request and the response from the server. This way you don't have to add the error handler (although you may want to for other reasons eventually)
EDIT
To answer the other part of your question, you can access the textbox for which the change event was triggered through the use of the 'this' keyword inside of the event handler.
$('.textChangeClass').live('change', function(event) {
//Note that the 'event' parameter has interesting things in it too.
var changedText = $(this).val();
alert("The value in the textbox is: '" + changedText + "'");
var data = {
param1: changedText
};
$.ajax({
...
//Using json2 library here to create json string
data: JSON.stringify(data),
...
});
});
Note that I added the optional 'event' parameter to the event handler. It has interesting things in it and it's something that is often overlooked by people who are new to jQuery. Read about it here.
You need to write you code of adding the event to textbox after generation of textbox otherwise it's not get fire.
add text box
After that write code to add event to text box or bind event to text box
just follow the above step will do your work
EDIT
Add the error function to your ajax call you will get the error ... will allow you to proceed further
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Related
I've assembled a page as a proof-of-concept for retrieving matching user names from Active Directory (via a web service on out intranet) while typing values into a text box. It works beautifully, but only on my workstation and only in IE (version 10). Every other user who has tried it gets the alert, "error", which is also what I get when I try it in Chrome. I've further verified that the other users can actually retrieve the data by pasting the web service URL directly into their browsers, so the breakdown occurs somewhere between fetching the data and displaying in the form. My only thought was that maybe there are some browser settings responsible for allowing this to work, but I really have no idea what those might be.
Here's what the code looks like:
<div>
<h1>Active Directory lookup</h1>
<input name="txtADAccount" type="text" id="txtADAccount" style="width:400px;" />
</div>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtADAccount").autocomplete({
source: function (request, response) {
$.support.cors = true;
$.ajax({
crossDomain: true,
headers: { 'Access-Control-Allow-Origin': '*' },
url: "http://fetch.mycompany.com/ADUser/ADUserByAccountOrDisplayName/" + $('#txtADAccount').val(),
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
var jsonData = JSON.parse(data);
// Filter out records where there is no email address
var jsonFiltered = jsonData.result.filter(function (row) {
if(row.mail != '') {
return true
} else {
return false;
}
});
response($.map(jsonFiltered, function (item) {
return { label: item.displayName + ' (' + item.mail + ')' }
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ': ' + errorThrown);
}
});
},
select: function (event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
$(this).val(ui.item.label);
},
minLength: 2 //minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
});
});
</script>
</body>
Just looking for some hints as to what the source of the problem might be.
UPDATE: Updating the script links to the latest versions of jquery and jquery.ui resulted in it working on at least one more workstation that didn't work previously. However, it's still not working on any other machines I've tried and the error messages displayed are not consistent. Sometimes it just displays "error", other times "error: No Transport", and other times "error: Access is Denied".
UPDATE 2: On this second workstation where I've been able to get it working, I noticed that if I log in using a different account, I get the "error: Access is denied" message. This is puzzling... to what exactly is access being denied? It's not the web service itself because any user can drop the web service URL into their browser and it will return the appropriate json data.
UPDATE 3: I just discovered that changing the contentType to "application/x-www-form-urlencoded; charset=utf-8" has resulted in it working now for several other users as well as working for me now in Chrome. It's still not working for at least two users, one using IE who gets no message whatsoever, and another who is still getting the "Access is denied" message (I may need to have them try clearing their browser cache). I'm still baffled as to why it always worked for me alone regardless of the contentType setting.
Currently I am stuck I want to return the title, plot and poster using themoviedb api I have no idea how to start the coding for this
Currently when i run a search the information is display in the console log of the browser i want to take that information and style it into a table format nothing fancy just the title and poster need help no clue where to start
doc site here http://docs.themoviedb.apiary.io/#get-%2F3%2Fsearch%2Fmovie
<html>
<head>
<title>Sample Seach</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie',
input,
movieName,
key = '?api_key=My API KEY HERE';
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+movieName ,
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
});
});
</script>
</head>
<body>
<input id="movie" type="text" /><button>Search</button>
</body>
</html>
output looks like this it returns objects under a movie title in his chase 300
error when running each staement
Something like this:
$.ajax({
url: url + mode + key + '&query='+movieName ,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.original_title + '</td><td>' + value.release_date + '</td></tr>';
});
table += '</table>';
$('.myelement').html(table);
}
});
You don't read from the console. It's just for outputting debug information. The AJAX call basically returns an JavaScript object (whose structure you can see in the the console).
Access the data from it just like from any other JavaScript object (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects if you need to learn how) and work with that.
EDIT: If you need to know how to display the data on the web page, you need to learn about the DOM. See for example: http://www.elated.com/articles/javascript-dom-intro/
I am generating
<a href="...">
dynamically in a code behind. When I click on the link it needs to run a sub from the code behind and also I need to know which link actually triggered that code behind function.
This is my code behind (dynamically generating link) which is then displayed in div. I literally dump this (below code) as a string into a div:
<a href='#'
id='" + i.MemberId.ToString() + "'
Text='Click Me'
onServerClick='Check_Clicked'
runat="server">Click Me
</a>
And this is what I need to call:
Sub Check_Clicked(sender As Object, e As EventArgs)
Me.div_result.InnerHtml = "TEST"
End Sub
UPDATE:
Okay I added the following to my project:
<script type="text/javascript">
$(document).ready(function () {
$('#inboxLink').click(function () {
$.ajax({
type: 'POST',
url: 'inbox.aspx/GetSomething',
data: '{ test1: "somevalue" }',
ContentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Fail");
}
});
});
});
</script>
and then
<System.Web.Services.WebMethod()> _
Public Shared Sub GetSomething()
Me.div_result.InnerHtml = "TEST"
End Sub
but there are more problems In the code behind
'Me' is only valid within an instance method.
so I am not sure the way I am approaching this problem might be wrong?
Generating an element at the client side with runat="server" will not make it a server control. You better implement an AJAX based architecture.
Generate your client side anchor element (I'm using jquery here)
$('<a />', {
text:'Click Me',
id:'<whatever you like>',
click:function(){ makeCallToServerWithYourData(yourData); }
}).appendTo('yourTargetDivSelector');
So that's it if you want to call a server method.
If you just want to change the content of a div when you click on the anchor tag, as in your sample code, just replace the click event handler with whatever you want.
Please mark as answer if it helped you.
Thank you :)
When I use ajax, I noticed that Jquery effects don't work. The reason is "The new HTML you're adding to the DOM (page) didn't exist when your jquery ran the first time "
another similar question
Therefore, I changed my code to following but still I don't get the jquery effects.
Where I have done the mistake?
Previous code
$("#sendemp").click(function(e) {
e.preventDefault();
var submit_val = $("#searchbox").val();
//alert('submitval is ' + submit_val);
$.ajax( {
type : "POST",
//dataType :"jason",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'employee_pimary_details',
user_name : submit_val
},
success : function(data) {
// alert('hhh');
$('#accordion21').html(data);
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
});
New code
$("button").on( "click", "#accordion3",function(){
$.ajax( {
type : "POST",
dataType : "json",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'employee_deatils_search',
user_name : submit_val
},
success : function(data) {
// alert('hhh');
$('#accordion3').html(data);
$("tr:odd").css("background-color", "#F8F8F8");
$("#accordion3").accordion({ heightStyle: "fill", active: 0 });
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
} );
I have following submit button
<input type="submit" id="sendemp" value="Search" />
I don't think your click binding is correct, if you want to handle clicks on button inside #accordion3 change it to:
$("#accordion3").on( "click", "button",function(){...});
It is hard to tell without your html, but it looks like in your old code you are replacing the sendemp button. In your new code your event delegation is incorrectly specified. You are applying delegation to a button element (which doens't exist since your sendemp button is an input element).
Apply delegate to something that is the parent of #sendemp like so:
$('body').on('click', '#sendemp', function() {
// your ajax call
});
I could fix the issue, I tried the above solution that is using on method. However, it doesn't make sense to my problem.
As following artical explain I think, Accordion is already instantiated and effects are persistance. When it is called second time, it won't create again since there is already the effects.
Therefore, I needed to destroy it and recreate accordion.
support link
I changed the code on success as follows
success : function(data) {
// alert('hhh');
$('#accordion3').accordion('destroy');
$('#accordion3').html(data);
$("tr:odd").css("background-color", "#F8F8F8");
//$("#accordion3").accordion( "disable" );
$("#accordion3").accordion({ active: 0 });
}
And out of $(document).ready(function() {
I added
$(function() {
$("#accordion3").accordion({
// heightStyle: "fill",
active: 0 });
});
I am trying to pass extra parameters through to my ashx when using Jquery UI auto complete.
I have seen lots of examples and have spent ages fiddling but I can't get mine to work.
I have two auto complete textboxes, what ever is entered in the first one needs to narrow down the search for the second one.
On my first autocomplete textbox all works fine and the ID that is returned is set to a hidden field.
$("#<%=txtSearch1.ClientID%>").autocomplete('/Search1.ashx');
$('#<%=txtSearch1.ClientID%>').result(function (event, data, formatted)
{
if (data) {
var id = data[1];
$("#<%=hdnSearched1.ClientID%>").val(id);
}
});
I want to use the value of the hidden field along with the value the user enters into the second textbox to do the search for the second auto complete
I first tried this:
$("#<%=txtSearch2.ClientID%>").autocomplete('/Search2.ashx',{
extraParams: { "Id": $("#<%=hdnSearched1.ClientID%>").val() }});
This fired my ashx but the Id in the extraparams was blank. A bit of googling told me this was because it was set when the page loaded so the value for the extra param was set before I set the value of the hidden field.
I did a bit more fiddling and searching and came up with something like this which a lot of people seem to be using.
$('#<%=this.txtSearch2.ClientID %>').autocomplete({
source: function (request, response)
{
$.ajax({
url: '/Search2.ashx',
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
term: request.term,
sId: $("#<%=hdnSearched1.ClientID%>").val()
},
success: function (data)
{
response(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert(textStatus);
}
});
}
});
The problem is this doesn't even fire the ashx! I have been fiddling about with this for ages, following example after example but I can't seem to work what I am doing wrong!
I'm sure it must be obvious!
Can anyone help?