How to pass json data via ajax? - javascript

I am working a visual studio 2012 MVC program.
I use ajax to send data to a controller and wish the controller returns a body of html. the data is in json format. the data is a string name and decimal TotFees.
I found that the parameters value in the public ActionResult ImmPay(string Name) in the controller are always null. Finally I tried just to pass name, but the value of name in the controller side is still null.
what is wrong in my code, and how to solve the problem? Thank you.
View:
function ImmPay()
{
var name = "ASP";
var TotFees = 100.01;
//var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "\'}";
//var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "m\'}";
dd = "{\'b\':\'" + b + "\'}";
dd = JSON.stringify(dd);
$.ajax({
url: '#Url.Action("ImmPay", "Consult")',
type: 'GET',
async: true,
data: dd,
contentType: 'application/json',
context: document.body,
success: function (response, textStatus, jqXHR) {
$("#dialog-immpay").html(response);
$("#dialog-immpay").dialog("open");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
},
complete: function () {
;
}
});
}
Controller:
public ActionResult ImmPay(string Name)
{
do something here
}

JSON.stringify takes an object or an array and converts it into JSON, so you can build your data into an object and stringify it like so
dd = JSON.stringify({b: b});

Related

Parse a Namespace in JavaScript

I have a fairly simple web service response. How I can parse the response in a way that I could get the value of namespace ns2:count.
Web Service Response
<availableSlots xmlns:ns5="http://jabber.org/protocol/httpbind" xmlns:ns2="http://bindings.egain.com/chat" xmlns:ns4="urn:ietf:params:xml:ns:xmpp-stanzas" xmlns:ns3="jabber:client">
<ns2:count>1</ns2:count>
</availableSlots>
My JavaScript
$(document).ready(function () {
$.ajax({
url: "https://myserver/system/company/chat/fake/capacity/1007",
dataType: 'xml',
success: function (data) {
var xmlDoc = $.parseXML(data),
$xml = $(xmlDoc),
$name = $xml.find("ns2\\:count");
$("#AvailableAgents").html($name);
alert($name);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText + "\n" + xhr.status + "\n" + thrownError);
}
});
});
this way my alert shows object [Object]. How I can get the value 1.
Unfortunately, parseXML dose not work for me but I was able to get the values as;
I get the xml attribute which is availableSlots
Then I get the valueof ns2 namespace
var slots = $(data).find('availableSlots');
var numberOfAgents = $(slots).find("ns2\:count").text();

POST http://localhost:51348/TestService.svc/SendCredentials 400 (Bad Request)

I have been stuck at this problem for almost two days now and I don't seem to find any solution. I have hosted a WCF service on my machine that contains a method SendCredentials which accepts two string parameters.
Now I am supposed to send a public key to my service through which it will do encryption(Asymetric cryptography) and send some information back to the client.
I am not able to pass that public key to the service method from the client as it is in XML format.Here is my client side code:
$(document).ready(function () {
$("#btnSend").click(function () {
debugger;
jQuery.support.cors = true;
var doOaepPadding = true;
var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
_privateKey = rsa.ToXmlString(true);
_publicKey = rsa.ToXmlString(false);
var data = $("#txtName").val();
var name = "testvalue";
var _privateKey = rsa.ToXmlString(true);
**var _publicKey = rsa.ToXmlString(false);**
//<![CDATA[ and ]]>;
$.ajax({
type: "POST",
url: 'http://localhost:51348/TestService.svc/SendCredentials',
crossDomain: true,
data:JSON.stringify({ mac: "bac", pubKey: _publicKey }),
contentType: "application/json",
dataType: "json",
success: function (result) {
var ans = JSON.stringify(result);
alert(ans);
// result = new XMLSerializer().serializeToString(result.documentElement);
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
return false;
});
});
</script>
_publicKey is the variable I want to pass but throws above said error. Any suggestions How do i pass this XML variable would be really appreciated.
I would suggest you to convert _publicKey to base64 string
convert your _publicKey to string then byte Array and use
Convert.ToBase64String(byte[] inArray)
and on the service side do the reverse
System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(endodedString), true));

JsonResult returning data, but Jquery Ajax returns undefined data when type is GET

I have a javascript function calling a JsonResult method, and the JsonResult method is sending the data back to the function, but when I test it with an alert in the javascript function it returns as Undefined. I have checked out a couple similar answers on SO, like this JsonResult returns null for Jquery .ajax and Jquery ajax not returning data [duplicate] but they are dealing with POST and not GET, can I get some guidance on what I am doing wrong or direction to where I can this figured out?
The end result is I need to get all the returned data from the JsonResult method then populate it into textfields.
My JsonResult method is..
public JsonResult myResult(string id)
{
dal = new AWDAL();
List<CustomerToAdd> cust = dal.GetCustomerByID(id);
return Json(cust, JsonRequestBehavior.AllowGet);
}
and my JavaScript is this..
function DataToGet(whatever) {
alert(whatever.customerName);
}
function GetCustomerByCustomerID() {
//var id = selectCustomerID;
var result = "";
$.ajax({
type: "GET",
url: "#Url.Action("myResult", new { id = "1234-5678-9012" })",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
return DataToGet(data);
}
});
}
I found this way of doing what I want but its for WebAPI2, I am not using WebAPI2 but it looks better, I am not even sure if I can use it to do what I want.
function formatItem(item) {
return item.Name + ': $' + item.Price;
}
function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
EDIT
Response Header
Response Body
The payload is an array. To get a single item in the payload you would need to get it like so data[0] and each field data[0].customerName.

On Save of when creating account record create a task (capturing current time and user in description field) using odata

**
function task()
{
var date=Date.now();
var accountid=Xrm.Page.data.entity.getId();
var entity = {};
entity.Description = date;
entity.Subject = "Hi.....";
entity.RegardingObjectId = {
Id:accountid,
LogicalName: "account"
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/TaskSet",
data: JSON.stringify(entity),
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: false,
success: function (data, textStatus, xhr) {
var result = data.d;
var newEntityId = result.TaskId;
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
}
//I try to get date from system and inserted in to task description but it showing.
Blockquote
Error bad request
Blockquote
so please help me out ,thanks in advance.
the statement :
var date=Date.now();
captures current date and time and returns as DateTime format.
here is where you went wrong
entity.Description = date;
entity.Description accepts sting only ..not datetime try converting the variable to string with toString() also check the other possible methods
check for demo
instead of var date=Date.now(); we can use `var date=Date();' it will work.
Instead of var date=Date.now(); we can use var date=Date();

Simplest way to test ASP.NET Webservice that returns JSON from some JavaScript?

We have a .asmx service that returns JSON data. Can someone point me to a simple example that calls the service from a page w JavaScript ?
Tks
You can use jQuery's get function.
var dataID = $('#WhatINeedForAParameter').val();
$.get('WebApiAddress/MethodName', { id: dataID },
function(data) {
alert(data);
// Since your method returns a JSON object you can access
// the properties of that object
alert(data.id);
alert(data.name);
});
Or if you want to use the long hand jQuery ajax you can do the following:
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "WebApiAddress/MethodName",
type: "POST",
data: { id : dataID },
dataType: "jsonp"
});
request.done(function(msg) {
alert('You got this ' + msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});

Categories