Reputation: 67
Can someone show me how to pass a variable from a $.ajax() call to an ASMX Web Service?
Web Service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
public class Psyience
{
public int ID;
public string Choice;
public string First;
public string Last;
public string Email;
}
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
[System.Web.Script.Services.GenerateScriptType(typeof(Psyience))]
public class CRUD : System.Web.Services.WebService
{
[WebMethod]
public Psyience[] Anchor()
{
List<Psyience> items = new List<Psyience>();
string constr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["myConString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select Choice from tbl_Psyience WHERE Choice = 'Anchor'";
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Psyience item = new Psyience();
item.Choice = dr["Choice"].ToString();
items.Add(item);
}
con.Close();
return items.ToArray();
}
catch
{
return null;
}
}
}
And here's the jQuery:
$(document).ready(function () {
$.ajax({ type: "POST",
url: "Services/CRUD.asmx/Anchor",
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = response.d;
var myRecord = "";
$.each(result, function (index, res) {
myRecord = res.Choice;
$('#myDiv').append(myRecord);
});
},
error: function (msg) {
$('#myErr').html("Error while calling web service,,")
}
});
});
I'd like to pass a string value from the jQuery to my command text in my web service.
"select Choice from tbl_Psyience WHERE Choice = 'passVarToHere'"
Not sure how to accomplish this.
Thanks in advance.
Upvotes: 0
Views: 1878
Reputation: 548
and ofcourse, the 'choice' variable can take value from a textbox control like so:
var passvartoHere = $("#txtbox").val();
EDIT: my solution to be used in conjunction with the solution already posted above.
Upvotes: 0
Reputation: 55740
You do that in the data attribute of your ajax Request
data: { 'Choice' : yourchoice }, // Yourchoice in string
And your WebMethod will take in a string argument
public Psyience[] Anchor(string Choice)
{
Upvotes: 1