I have the following variable that post it normally to the following web method.
data: "{item:" + JSON.stringify(json) + ",step:" + JSON.stringify(john) + " }",
The web method:
[WebMethod(EnableSession = true)]
public static string GetCart(string item, string step)
{
HttpContext.Current.Session["f"] = item;
HttpContext.Current.Session["l"] = step;
return item;
}
When I try to add the following variable the 3rd variable(mytest) is not posted
data: "{item:" + JSON.stringify(json) + ",mytest:" + JSON.stringify(json) + ",step:" + JSON.stringify(john) + " }",
The web method
[WebMethod(EnableSession = true)]
public static string GetCart(string item, string step, string mytest)
{
HttpContext.Current.Session["f"] = item;
HttpContext.Current.Session["l"] = step;
HttpContext.Current.Session["mytest"] = mytest;
return item;
}
Edit
And the post statment
$.ajax({
type: 'POST',
url: "mypage.aspx/GetCart",
data: "{item:" + JSON.stringify(json) + ",mytest:" + JSON.stringify(json) + ",step:" + JSON.stringify(john) + " }",
contentType: 'application/json; charset=utf-8',
dataType: 'json'
You need double quotes:
...
data: "{\"item\":" + JSON.stringify(json) + ",\"mytest\":" + JSON.stringify(json) + ",\"step\":" + JSON.stringify(john) + " }"
...
Alternatively, you could stringify once:
...
data: JSON.stringify({item: json, mytest: json, step: john })
...
Related
I'm not understanding why the data is coming back as undefined. It knows there is something there but the value is not being shown. Am I forgetting to do something in the main function? Thanks in advance to whom may solve my dilemma.
Here is the current output I'm getting:
Here is what I need the output to render:
Here is the code for my employee.js:
$(function() {
ajaxCall("Get", "api/employees", "")
.done(function (data) {
buildTable(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
}); // ajaxCall
});
// build initial table
function buildTable(data) {
$("#main").empty();
var bg = false;
employees = data; // copy to global var
div = $("<div id=\"employee\" data-toggle=\"modal\"data-target=\"#myModal\" class=\"row trWhite\">");
div.html("<div class=\"col-lg-12\" id=\"id0\">...Click Here to add</div>");
div.appendTo($("#main"));
$.each(data,function(emp){
var cls = "rowWhite";
bg ? cls = "rowWhite" : cls = "rowLightGray";
bg = !bg;
div = $("<div id=\"" + emp.Id + "\" data-toggle=\"modal\" data-target=\"#myModal\" class=\"row col-lg-12" + cls + "\">");
var empId = emp.Id;
div.html(
"<div class=\"col-xs-4\" id=\"employeetitle" + empId + "\">" + emp.Title + "</div>" +
"<div class=\"col-xs-4\" id=\"employeefname" + empId + "\">" + emp.Firstname + "</div>" +
"<div class=\"col-xs-4\" id=\"emplastname" + empId + "\">" + emp.Lastname + "</div>"
);
div.appendTo($("#main"));
}); // each
} // buildTable
function ajaxCall(type, url, data) {
return $.ajax({// return the promise that '$.ajax' returns
type: type,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true
});
}
Here is my Controller method code:
// GET api/<controller>
[Route("api/employees")]
public IHttpActionResult Get()
{
try
{
EmployeeViewModel emp = new EmployeeViewModel();
List<EmployeeViewModel> allEmployees = emp.GetAll();
return Ok(allEmployees);
}
catch(Exception ex)
{
return BadRequest("Retrieve failed - " + ex.Message);
}
}
The first parameter of the callback is the index, the value is in the second parameter:
$.each(data,function(index, emp){
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);
}
});
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];
}
I have written the following Javascript but get the error 'Invalid JSON primitive: strSeason'. The rest of the syntax seems fine but I can't seem to get the 'data' parameter right. Can anybody help me with the syntax?
TagBuilder script = new TagBuilder("script");
script.Attributes.Add("type", "text/javascript");
script.Attributes.Add("language", "javascript");
// ReSharper disable LocalizableElement
script.InnerHtml = #"
$.ajax({
type: 'POST',
async: true,
contentType: 'application/json; charset=utf-8',
dataType: 'html',
url: '/en-US/" + areaName + '/' + controllerName + '/' + actionName + #"',
data: " + "{strSeason:'" + season + "', strTeam:'" + team + #"'},
beforeSend: function(xhr){
$(this).addClass('ajaxRefreshing');
xhr.setRequestHeader('X-Client', 'jQuery');
},
success: function(html){
$(this).html(html);
},
complete: function(){
$(this).removeClass('ajaxRefreshing');
}
});
";
wrap the names in quotes
data: " + "{'strSeason':'" + season + "', 'strTeam':'" + team + #"'},
EDIT: You may just need to send the JSON string so wrap entire string in quotes.
data: " + "\"{'strSeason':'" + season + "', 'strTeam':'" + team + "'}\"" +#",
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.