How to convert string to JSON Object - javascript

timeline.js + MVC + Ajax + JSON
hello,
I have problem while converting string to Json Object
I have to display timeline on my webpage, I have used Timeline.js for the same, I am able to run the timeline using static data that is as following
Static Data
// Create a JSON data table
data = [
{
'start': new Date(2010, 7, 23),
'content': 'Conversation'
},
{
'start': new Date(2010, 7, 23),
'content': 'New Conversation'
},
{
'start': new Date(2010, 7, 23),
'content': 'Very New Conversation'
}
now when I do
alert(data);
it gives me
[object Object],[object Object],[object Object]
but now I have to display a data from the DB, so I am calling the following function on controller
GetTimeLine method on controller
public JsonResult GetTimeline()
{
JsonResult jr = new JsonResult();
var objtimeline = objEntities.Timelines.Where(tl => tl.StudentID == Sessions.StudentID).ToList().AsQueryable();
String newstr = "[";
foreach(var tml in objtimeline)
{
DateTime date1 = Convert.ToDateTime(tml.CalculatedDate);
newstr += "{'start': new Date("+date1.Year+","+date1.Month+","+date1.Day+","+date1.Hour+","+date1.Minute+","+date1.Second+"),'content':'"+tml.Description+"'},";
}
newstr = newstr.TrimEnd(',');
newstr += "];";
jr.Data = newstr;
jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jr;
}
function to call controller method
jQuery.ajax({
type: "POST",
url: "#Url.Content("~/Student/GetTimeline")",
success: function (result) {
data = result;
},
});
alert(data);
it gives me the following alert
[{'start': new Date(2012,2,11,0,0,0),'content':'Parents meeting'},{'start': new Date(2012,2,15,0,0,0),'content':'Exam Meeting'}];
so the problem is with conversion of string to Json Object,
How can I convert string returned from controller to Json Object on my view...

You're working too hard. Let the framework do it for you.
public JsonResult GetTimeline()
{
var timeline = objEntities.TimeLines.Where( tl => tl.StudentID == Sessions.StudentID )
.ToList() //required due to Convert call
.Select( tl => new
{
start = Convert.ToDateTime(tl.CalculatedDate),
content = tl.Description
});
return Json( timeline, JsonRequestBehavior.AllowGet );
}
Then either use getJSON (since you specifically allow gets) or specify dataType: 'json' in your request.
$.getJSON( '#Url.Action("gettimeline","student")', function(data) {
alert(data);
});

What you have the server returning is not valid JSON. Or give your server-side code, it may be valid JSON which just defines a string rather than an object graph. In JSON:
All object keys must be in double quotes, not single quotes.
All strings must be in double quotes, not single quotes.
new Date(...) is not valid (JSON doesn't have any concept of dates).
I believe you want to build up an array (not a string) and assign that to jr.Data, and then let the JsonResult object handle the serialization for you (but I haven't done this in ASP.net MVC).
Once you have the server returning valid JSON, ensure that it's returning it with the correct Content-Type header (the value is application/json). When you do, jQuery will see that it's JSON and deserialize it into an object graph for you. If you can't or don't want to make your server return valid JSON, add dataType: 'json' to the ajax call to force it.

Related

how to replace single quotes with double qoute in jq

I have some thing like this.."Skin','Hair"...
i want result like this ['Skin', 'Hair'];
I tried this
type: 'GET',
url: '/HOME/Getselecteddata',
dataType: 'json',
data: { id: 8 },
success: function (data) {
debugger;
var endString = data.replace(/"/g, "'");
var selectedCodeWBs = [data]
$(".tokenizationSelect2").val(selectedCodeWBs).trigger('change');
Not working. please someone help me
my controller code:
public ActionResult Getselecteddata(int id)
{
var data = db.Segments.Where(x => x.Id == 7003).Select(x => x.Segname).SingleOrDefault();
List<string> segmentdata = new List<String>(data.Split(','));
string s2 = String.Join("','", segmentdata);
return Json(s2, JsonRequestBehavior.AllowGet);
}
You can much better do this:
return Json(segmentdata, JsonRequestBehavior.AllowGet);
Using segmentdata directly will work 100% better than creating a messy string variable that contains unbalanced quotes.
MVC Json() is perfectly capable of working with a List, it will output it as JSON array notation. Then in your javascript the received value in data will already be a Javascript array that won't need further manipulating.

How I send the result of the AJAX back to the JSP?

I post some via AJAX in my servet from my jsp
$.ajax({
url: 'myServlet?action=FEP',
type: 'post',
data: {machine: i, name: txt}, // i, txt have some values.
success: function (data) {
alert('success');
}
});
and in my Serlvlet
String jspAction = request.getParameter("action");
//...
if(jspAction.equals("FEP")){
int idMachine = Integer.parseInt(request.getParameter("machine"));
String name = request.getParameter("name");
double value = actions.getValue(idMachine, name); //<-- this variable I want to send it back to the JSP.
}
The data are sent succesfully. However I haven't understand how I send back the vaule to the jsp..
returning a string would go as follows:
response.getWriter().write("a string");
return null;
If you want to return json, you can use many libraries like: http://www.json.org/
This would result in something like following code:
response.setContentType("application/json");
JSONObject jsonObject = new JSONObject();
double aDouble = 38d;
jsonObject.put("returnValue", aDouble);
response.getWriter().write(jsonObject.toString());
return null;
Use
response.getWriter().write(value);
return null;
And in your ajax success block access the value.
See the following link for more understanding http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html

How to print array list data using ajax?

I am new to AJAX and JSON. I have an ArrayList which contains another ArrayList and I converted the whole array in to JSON object:
#Produces(MediaType.APPLICATION_JSON)
public String getRecords(#QueryParam("mobile_no") String mobilenumber) {
UserActivityDelegate delegate = new UserActivityDelegate();
List<AssessmentDTO> list = delegate.getLastFiveAssessment(mobilenumber
.trim());
if (list.isEmpty())
return "Sorry....You have not attended any assessment";
else {
System.out.println(list);
return (new Gson()).toJson(list);
}
Now I want to know how can I retrieve or iterate the response object in JSP using ajax??
In Ajax response you receive a response string you can convert that either to javascript list or json and iterate over them.
Like below:
jQuery.ajax({
type: 'POST',
url: your_url_string,
data: 1=1 //params,
async: false,
success: function(response,textStatus){
json= JSON.parse(response);
},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
then json object is what you need to take care of.

Passing string array from ASP.NET to JavaScript

I am trying to call the server side from JavaScript and then pass a string array back to JavaScript, but running into problems.
// Call the server-side to get the data.
$.ajax({"url" : "MyWebpage.aspx/GetData",
"type" : "post",
"data" : {"IdData" : IdData},
"dataType" : "json",
"success": function (data)
{
// Get the data.
var responseArray = JSON.parse(data.response);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
On the ASP.Net server side, I have:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetTip(String IdTip)
{
int iIdTip = -1;
String[] MyData = new String[2];
// Formulate the respnse.
MyData[0] = "My header";
MyData[1] = "My body";
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(MyData);
return strResponse;
}
I am probably mixing things up, as I am still new to JSON.
UPDATE with error code:
Exception was thrown at line 2, column 10807 in http://localhost:49928/Scripts/js/jquery-1.7.2.min.js
0x800a03f6 - JavaScript runtime error: Invalid character
Stack trace:
parse JSON[jquery-1.7.2.min.js] Line 2
What is my problem?
I modified your ajax call script to :
// Call the server-side to get the data.
$.ajax({
url: "WebForm4.aspx/GetTip",
type: "post",
data: JSON.stringify({ IdTip: "0" }),
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
Note that I added contentType: 'application/json' and changed
var responseArray = JSON.parse(data.response);
to
var responseArray = JSON.parse(data.d);
This s purely out of guess work. But see if this is what you are getting:-
In your Ajax call, your data type is json and looking at the method you are returning a json string. So you do not need to do JSON.parse(data.response). Instead just see if the below works for you. Also i dont see a response object in your Json, instead it is just an array. So it must be trying to parse undefined
var strHeader = data[0];
var strBody = data[1];

How can I output javascript to a view in asp.net mvc3?

Good morning All,
I have a javascript variable in my view. I keep doing this...
var skinData = null;
and then on document.ready....
$.ajax({
type: 'POST',
url: 'theme/getskins',
data: {},
contentType: 'application/json; charset=utf-8',
success: function(data){
skinData = data;
}
});
my question is why am I doing this on after the view has loaded. I'm trying to do this in _ViewStart.cshtml
viewPage.ViewBag.SkinInfo = new JsonResult { Data = SkinManager.GetSkins() };
How can I take this value and output its value to my javascript variable. I don't think I need to do another request when I really want to push this to the client on the first trip. Any tips or advice is of course appreciated. How can I do this correctly? I tried a few variations of this but it obvious isn't working. Stuff like...
var skinData = #ViewBag.SkinInfo.Data;
This just outputs the namespace. Any ideas how to do this correctly?
Cheers,
~ck in San Diego
You will want to use some a serializer to convert your .GetSkins() method result into a json object. Either the built in JavaScriptSerializer or json.net
JavaScriptSerializer serializer = new JavaScriptSerializer();
viewPage.ViewBag.SkinInfo = serializer.Serialize(SkinManager.GetSkins());
And then in your view
var skinData = #Html.Raw(ViewBag.SkinInfo);
Here's a way of doing it using a Html helper. It will convert your object into json and put it into a javascript variable.
HtmlHelper extension method
public static MvcHtmlString Jsonize(this HtmlHelper helper, string variableName, object obj)
{
StringBuilder str = new StringBuilder();
str.Append("<script type='text/javascript'>");
str.Append("var ");
str.Append(variableName);
str.Append("=");
if (obj == null)
str.Append("null");
else
str.Append(JsonHelper.Serialize(obj));
str.Append(";");
str.Append("</script>");
return MvcHtmlString.Create(str.ToString());
}
The json serializer. I'm using the DataContractJsonSerializer in this case.
public class JsonHelper
{
public static string Serialize(object obj)
{
string json = null;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
json = Encoding.Default.GetString(ms.ToArray());
}
return json;
}
}
Once you have that done, you can just use it in your views to create a javascript variable that contains your object
#Html.Jsonize("data", ViewBag.SkinInfo.Data);
which will create something like this:
<script type='text/javascript'>
var data = { your serialized object };
</script>

Categories

Resources