JSON call returning 'undefined' - javascript

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

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();
}
});

Need Help Diagnosing This Ajax Request Call

Need Help Diagnosing This Ajax Request Call.
filtered text is a text box from an input box further up the page , with filters is a Boolean checking if the user wants to search for anything at all and filtered text is what the user would like to filter by.
function GetData(torf) {
var watever = { "withfilters": torf, "filteredtext": $('#SortOrdersBy2').val() };
$.ajax({
url: '/WebService.asmx/GetData',
method: 'post',
dataType: 'json',
data: JSON.stringify(watever),
contentType: "application/json; charset=utf-8",
success: function (data) {
var employeeTable = $('#datatable tbody');
var employees = data;
for (i = 0; i < employees.length; i++) {
employeeTable.append('<tr><td>' + employees[i].CustomerId + '</td><td>' + employees[i].CustomerName + '</td><td>' + employees[i].Engineer + '</td></tr>');
}
},
error: function (err) {
alert("ERROR");
}
});
}
It Goes to this web service code and runs through it on load but still displays the error function.
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)
{
string connectionString = ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString;
List<Data1> Data = new List<Data1>();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand query = new SqlCommand
(withfilters ? "SELECT * FROM MainTable CustomerId LIKE '%" + (filteredtext) + "%' OR CustomerName LIKE '%" + (filteredtext) + "%' OR Engineer LIKE '%" + (filteredtext) + "%')"
: "SELECT * FROM MainTable",con);
SqlDataReader rdr = query.ExecuteReader();
while (rdr.Read())
{
Data1 data = new Data1();
data.CustomerId = Convert.ToInt32(rdr["CustomerId"]);
data.CustomerName = rdr["CustomerName"].ToString();
data.Engineer = rdr["Engineer"].ToString();
Data.Add(data);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(Data);
}
Any Help Would be greatly Appreciated, need more info let me know.
In your webservice you have set the UseHttpGet=true which means that this method can be executed using Http GET request not POST
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)
However, in javascript you are trying to execute the method using POST from client-side
$.ajax({
url: '/WebService.asmx/GetData',
method: 'post',
dataType: 'json',
SOLUTION:
Remove the HttpGet=true from ScriptMethod attribute:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)

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!!!!

Sending json from Javascript to Javascript

I have a js inside a jsp from where I want to send a json in another js.
In jsp the console.log(html_out); prints the json right.
$.ajax({
//ajax code
},
async: true
})
.done(function(html_out) {
console.log(html_out);
drawTable(html_out);
})
Output for console.log(html_out):
{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }
But, in js the json doesn't put the data right inside the table i want to put them. The console.log(rowData); displays :
{
t
i
t
l
e
:
"
h
...
...
Here is my code in the js that i want to print my json:
function drawTable(data){
for (var i=0; i<data.length; i++){
drawRow(data[i]);
}
}
function drawRow(rowData) {
console.log(rowData);
var row = $("<tr />")
$("#farmacyDataTable").append(row);
row.append($("<td>" + rowData.title + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
}
As mentioned by dfsq, you have to parse the JSON string into a JavaScript object, right now you are iterating over the string
$.ajax({
//... ajax code
async: true, // Not needed, it default to async: true, async:false is deprecated
// If you add the line below, you don't need to parse the response
// dataType: 'json'
})
.done(function(html_out)
drawTable(JSON.parse(html_out));
})
If you correctly set the MIME type for the response (on the server), you will not need to call JSON.stringify
http://api.jquery.com/jquery.ajax/
dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
var parsed = JSON.parse(html_out);
drawTable(parsed);
Please take a look at the JSON.parse MDN page for browser compatibility.
I made some corrections to your code, you can play with it here: https://jsfiddle.net/mzf4axc0/
var jsonData=[{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }];
function drawTable(data){
for (var i=0; i<data.length; i++){
drawRow(data[i]);
}
}
function drawRow(rowData) {
console.log(rowData);
var row = $("<tr /><td>" + rowData.title + "</td><td>" + rowData.name + "</td>" + "</tr>");
$("#farmacyDataTable").append(row);
}
$(document).ready(drawTable(jsonData));

Why my WebMethod always returns JSON?

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.

Categories