Autocomplete JQuery is not working - c#

Merged with jQueryUI Autocomplete Plugin not working.
I am NEW in JQ stuff. So basically I have a simple textbox in which I want user to search some items. I am using JQ for this. I read this link which implements this example:
http://aspnetnova.blogspot.com/2009/06/simple-jquery-ajax-server-side.html
Here is my code:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<style type="text/css">
.login
{}
</style>
<script type ="text/javascript">
var data = "";
$(document).ready(function () {
$("#tbSearch").click(function () {
$.ajax({
type: "POST",
url: "AgentList.aspx/LoadData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
data = msg.d.split(" ");
$('#<%= tbSearch.ClientID %>').autocomplete(data);
}
});
});
});
</script>
</asp:Content>
<asp:TextBox ID="tbSearch" runat="server" ontextchanged="tbSearch_TextChanged"></asp:TextBox>
Here is my code behind:
#region "Auto Complete"
[System.Web.Services.WebMethod]
public static string LoadData()
{
return "S M SMI SM A ABC ABCD ABCI";
}
#endregion
What I am doing wrong here?

Related

Can't send a basic, non MVC form using ajax in .Net (C#)

I have seen answers to this question many times, but most of them are related to MVC controllers.
The issue I am having while trying to send a form using Ajax is that while in debug mode, the execution flow won't reach the break point I have in my code behind. Also, I notice that when I click in the submit button, the page refreshes very quickly; I though that the whole idea of ajax was to not refresh the page.
This is my index.aspx
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="ajaxform.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset class="fs1">
<input id="inputData" tabindex="1" name="theinputData" class="field" placeholder="Paste URL, docId or docSetId" runat="server"/>
<input id="form1Send" type="submit" class="button" onclick="submit()"/>
</fieldset>
</div>
</form>
</body>
Here is the code of my ajaxform.js
$(document).ready(function () {
$('#form1').submit(function (e) {
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
e.preventDefault();
});
});
Finally, here is my code behind
namespace mySpace
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string OnSubmit()
{
return "I was in code behind";
}
}
}
My break point is on the return line. Why the program never reach the WebMethod?
There are a couple of issues with your code:
You're double declaring something to handle the form. Your form1send button has onclick="submit()" in it as well as the form submit handler you're wiring up via jQuery
The content of your JavaScript handler is slightly off, for example you set contentType twice.
Here's a simplified version of the JavaScript that works on my machine:
$(document).ready(function () {
$('#form1').submit(function (e) {
$.ajax({
type: "POST",
url: "index.aspx/OnSubmit",
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
}
});
e.preventDefault();
});
});
NOTE: I based this (the content of the $.ajax call) on a code sample I found elsewhere, which is why the parameters and order of the parameters are different to yours.
If your app has a RouteConfig.cs file present, you may also need to change settings.AutoRedirectMode = RedirectMode.Permanent; to settings.AutoRedirectMode = RedirectMode.Off; if you see an HTTP 401 error in your browsers developer tools console for the request to your WebMethod decorated method in index.aspx.
By executing event.preventDefault() before FormData(this) a premature refresh is prevented.
See below:
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
});
});

passing bulk array values to codebehind(cs) using ajax

I have to pass bulk array values to code behind (cs) using ajax i had researched a lot and used this code but it didnot worked for me below is the code that i used what i need is i need to pass bulk array values in code behind(cs) using ajax
JS
<head runat="server">
<title></title>
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace PassingValueFromJavascriptToCs
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
// Do whatever processing you want
// However, you cannot access server controls
// in a static web method.
}
}
}
First of all the button for aspx is sending your aspx form to a postback so that you would need to change the aspx like this
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
The reason the foo method returns false that you dont want to make your button start a postback. I also added another property UseSubmitBehavior="false" to guarantee it.
The scripts section i changed the values object to a real array and then when sending data , i converted it to json with values object inside. This code will work in your example just fine
Edit : For the working version on my tests
The aspx page (trimmed details to the master page)
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
function test() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/test", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
debugger;
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
<asp:Button ID="Button3" UseSubmitBehavior="false" OnClientClick="return test();" runat="server" Text="Deneme" />
</asp:Content>
The RouteConfig and original method
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}
Well at least one issue is your url is "Default.aspx/Done" but the method appears to be on WebForm3.aspx/Done.
What actually happens with your code? Does it error?

Call asp.net function from javascript function

I want to call asp.net function from a javascript function passing string value.
this is the asp.net function :
[System.Web.Services.WebMethod]
public static string InsertData(string ID)
{
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
using(SqlConnection con = new SqlConnection(source))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con)) {
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
return "True";
}
}
}
So i want to call this function from javascript function which passes the string value "ID" to the the asp.net function.
this is the javascript function i use
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Errorrr');
}
and i call it from here
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
so i have a button and onClick i want to add "Hello" Row to my table but nothing happens and CallError function calls
You can call web method from ajax call in javascript . you need to set url parameter values to function you want to call and you can pass value in the data prameter in json formate.
like this data:"{ParamterName:'VALUE'}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/YouPageMethod",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Method Called Sucess fully');
},
error: function (result) {
alert("error " + result);
}
});
});
</script>
OR
you can call using PageMethod Eample
<script type="text/javascript">
function callInsert() {
PageMethods.InsertDate(id, OnSucceeded, OnFailed);
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
/* call this javascript function */
callInsert();
</script>
You will need to include Jquery first in your page. Then you need to add the following Javascript code.
<script type="text/javascript">
var id ="5"; //your id will be stored here
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/InsertData" + "&?id=" ,
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Success');
},
error: function (xhr, request, status) {
alert(xhr.responseText);
}
});
});
</script>
You need to have scriptManager in your .aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
After that you can call the method using
<script type="text/javascript">
function func(){
PageMethods.InsertData(id,success_msg,failure_msg);
}
</script>

Jquery Auto complete extender not working after postback

Im using jQuery Autocomplete using Web Service in ASP.Net.I've used the autocomplete to filter employeecode.When the page loads autocomplete works fine,but after when i click the search button autocomplete is not working properly.
I think the problem lies in document.ready function,so when the page loads it works fine,But i've to use autocomplete after the buttonclick event also.
How can i do this ???
Heres my jQuery Autocomplete
<link href="../AutoComplete/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../AutoComplete/jquery.min.js" type="text/javascript"></script>
<script src="../AutoComplete/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
});
</script>
Markup
<td align="right">
<asp:Label ID="lblEmpCodeSrch" runat="server" Text="EmpCode" CssClass="label"> </asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmpCodeSrch" runat="server" Width="250px" ToolTip="Enter Employeecode"></asp:TextBox>
<asp:Button ID="bttnSearch" runat="server" CssClass="submit" Height="23px" Text="Search" onclick="bttnSearch_Click" />
</td>
ButtonSearch Codebehind
protected void bttnSearch_Click(object sender, EventArgs e)
{
clsEmp.EMPLOYEEID =txtEmpCodeSrch.Text.Trim()==""? 0:Convert.ToInt32(hFieldEmpId.Value);
DataTable dtEmp = clsEmp.GetDetails();
if (dtEmp.Rows.Count > 0)
{
hFieldEmpId.Value = "";
// txtEmpCodeSrch.Text = "";
if (ViewState["Sort"] != null)
{
DataView dView = new DataView(dtEmp);
dView.Sort = ViewState["Sort"].ToString();
gdView.DataSource = dView;
gdView.DataBind();
}
else
{
gdView.DataSource = dtEmp;
gdView.DataBind();
}
}
}
When you have an UpdatePanel, after the update of the data, you also need to re-initialize the javascript, because the old one is not longer working, because the struct of your html page have change, the dom have change.
The UpdatePanel is giving some function to do that on client side, and your code will be as:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Place here the first init of the autocomplete
InitAutoCompl();
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel re-init the Autocomplete
InitAutoCompl();
}
function InitAutoCompl() {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
}
</script>
I tell you that I could solve the problem by adding a Triggers within the UpdatePanel tag, thus achieves the desired behavior in my case. I hope you can serve you as me helped me.
<ajax:UpdatePanel>
<ContentTemplate>
//My label fire autocomplete
<asp:TextBox id="MyLabelForAutoComplete" runat="server"/>
// Other Html Tags...
<Triggers>
<ajax:PostBackTrigger ControlID="MyLabelForAutoComplete">
</Triggers>
</ajax:UpdatePanel>

Ajax method call

I am trying to call a simple method in my code behind using Jquery with Ajax. But I get a 404 not found exception everytime. Unfortunately this is a web forms solution. So I dont have all the perks of MVC :(
It does get into the javascript method and gives the alert but won't go into my c# method. My previous experience of using this Jquery method is in an MVC website. Is it compatible with webforms sites?
My Javascript is:
$(document).ready(function() {
$('#btn_<%=UserStuff.tag %>').click(function() {
var value = $('#<%#Eval("tag") %>twink').val();
something(value);
});
});
function something(theval) {
alert(theval);
$.ajax({
type: "POST",
url: "/Default.aspx/MyMethod?something=" + theval,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
}
}
And my C# code is:
public JsonResult MyMethod(string something)
{
JsonResult ret = new JsonResult();
return ret;
}
Thanks in advance.
Your method returns JsonResult. This is MVC specific and you cannot use it in a webforms application.
If you want to call methods in the code behind in a classic WebForms application you could use PageMethods:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
And then to call the method:
$.ajax({
type: 'POST',
url: 'PageName.aspx/GetDate',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// Do something interesting here.
}
});
And here's a full working example I wrote for you:
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
[WebMethod]
public static string SayHello(string name)
{
return "Hello " + name;
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'default.aspx/sayhello',
data: JSON.stringify({ name: 'John' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
// Notice that msg.d is used to retrieve the result object
alert(msg.d);
}
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
</form>
</body>
</html>
PageMethods are not limited to simple argument types. You could use any type as input and output, it will be automatically JSON serialized.

Categories

Resources