Ajax Post is failing if post data contains formatted string - html

How can i post formated strings like
has<STRONG>b</STRONG>
I need to send ajax request .In my page i am using an editor , so that user can type and format. BUt ajax request failing if the string is formatted( eg: if the string have bold string .example data is shown above
var test=$('#callTranscription').val(); // contains has<STRONG>b</STRONG>
var postData = { transID: $('#callTransactionID').val(), callTranscription: test, recordID: $('#selectedRecord').val() };
$.ajax({
type: "POST",
data: postData,
url: '<%= Url.Action("SaveCallTranscription", "Search") %>',
success: function (result) {
$('#callTransactionID').val(result)
alert('success');
},
error: function (result) { alert('error'); }
});
)
Here the callTranscription contains formatted string. How can i post is safely?Is there any conersion i need to do before sending that type if data.??

You should format the string properly. Is it already formatted or are you sending raw data?
Think of URLencoding http://www.javascripter.net/faq/escape.htm

Related

JSON: Controller parameter value has slash appended in its value

I am working on a simple project and want to send the JSON data to Controller
Here is my code:
var emailId = JSON.stringify(response.emails.account); // get email ID
$.ajax({
url: "/Home/GetDetails",
method: "GET",
contentType: "application/json",
dataType: "json",
data: { 'emailId': emailId },
success: function (data) {
// some logic here
}
And my Home controller is:
public JsonResult GetDetails(string emailId){
// logic here
}
The problem is JSON value of parameter emailId in controller is correct but it is in the form ""abc#gmail.com"" instead of simple "abc#gmail.com" I get the "\ .. " as an extra appended in the parameter value which I would like to avoid. How can I avoid it? Also Why is it happening? Am I missing something?
I think, instead doing this:
var emailId = JSON.stringify(response.emails.account); // get email ID
You should JSON everything in the data section of your ajax call.
Such as
data: JSON.stringify({"emailId": response.emails.account}),

how to get data from json in servlet

function getvalue1(){
debugger
var str=document.getElementById("SystemName").value;
var str1=document.getElementById("IP").value;
var str2=document.getElementById("SystemLevel").value;
var str3=document.getElementById("Ownera").value;
var str4=document.getElementById("Ownerb").value;
var str5=document.getElementById("SystemDesc").value;
var str6=document.getElementById("SystemDate").value;
var str7=document.getElementById("Recorder").value;
$.ajax({
type:"post",
url:"../AddServlet",
data: {
str:str,
str1:str1,
str2:str2,
str3:str3,
str4:str4,
str5:str5,
str6:str6,
str7:str7
},
async:false,
dataType:"json",
contentType:"application/json;charset=utf-8",
success:function (data) {
$.message.alert('successful');
},
error:function () {
alert("failedjump");
}
});
}
The previous is my js code, I wanna to take these "strs" into the servlet, I programmed servlet part to get the data is
enter image description here
But these strings are null in the servlet. How can I get the JSON data? thx!
getParameter will read standard form encoded data, not JSON data.
This wouldn't normally be a problem because you are sending standard form encoded data, not JSON.
However, since you have said contentType:"application/json;charset=utf-8", you are claiming to be sending JSON, so it isn't being parsed.
Remove that line.

How to send multiple parameters from kendo data source read operation to WebApi controller

I have the following scenario: I have a kendo.dataSource which is populated via read request to a WebApi Controller. In addition to the read, I am sending a couple of parameters, which then I use in my controller to do some server logic. I was able to send as many simple parameters as I want via the parameterMap property of the transport function. Till now it was a simple get request. However now I need to send additional json object to the controller as a parameter. I read that I have to transform the Get request to Post and put the Json onto the body of the request but I don't know how to do it.
The code that I have so far:
var gridDataSource = new kendo.data.DataSource({
type: 'odata-v4',
transport: {
read: {
url: wave.alarmsAndEvents.api('api/alarmsAndEventsSearch/post'),
type: "POST",
data: {
SearchModel: JSON.stringify(vm.searchModel)
},
contentType: 'application/json; charset=utf-8',
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.startDate = kendo.toString(vm.selectedTimeInterval.start, "G");
data.endDate = kendo.toString(vm.selectedTimeInterval.end, "G");
data.alarmsToDisplay = vm.maxRecords;
}
return kendo.stringify(data);
}
},
pageSize: vm.maxRecords,
error: function (e) {
alert(e.xhr.responseText);
}
});
The SearchModel is the thing that I want to send as JSon. The rest are simple DateTime and int parameters.
My controller:
[HttpPost]
public IQueryable<AlarmsSearchViewModel> Post(DateTime startDate, DateTime endDate, int alarmsToDisplay, [FromBody]JToken jsonbody)
{
....
return something;
}
I end up with Not Found 404, but I am pretty sure that I have messed up the parameters. And from the Network window I can see that the json object is not sent at all. Any help will be much appreciated!

How to read a Json file in jQuery

I'm using VS2012, and running an ASP.NET MVC4 project.
I cannot seem to get this to fire below :
$.ajax({
url: "~/xml/JsonTest.json",
type: "GET",
dataType: "json",
success: function (json) {
alert("HI");
}
});
I also tried it this way , but to no avail :
$.getJSON('../xml/JsonTest.json', function (json) {
alert("GET JSON !");
});
Is it somehow not finding the directory structure ?
thanks.
Bob
The first one definitely won't work, since ~ doesn't mean anything client-side. What actual URL is requested by the second example? Does it send an AJAX request at all? What is the response?
If you have a dynamic server-side URL then you'll want to use server-side code to dynamically build it in the rendered output. Something like this:
$.ajax({
url: '#Url.Content("~/xml/JsonTest.json")',
type: 'GET',
dataType: 'json',
success: function (json) {
alert("HI");
}
});
This would result in the client-side JavaScript being rendered with the full URL for the server-side path "~/xml/JsonTest.json".
Best solution for my case was to properly code it up in a C# method as follows :
public string getJsonParameters()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
string jsonStr = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/myKeys.json"));
JsonParameters jsonData = (JsonParameters)ser.Deserialize(jsonStr, typeof(JsonParameters));
return jsonStr;
}

Send generic JSON data to MVC2 Controller

I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers. The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model. So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.
My ajax call:
function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
// Make a call to the server to process the object
var jsonifiedObject = JSON.stringify(object);
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: jsonifiedObject
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});
}
My MVC Controller:
public ActionResult SaveForm(string obj)
{
// Ok, try saving the object
string rc = PassJSONToSomething(obj.ToString());
string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
return new ContentResult { Content = message, ContentType = "application/json" };
}
The problem is that obj is always null. Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server? I'm using MVC2. This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.
Thanks very much.
Have you tried something like that?
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: {obj :jsonifiedObject}
, contentType: 'application/json; charset=utf-8'
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});