I\'m trying to learn how to make a simple call to the server from Javascript/jQuery. I\'ve been trying to learn and could not find a tutorial with those simple steps.
Here sample code using jquery ajax call and on serverside webmethod returns jSon format data. Jquery :
$(‘#myButton’).on(‘click’,function(){
var aData= [];
aData[0] = “2010”;
aData[0]=””
var jsonData = JSON.stringify({ aData:aData});
$.ajax({
type: "POST",
url: "Ajax_function/myfunction.asmx/getListOfCars", //getListOfCars is my webmethod
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response.d)) {
console.log(response.d)
}
function OnErrorCall(response)) { console.log(error); }
});
Codebehind : Here a webmethod which is returning json format data i.e list of cars
[webmethod]
public List<Cars> getListOfCars(list<string> aData)
{
SqlDataReader dr;
List<Cars> carList = new List<Cars>();
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "spGetCars";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("@makeYear", aData[0]);
con.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
string carname=dr[“carName”].toString();
string carrating=dr[“carRating”].toString();
string makingyear=dr[“carYear”].toString();
carList .Add(new Cars{carName=carname,carRating=carrating,carYear=makingyear});
}
}
}
}
return carList
}
//Created a class
Public class Cars {
public string carName;
public string carRating;
public string carYear;
}
Blog Article:
If you are using jQuery you could do it with a GET or POST.
$.get ('<url to the service>',
{ dateParam: date, stringParam: 'teststring' },
function(data) {
// your JSON is in data
}
);
$.post ('<url to the service>',
{ dateParam: date, stringParam: 'teststring' },
function(data) {
// your JSON is in data
}
);
Note that the name of the parameters in (e.g. dateParam, stringParam) need to be the same as the name of the parameters your service method is expecting. Also that your service will need to format the result as JSON, the data parameter in the call back will contain anything your service sends back (e.g. text, xml, json, etc).
See the jQuery documentation for $.ajax, $.get, $.post: http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.get/, http://api.jquery.com/jQuery.post/
There are several ways that you can do this; this will serve as a single example.
You could write something like this for your jQuery code:
urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function(data) {
setAutocompleteData(data.responseDateTime);
},
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
Next, you need to create a "generic handler" in your ASP.net project. In your generic handler, use Request.Form
to read the values passed in as json. The code for your generic handler could look something like this:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
string stringParam = (string)Request.Form["stringParam"];
// Your logic here
string json = "{ \"responseDateTime\": \"hello hello there!\" }";
context.Response.Write(json);
}
See how this work out. It will get you started!
Update: I posted this code at the CodeReview StackExchange: https://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example