Strange json response bact to jQuery [duplicate] - c#

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

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)
{
}

JSON-data to WebMethod using jQuery returning errors

I'm trying to send a json list populated with the id's from the 'data-seq' attribute only when the 'value' == true.
I have tried out a lot solution but it keeps getting me error messages, the most common are "there is no parameterless constructor for the type string" when using string[] or "string is not supported for deserialization of an array" when using string as code-behind parameter in the WebMethod.
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var obj = {
id: $(this).attr("data-seq")
};
json.push(obj);
});
json = JSON.stringify({ jsonList: json });
console.log(json); // {"jsonList":[{"id":"38468"},{"id":"42443"},{"id":"42444"}]} (the right id's are getting stored)
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: json,
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
// Code-Behind
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
// string: string is not supported for deserialization of an array
// string[]: there is no parameterless constructor for the type string
}
You are just sending IDs so send them as comma-separated string like this:
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var id = $(this).attr("data-seq")
json.push(id);
});
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: '{jsonList: "' + json + '" }',
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
And Code-Behind:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
List<string> ListOfIDs = jsonList.Split(',').ToList();
}

Message: Invalid JSON primitive: ajax jquery method with Webmethod

I am using Data value as object literal, instead of concatenating a String as explained in this answer
My code is the following:
$.ajax({
url: "../Member/Home.aspx/SaveClient",
type: "POST",
async: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
"projectSoid": ProjectId,
"startDate": StartDate,
"endDate": EndDate,
"clientManager": ClientManager
},
success: function(response) {
if (response.d != "") {
}
},
error: function(response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
})
and my webmethod is like this :
[WebMethod]
public static string SaveClient(string projectSoid, string startDate,
string endDate, string clientManager)
{
...
}
But I get the following error:
Message: Invalid JSON primitive: projectSoid
With your contentType: 'application/json; charset=utf-8' you are claiming that you will send JSON but currently your data property is not holding JSON.
You need to transform your data to JSON with the JSON.stringify method:
So change your data property to:
data: JSON.stringify({
"projectSoid": ProjectId,
"startDate": StartDate,
"endDate": EndDate,
"clientManager": ClientManager
}),
You should note that the JSON.stringify method is not natively supported in older browsers so you may need to provide an implementation with using one of the various libraries like:
Douglas Crockford's JSON2 library.
Javascript at Client side
var items = [{ projectSoid: ProjectId, startDate: StartDate, endDate: EndDate, clientManager: ClientManager }];
$.ajax({
url: '"../Member/Home.aspx/SaveClient',
type: "POST",
data: JSON.stringify({ items: items }),
//data: JSON.stringify("{DocKey : '" + DocKey + "',highlightText: '" + JSON.stringify(text) + "',pageNo: '" + pgNo + "',left: '" + left + "',top: '" + top + "',width: '" + width + "',height: '" + height + "'}"),
//data: "{DocKey\":\""+ DocKey+"\",\"highlightText\":\""+ text +"\",\"pageNo\":\""+pgNo+"\",\"left\":\""+left+"\",\"top\":\""+top+",\"width\":\""+width+"\",\"height\":\""+ height +"}}",
// data: "{DocKey : '" + DocKey + "',highlightText: '" + text + "',pageNo: '" + pgNo + "',left: '" + left + "',top: '" + top + "',width: '" + width + "',height: '" + height + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("Save data Successfully");
},
failure: function (msg) { alert("Sorry!!! "); evt.obj.deleteObject(); },
async: false
});
Web Method at Code behind
[WebMethod]
public static string SaveClient(object items) {
List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
Dictionary<string, object> dic = (Dictionary<string, object>)lstItems[0];
}

How to pass parameter(email ID) to a c# function from Jquery Ajax call?

I am trying to call a Web Method of service from a Jquery Ajax call.
Method accepts 3 parameter from the front end and search for the record in the DB.
I am not able to concatinate those 3 parameter properly in the Ajax call :
The Web Method is :
public bool FindRecord(string Fname, string Lname, string Email)
{
string SQL = "SELECT * FROM contactsSource WHERE (first_name ='" + Fname + "') AND (last_name = '" + Lname + "') AND (email_address_work = '" + Email +"')";
OleDbDataReader reader = DataAccess.GetData(SQL);
if (reader.HasRows)
{
return true;
}
else
{
return false;
}
}
and the Ajax call I am trying is :
<script type="text/javascript">
$(document).ready(function() {
$('#btnDownload').click(function() {
var Fname = $('#Fname').val();
var Lname = $('#Lname').val();
var email = $('#Email').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"Fname":"' + Fname + '", "Lname":"' + Lname + '", "Email":' + email + '}',
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});
//$('.secondary').show(500);
});
});
</script>
But I am keep on getting 500 Internal Server error :
{"Message":"Invalid JSON primitive: (Email ID that I am passing).","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
Your email parameter should be enclosed in double quotes, otherwise it will not be parsed properly as a JSON string value. The corrected syntax should be:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"Fname":"' + Fname + '", "Lname":"' + Lname + '", "Email":"' + email + '"}',
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});
You are constructing your data object wrong. Do this instead:
data: {Fname: Fname, Lname: Lname, Email: Email }
No need for quotes..
Try:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: {Fname: Fname, Lname: Lname, Email: email},
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});

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