How to read a Json file in jQuery - json

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

Related

ASP MVC Areas and JSON POST

I have a project with areas and would like to post a view model as JSON to a controller method.
This is what I have, with performance being generated in the default area and passed to the view in area SeatSelection:
$("#addToCartButton").click(function () {
var json = #Html.Raw(Json.Encode(performance));
$.ajax({
url: 'https://#(Request.Url.Host)/SeatSelection/Home/AddToCart',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
And the action method for testing:
[System.Web.Http.Route("SeatSelection_AddToCart")]
[System.Web.Http.HttpPost]
public JsonResult AddToCart(PerformanceViewModel performance)
{
return Json(performance.Name);
}
I created the following route:
context.MapRoute(
"SeatSelection_AddToCart",
"SeatSelection/Home/AddToCart",
new { action = "AddToCart", controller = "Home", id = UrlParameter.Optional },
namespaces: new string[] { "myProject.Areas.SeatSelection.Controllers" }
);
But all I get is a internal server error 500. I also tried to use [FromBody] and setting a breakpoint to the method, but it is not invoked. I can't figure out what's wrong or missing, please help.
UPDATE
This is the json / performance:
PerformanceID=00000000-0000-0000-0000-000000000000&Name=Performance+15&StartDate=%2FDate(1360364400000)%2F&EndDate=%2FDate(1500328800000)%2F&LatestDateBookable=%2FDate(1450911600000)%2F&Organizer=Organizer+15&Location=Location+15&Availability=75&IsFull=false&IsBookable=true&HasPrice=true&BookableSeats=11&BookedSeats=94&Description=Description+of+Performance+15&Price=443
I found an error: "invalid json primitive: performanceid"
First of all, I would recommend you to use #Url.Action helper method instead of generating url like this: https://#(Request.Url.Host)/SeatSelection/Home/AddToCart.
Secondly, always validate params which comes from the browser. return Json(performance.Name) looks suspicious. What is performance will be null? This might be a problem of your internal server error 500.
If this is not a problem then try to send string instead of JSON to the server and validate and parse JSON on the server side.
You can use Url.Action method like this. I suppose SeatSelection is an area in your project.
$.ajax({
url: '#Url.Action("AddToCart", "Home", new { Area = "SeatSelection"})',

Trying to pass list of ids to the M-V-C Action through Ajax Function

I am trying to get and store the Ids of all the selected check-boxes in the JavaScript object. And then passing this object as a data to my JSON Action. I am able to successfully get the Ids of all the selected check-boxes, but when I am passing this object to my action I am getting null. Following is my code:
$("#btnSave").on('click', function () {
var selected = [];
$('input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '#Url.Action("SaveRecords", "Users")',
data: { ids: selected },
cache: false,
type: "GET",
success: function (data) {}
});
});
My Action:
public JsonResult SaveRecords(List<int> ids) //Here I'm getting Null.
{
return Json(true, JsonRequestBehavior.AllowGet);
}
As suggested in the comments, since you are saving data POST is more appropriate than GET. Also, I think you will save yourself some trouble by using JSON as input - you're already using it as output format from the action. This means your AJAX call will look like this:
$.ajax({
type: 'POST',
url: '#Url.Action("SaveRecords", "Users")',
contentType: 'application/json',
data: JSON.stringify(selected),
success: function (data) { /* ... */ }
});
When I say "save yourself trouble by using JSON as input" I mean that model binding collections and complex types in MVC can be a bit tricky when sending data as a form post - google it and you'll see that there are several implementation characteristics to be aware of. In my experience, using JSON for structured data posted with AJAX just works much more like what you would expect.

Getting json object

first time using json. I currently send a postcode to a php page, and try to store the result as json:
$("#make_ajax_call").click(function()
{
var form_postcode = $("#postcode").val();
$.ajax({
type: "POST",
url: 'mapping-ajax.php',
data: { postcode: form_postcode},
success: function(data)
{
var jsonObject = data;
var trimmedpostcode = jsonObject.trimmedpostcode;
alert(jsonObject);
alert(jsonObject.trimmedpostcode);
$('#result').html(data);
//alert('Load was performed.');
}
});
});
On the other end I use a php function echo json_encode($return_array);
The two alerts give me:
{"trimmedpostcode":"CO125WL","success":true,"outputstring":"CO125WL<br\/>"}
and
Undefined
How come the second one doesn't return "CO125WL"? Do I need to tell javascript its a json object somehow?
Have you tried:
dataType: 'json'
This is how I pull in my json information in Javascript with an ajax call.
You got it. You need to call:
var obj = JSON.parse(jsonstr);
That will parse the JSON into a JavaScript Object.
Do I need to tell javascript its a json object somehow?
Yes, you will need to tell it that it's a json string. Set the mimetype of your response to the appropriate "application/json", and jQuery's intelligence will parse the text automatically and call your success function with an object instead of a string.
Or you can set the dataType of your jQuery call to "json", see the jQuery.ajax() documentation.

how to set jsonp callback in retrieving restful web service data via jquery

I have asked a question regarding invalid label on firebug which happens when I try to retrieve data from my restful web service. Most of the answers I received was about setting a callback function. but I can't seem to get the right juice from it. can you show me an exact code on how to do it? or atleast correct the code here:
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
processdata:true,
jsonp: false, jsonpCallback: "success",
url: 'http://localhost:8732/Service1/data/10',
success : function success(data) {
jsonResponse = eval("(" + data + ")");
alert(jsonResponse)
},
error : function(req,status, ex) {
alert(ex);
}
Thanks,
Wow, you've got a lot of unnecessary stuff there. Try this:
$.ajax({
url: 'http://localhost:8732/Service1/data/10',
dataType: 'jsonp',
error: function(req, status, ex) {
// your code here
},
success: function(data) {
//your code here
// Please note: you don't need to 'eval' the json response.
// The 'data' variable will be loaded with the object that the json string represents.
// By the way, don't use 'eval', ever.
}
});
jQuery will take care of the callback on the url. See here: http://api.jquery.com/jQuery.ajax/
UPDATE
Why jsonp? If you're getting this from localhost, why not just json? As discussed in the comments below, your server currently is not capable of a jsonp response, but it can do json.

ASP MVC 3 complex multi parameters kno

in my previos question Asp MVC 3 json complex object not initialize properties
My mistake was in JSON convert from Knockout and after one more time with JSON.stringify(data).
Now evering working fine with one parameter,
but I wonder about if I need send to MVC controller two or more parameters one of them is knowckout data = ko.toJSON(viewModel); variable other one is some text.
var settings = ko.toJSON(viewModel);
var parameters = JSON.stringify({ id : *"guid"*, data : settings });
$.ajax({
url: '/KioskAjax/SaveSettings/',
type: "POST",
data: parameters,
dataType: "JSON",
contentType: "application/json; charset=UTF-8",
success: function (result) {
alert('ok');
}
});
[HttpPost]
public JsonResult SaveKiosksSettings(Guid id, GlobalData data)
{
return Json(false.ToString(), JsonRequestBehavior.AllowGet);
}
In this example id is getting value, but GlobalData parameters is null again,
i think this is because I use JSON.stringify again, but how build correct JSON for controller call if I have knowckout object ?
thanks.
ko.toJSON(myObject) does a ko.toJS(myObject) and then a JSON.stringify(myObject).
So, you could choose to use ko.toJS(myObject) to get a clean copy of your data and then JSON.stringify it with your other data, as you are already doing.