Why my WebMethod always returns JSON? - javascript

First my apologies if this is a noob question, it's not my area.
I have a WebMethod, which return String (string table=""). But the Ajax return function
always see that as an JSON Object looks like {"d":{...}}. My Question is WHY
I get a JSON back, even though my Ajax is expecting "text" ?
WebMethod:
[WebMethod()]
public static string TestAjax(string val)
{
string sSql = ConfigurationManager.AppSettings["GetMiToSend"];
sSql = sSql.Replace("$Company$", val);
string table = "";
try
{
DbCommand command = m_connection.CreateCommand();
command.CommandText = sSql;
command.CommandType = CommandType.Text;
DbDataReader oDataReader = command.ExecuteReader();
int count = 0;
if (oDataReader != null)
{
count = oDataReader.FieldCount;
}
table = "<table>";
while (oDataReader.Read())
{
table += "<tr>";
for (int i = 0; i < count; i++)
{
table += "<td>" + oDataReader.GetValue(i) + "</td>";
}
table += "</tr>";
}
table += "</table>";
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.Message);
}
return table;
}
My Ajax function:
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/Default.aspx/TestAjax") %>',
data: JSON.stringify(toSend),
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (data) {
alert(data);
$('div#container div#content').html(data.d).show(1000);
$('div#container div#showContent').hide();
$('div#container div#content').addClass('rwd-table');
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});

I'm pretty sure you can't return a string from a WebMethod. I tried without success to confirm my assertion. So change your code to return a json instead of a string.
MS Developer Network: How to: Use the WebMethod Attribute:
Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service.
Return a json in your WebMehod:
List<object> jsonObject = new List<object>();
jsonObject.Add(new
{
htmlTable = table
});
return (new JavaScriptSerializer()).Serialize(jsonObject);
Change your ajax to return a json:
dataType: "json"
Then access your json object and your html table:
var dataParsed = $.parseJSON(data.d);
var htmlTable = dataParsed[0].htmlTable;
// Do your actions with your htmlTable. Append to an element or other action.

Related

Cannot get data to page using Ajax with spring boot

I am not able to get the data on the page using AJAX with Spring Boot. When I try the URL on postman it gets all the values from the database, but when I type the same URL in the browser it's only showing []. I have attached my code here please help me find a solution for this problem. The list of data is taken correctly.
Controller
#RequestMapping(value = "/getEasyQuestionsBySkill/{primarySkill}", method = RequestMethod.GET, produces = { MimeTypeUtils.APPLICATION_JSON_VALUE })
public ResponseEntity<List<EasyQuestions>> getAllEasyQuestions(#PathVariable String primarySkill) {
try {
ResponseEntity<List<EasyQuestions>> responseEntity = new ResponseEntity<List<EasyQuestions>>(easyQuestionsService.getEasyQuestionsBySkill(primarySkill), HttpStatus.OK);
return responseEntity;
} catch (Exception e) {
return new ResponseEntity<List<EasyQuestions>> (HttpStatus.BAD_REQUEST);
}
}
Thymeleaf - Javascript
$("#skillSubmitBtnId").on("click",function() {
var skill_name = $(".skillCls").val();
if(skill_name == ""){
alert("Select a Primary Skill");
}else {
$.ajax({
type: 'GET',
url: '/getEasyQuestionsBySkill/{'+skill_name+'}',
dataType: 'json',
success: function(result) {
var str = '';
for(var i=0; i<result.length; i++) {
str += '<br/> Question :' +result[i].question;
str += '<br/> Primary Skill :' +result[i].primarySkill;
str += '<br/> Secondary Skill :' +result[i].secondarySkill;
str += '<br/>';
}
$("#contentDivId").html(str);
}
});
$("#errorDivId").hide();
$("#javaTableDivId").show();
}
});

Call Webmethod to Fill DropDownList

I want to fill the DropDownList via SqlQuery in webmethod. But it gives internal Server error.
Except for the error, can't I just do this in javascript?
function doldur() {
$.ajax({
url: "UserServis.asmx/ListDoldur",
type: "post",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: "{ 'sysName': 'Sudio', 'categoryID': " + 544 + " }",
success: function (data) {
var result = data.d;
alert(result);
},
error: function (requeset, status, error) {
alert(error);
}
});
}
[WebMethod(EnableSession = true)]
public static List<string> ListDoldur()
{
List<string> retList = new List<string>();
SqlConnection baglanti = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnLEO"].ConnectionString);
SqlCommand komut = new SqlCommand("select BolumAdi from emre_bolumler ", baglanti);
SqlDataAdapter da;
DataSet ds;
DataTable dt;
baglanti.Open();
da = new SqlDataAdapter(komut);
ds = new DataSet();
da.Fill(ds,"TestTable");
dt = ds.Tables["TestTable"];
for (int i = 0; i < dt.Rows.Count; i++)
{
retList.Add(dt.Rows[i].ItemArray[0].ToString());
}
return retList;
}
Yes you can.
you are sending data to the code behind method but it does not have a parameter to accept data;
I think the simplest way is to serialize your datatable and return a JSON string, not a List<string> (maybe you can do return retList.ToArray() ? not sure);
skip the dataset, just use a table. I'm not entirely sure what's going on with the loop, but I think when you serialize the data you won't have to do that (unless you have a ton of columns to avoid).
using Newtonsoft.Json;
// convert datatable to a string.
string result = JsonConvert.SerializeObject(tbl);
when the data is returned to the ajax method, create the dropdown options.

'undefined' reported when bind gridview using AJAX in C#

I want to bind the gridview using AJAX. So, for that I done client side code using AJAX and server side code as a webmethod.
Everything is working fine even I alert the data in success method at that time also data is showing but in loop I really confused that it is showing undefined in alert. So for that's why grid is not binding.
Here is my code
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data.d[i].schoolName);
}
},
failure: function () {
alert("error! try again...");
}
});
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname as [School Name] from tbl_schoolregistration", con))
{
con.Open();
object val = cmd.ExecuteScalar();
return val == DBNull.Value ? "" : (string)val;
}
First of all
ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
In this case you will have a single string.
Secondly beware of the name in your query leave it as schoolname not [School Name].
Then you have to Serialize into json and again parse into json in order to loop through objects.
Here is fully working code:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
data = JSON.parse(data.d);
for (var i = 0; i < data.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data[i].schoolname +"</td></tr>");
}
},
failure: function () {
alert("error! try again...");
}
});
[WebMethod]
public static string GetGridData()
{
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname from tbl_schoolregistration", con))
{
con.Open();
//object val = cmd.ExecuteScalar();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt); // fills data from select query
// return val == DBNull.Value ? "" : (string)val;
return JsonConvert.SerializeObject(dt);
}
}

Ajax request inside loop, page reload after completion

I m using Jquery ajax request inside loop, all goes well till the last request. but after last request, page automatically reloads.I m not being able to understand what is happening there.
Plz review and help.
I m using asp.net web form and web services for handling ajax request.
Jquery Code:
var mainData = GetFromExcel();
function StartSaving()
{
for (i = 0; i < totalCount; i++)
{
DoPost(i);
}
}
function DoPost(i)
{
var mainCode = MainData[i].MainCode;
var noOfAllot = MainData[i].NoOfAllotment;
var CompanyCode = MainData[i].CompanyCode;
console.log(mainCode +' Company Code:'+ CompanyCode+':' + noOfAllot);
$.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'" + noOfAllot + "',CompanyCode:'" + CompanyCode + "'}", // the data in JSON format. Note it is *not* a JSON object, is is a literal string in JSON format
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "Post",
async: false ,
success: function (res) {
console.log(res);
},
error: function (res) {
}
});
}
GetFromExcel is function that takes excelsheet and convert into json array. for that i have used xlsx.js
WebServices Code:
[WebMethod]
public String DoAllotment(string MainCode, string sNoOfAllotment, string CompanyCode)
{
JavaScriptSerializer js = new JavaScriptSerializer();
if(checkData())
return "Error";
else
return "Success";
}
this is a common pitfall.
Modify your javascript method to return false, see below:
function StartSaving() {
for (i = 0; i < totalCount; i++) {
DoPost(i);
}
return false; //This is important for not allowing button click post back
}
In The asp.Net button add OnclientClick as shown below:
<asp:button ..... OnClientClick="return StartSaving();"></asp:button>
***Everything else is perfect in your code!!!!

JSON call returning 'undefined'

I am relatively new to using JSON and have run into an issue that I can't seem to resolve. I have set up a generic handler (detailed below), and also a page with a JSON call to get the response from the handler and render it.
The page with the JSON call is:
<script type="text/javascript">
$(document).ready(function () {
triggerCall();
function triggerCall() {
$.ajaxSetup({
type: 'POST',
headers: { "cache-control": "no-cache" }
});
$.ajax
(
{
type: "POST",
url: "Services/DepartmentListHandler.ashx",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (data) {
alert(data.msg);
displayDirectory(data.msg);
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
}
);
}
function displayDirectory(dirlist) {
var tablestring = '<table class="centered-table"><tr><td colspan="2">';
tablestring = tablestring + "<tr><td><u>DeptCode</u></td><td><u>HeaderText</u></td></tr>";
for (var i = 0, len = dirlist.length; i < len; ++i) {
tablestring = tablestring + "<tr>";
tablestring = tablestring + " <td>" + dirlist[i].DeptCode + "</td>";
tablestring = tablestring + " <td>" + dirlist[i].HeaderText + "</td>";
tablestring = tablestring + "</tr>";
}
tablestring = tablestring + "</table>";
$('#divDirectoryList').html(tablestring);
}
});
</script>
<div id="divDirectoryList"></div>
And the handler method is:
Public Class DepartmentListHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim json = New JavaScriptSerializer()
Dim lst As New List(Of DepartmentList)
Dim cls1 As New DepartmentList(1, 0, "DEP1", "Header", 1, True, False)
lst.Add(cls1)
Dim serialisedList As String = json.Serialize(lst)
context.Response.ContentType = "application/json"
context.Response.Write(serialisedList)
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
All the seems to happen is that the alert in the 'success' branch returns 'undefined' each time, and the table is not rendered at all.
Can anyone see where I'm going wrong?
Many thanks!
I think the json data that you are serializing in our code is incorrectly formatted. json data to show as "data.msg" must be received as
{
msg: 'some message',
data:'some data'
};
Actually on client side you will get [object Object] collection of object ,that object contain the your list of objects.
Print
console.log('data',data); and see in the fire fox.
you can simply get as
data[0].msg;
data[0].id;
or you can iterate the java script object with jquery then get as below
data.msg;
data.id

Categories