Passing the HTML table to JSON via Server side causing error - c#

I've a dynamically created HTML table in the Server side code(using C#). When i pass that to client site using JASON. I couldn't able to receive that code in the client site. this is my code in the Server Side.
$.ajax({
type: "POST",
url: "ExcelUpload.asmx/UploadFile",
data: JSON.stringify({ XML: XMLDoc}),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#Status").html("<br><center><img src='ajax-loader.gif'/></center>");
},
success: function (result) {
var output = "";
var re = eval('(' + result.d + ')');
if (re.length > 0) {
for (var i in re) {
var xl = re[i];
switch (parseInt(xl.status)) {
case 1: { output = xl.message; break; }
case 2: { output = xl.message; break; }
}
}
$("#Status").html(output);
}
},
error: function (result) {
$("#Status").addClass("error");
$("#Status").html(result.d);
}
});
In that server side code I'm generating the HTML table using this code
HTML += "<table id='excelDoc'>";
HTML += "<tr><th>Date</th><th>Description</th><th>Reference</th><th>Nominal Code</th><th>Dept Code</th><th>Debit</th><th>Credit</th></tr>";
HTML += "<tr><td>" + eDoc.posting_Date.ToShortDateString() + "</td><td>" + eDoc.Description + "</td><td>" + eDoc.Ref_Number + "</td><td></td><td></td><td class='db'></td><td class='cr'></td></tr>";
HTML += "";
status = "{status : 1 , message : " + HTML + "}";
return " ["+ status+ "]";
Please Help me.

why are you doing result.d ?
Should it not be simply result ?
1 thing I notice more, in your AJAX request, your
dataType: "json"
but you are returning a simple string. Change to
dataType:"text"
and then try returning the string. It would def work

Related

jqplot - pass variable via ajax to C# page

I am unable to retrieve values passed by $.ajax on my c# page.
I am using jqplot and I want to pass two pieces of information. One is stored in a hidden field called 'hidden_plateid' and the second piece of information is from a dropdown box called 'SampleNumberList'
This is the hidden field
<input type="text" name="hidden_plateID" id="hidden_plateID" hidden="hidden" runat="server" />
And this is the drop down box:
<select name="SampleNumberList" class="DropDownBox_editjob" id="SampleNumberList">
<option value="--SELECT--"></option>
<option value="001r">001r</option>
<option value="002r">002r</option>
</select>
I simply then say that everytime, someone selects from the dropdown box, to get and get the information from the db and plot the graph
$('#SampleNumberList').on('change', function (e) {
var ajaxDataRenderer = function (url, plot, options) {
var ret = null;
$.ajax({
data: {
PlateID2: options.PlateID,
SampleID2: options.SampleID,
},
async: false,
url: url,
dataType: "json",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
return ret
};
var jsonurl = "SpectraData.aspx";
var plot2 = $.jqplot('chartdiv', jsonurl, {
title: "AMIRA",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl, PlateID: $('#hidden_plateID').val(), SampleID: $('#SampleNumberList').val()
}
});
});
I use Request.Querystring to try and retrieve the value in the c# file but so far, I get nothing
if (Request.QueryString["PlateID2"] != null)
{
PlateID = Request.QueryString["PlateID2"].ToString();
}
if (Request.QueryString["SampleID2"] != null)
{
SampleID = Request.QueryString["SampleID2"].ToString();
}
You are trying to retrieve values from a query string , yet you are passing the parameters as json.
In order to retrieve them as a query string params, you need to pass them along your url.
$.ajax({
async: false,
url: url + "?PlateID2=" + options.PlateID + "&SampleID2=" + options.SampleID + "",
dataType: "json",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
In reality, the right way to do this is to pass params as a json string and intercept in the code behind.
$.ajax({
url: url/Somemethod,
type: 'POST',
dataType: 'json',
data: "{'PlateID2':'" + options.PlateID + "','SampleID2':'" + options.SampleID + "'}",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
In your codebehind :
[WebMethod]
public static void Somemethod(string PlateID2,string SampleID2)
{
}

Strange json response bact to jQuery [duplicate]

So here is my problem. I'm using Jquery's $.ajax to pass back a series of values to a web method. The web method takes the values, creates an object and then sends it back as json to the calling page. Once I get the response back I am unable to access the response and display it's values.
Can anyone explain what I need to do to make this work?
The jquery script:
$(document).ready(function() {
$("#create").click(function() {
var name = $('#name').val();
var company = $('#company').val();
var location = $('#location').val();
var phonenumber = $('#phonenumber').val();
var country = $('#country').val();
$.ajax({
type: "POST",
url: "WebService.asmx/MakeEmployee",
data: "{name:'" + name +
"',company:'" + company +
"',location:'" + location +
"',phonenumber:'" + phonenumber +
"',country:'" + country +
"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg.d);
}
});
});
function AjaxSucceeded(data) {
//var item = jQuery.parseJSON(data) // this doesn't work for me.
$("#response").html(
"<ul><li> " + data.Name +
"</li><li> " + data.Company +
"</li><li> " + data.Address +
"</li><li> " + data.Phone +
"</li><li> " + data.Country +
"</ul> "
);
};
});
The web method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string MakeEmployee(string name, string company,
string location, string phoneNumber, string country)
{
Employee e = new Employee(name, company, location, phoneNumber, country);
return new JavaScriptSerializer().Serialize(e);
}
And the response that I'm getting back:
{"d":"\"Name\":\"bob\",
\"Company\":\"google\",
\"Address\":\"home\",
\"Phone\":\"123\",
\"Country\":\"usa\"}"}
This is what I think I should be getting back:
{"Name":"bob",
"Company":"google",
"Address":"home",
"Phone":"123",
"Country":"usa"}
The error I get once the pages renders again is this:
•undefined
•undefined
•undefined
•undefined
•undefined
Your response will already be parsed as JSON, so it's already an object...no need to parse it again just use it directly, like this:
function AjaxSucceeded(data) {
$("#response").html(
"<ul><li> " + data.Name +
"</li><li> " + data.Company +
"</li><li> " + data.Address +
"</li><li> " + data.Phone +
"</li><li> " + data.Country +
"</ul> "
);
}
The { d: ... } wrapper is added by ASP.Net, that's normal behavior. After that your issue is the element not returned correctly, you need to return an object not a string from ASP.Net, preferably this:
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Employee MakeEmployee(string name, string company,
string location, string phoneNumber, string country) {
return new Employee(name, company, location, phoneNumber, country);
}
...where Employee has the properties you want on the JavaScript side. Let ASP.Net handle the serialization here instead of doing it directly, you'll get a cleaner response overall.
Try using this ajax initaliazer function for asp.net ajax. It sets most defaults so you only have to supply url/params
Just call in your document.ready() function first, and then your calls.
function jqueryInit() {
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function (data) {
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
});
}
Start by cleaning your service method. You really don't need this constructor and all those properties. You already have an Employee type, so use it:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Employee MakeEmployee(Employee e)
{
// Maybe do something more useful here with this employee
// like raise his salary
return e;
}
And then clean your javascript:
$.ajax({
type: 'POST',
url: 'WebService.asmx/MakeEmployee',
data: JSON.stringify({
// All those correspond to Employee properties you would like to pass
Name: $('#name').val(),
Company: $('#company').val(),
Location: $('#location').val(),
PhoneNumber: $('#phonenumber').val(),
Country: $('#country').val()
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// msg.d is gonna be the returned employee
AjaxSucceeded(msg.d);
}
});

ajax call to web method does not working

i have this ajax call
function findPICKey() {
filter = document.getElementById('MainCT_dtvJobVac_PIC').value;
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: "{listuser:" + JSON.stringify(resultarr) + ", keyword:'" + JSON.strigify(filter)+ "'}",
dataType: 'json',
url: 'SvcAutoComplete.asmx/GetPICKey',
success: function (result) {
result = JSON.parse(result.d);
document.getElementById('<%= dtvJobVac.FindControl("PICKey").ClientID %>').value = result;
},
error: function (result) {
alert("error getting pic key");
}
})
}
web method
[WebMethod]
public string GetPICKey(List<BO> listuser, string keyword)
{
//List<BO> ListObj = new List<BO>();
//ListObj = (List<BO>)Session["ListPIC"];
//ListObj = listuser;
//string key = string.Empty;
//for (int i = 0; i < ListObj.Count; i++)
//{
// if(ListObj[i].label == keyword)
// {
// key = ListObj[i].value;
// break;
// }
//}
//return key;
return "";
}
for some reason my web method not called, i put a break point, but it does not triggered, what i do wrong here? btw resultarr is an object.
Just checking, but you know your second stringify is spelt wrong?
"JSON.strigify" :)
if you call webservice from localhost, you should check url
eq:
http://localhost/HenryChunag/SvcAutoComplete.asmx
url should be :
url: '/HenryChunag/SvcAutoComplete.asmx/GetPICKey'
I think problem is in
data: "{listuser:" + JSON.stringify(resultarr) + ", keyword:'" + JSON.strigify(filter)+ "'}",
it should be
data: {listuser:"+ JSON.stringify(resultarr) +" , keyword:" + JSON.strigify(filter)+ "},
or
data: {listuser:JSON.stringify(resultarr) , keyword:JSON.strigify(filter)},

How to add Items in jcarousel ? in C#

I would like to add Items in jcarousel using c# Webmethod + jquery Ajax
for that i made something like this :
my Html is like :
<div>
<ul id="mycarousel" class="jcarousel-skin-tango" style="float: left">
</ul>
</div>
Jquery code for jcarousel and Ajax Method is like this :
$("#mycarousel").empty();
var element =jQuery('#mycarousel');
$.ajax({
url: "Home.aspx/GetProjectData",
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: "{}",
async: false,
success: function (response) {
if (response.d != null) {
//$.each(response.d, function (i, response) {
$("#mycarousel").html('response.d');
element.jcarousel(
{
pager: true,
visible: 6
});
}
else {
}
},
error: function (xhr) {
}
});
and webmethod is like this :
[WebMethod]
public static List<string> GetProjectData()
{
// here i have 3 list in returnvalue
foreach (var item in returnvalue)
{
var classvalue = item.Soid + "|"
+ item.ProjectTitle + "|"
+ item.Role + "|"
+ item.StartDate + "|"
+ item.EndDate + "|"
+ item.Location.Country + "|"
+ item.Location.State + "|"
+ item.Location.City + "|";
string Template = "<li><img src='../Images/DefaultPhotoMale.png' class='"+ classvalue + "' width='40' height='40' alt='image'/></li>";
list.Add(Template);
}
return list;
}
but problem is , i am not able to images in jcarousel , i only see white box, i am not able to seee images inside, why ?
I'm not sure but wouldn't you need to append the elements sort of like this:
var listItem = $(response.d); //I'm guessing reponse.d is your returned li
element.append(listItem);

Passing parameter to controller function from jQuery function '$.ajax'

I am using ASPNET MVC 2.0. I'm trying to pass a value from View to Controller function using jquery function .ajax. My jquery function is:
$(document).ready(function() {
$("#Search").click(function(event) {
var searchString = $("#TraderSearch").val();
$.ajax({
type: 'POST',
url: '/Build/SearchTrader',
data: "{strData : '" + searchString + "' }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(ResultList) {
var contents = "";
var count = 0;
$(ResultList).each(function() {
contents = contents + '<tr><td>' + ResultList[count].Name + '</td><td>' + ResultList[count].Value +
'</td><td><a class="edit"><img src="../../html/images/Edit.gif" width="14" height="14" alt="edit" /></a></td></tr>';
count = count + 1;
});
$("#SerachResultList").append(contents);
alert("{strData : '" + searchString + "' }");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + "\n" + errorThrown);
}
});
});
});
And my Controller function is as follows:
public ActionResult SearchTrader(string strData)
{
//Function to search DB based on the string passed
return Json(lstDictObject);
}
My problem is that, I am not able to get the value in my controller. I'm getting strData as 'null'. I think there is somme mistake in the way i'm trying to pass the value? Can anyone correct me?
Thanks in Advance,
Vipin Menon
try this:
data: "strData = " + searchstring
I believe the following should work:
data: { strData: searchstring }
Quotes caused the same issue in the script I just tested.
You also need to check the spelling on your "#SerachResultList" if this is your actual code.

Categories