How to parse this json file?
I tried the following code, but it didn't work.
I tried the following code, but it didn't work.
{"success":true,
"CourseResult":[
[{"Key":"Course","Value":"Physics"}],
[{"Key":"Course","Value":"Chemistry"}],
[{"Key":"Course","Value":"Math"}],
[{"Key":"Course","Value":"English"}]]}
$.ajax({
type: "POST",
url: "/Course/GetCourse",
dataType: "json",
data: {
registrtionId: rId
},
success: function (data) {
if (data && data.success) {
var rst = JSON.parse(data);
alert(rst.CourseResult[1].Course);
},
error: function (msg) {
}
});
Related
I want to perform an Ajax Call to get data from a form that is in a partial view, to a controller and get a response message back.
Ajax Call
$("#submitContactInfo").on("click", function () {
if ($('#contact-form').valid() === true) {
$.ajax({
url: '#Url.Action("SendEmailAsync", "Home")',
type: "Post",
data: {
"name": Name.value,
"lastName": LastName.value,
"email": Mail.value,
"phone": Mobile.value
},
dataType: "json",
success: function (result) {
if (result.value === "1") {
...
}
else {
...
}
}
});
}
});
My Controller
[HttpPost]
public async System.Threading.Tasks.Task<ActionResult> SendEmailAsync(string name, string lastname, string email, string phone)
{
var value = 0;
...
return Json(value, JsonRequestBehavior.AllowGet);
}
First thing I stumbled upon was that#Scripts{} does not work on partial views so I had to think of another way.
So I created an external file and named it 'custom.js' and referenced it on _Layout.chtml, below the:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
...
#Scripts.Render("~/Scripts/custom.js")
The second thing I noticed was that the url from the Ajax Call was not working because I was using Razor syntax in an external js file.
So I changed url: '#Url.Action("SendEmailAsync", "Home")', to url: '/Home/SendEmailAsync',
After that I was getting a 500 error, so I figured that by changing type: "Post", to type: "Get", and dataType: "json", to dataType: "html", and by adding contentType: "application/json; charset=utf-8", I was a little closer because I was getting a 404 error.
So I went to my Controller method and removed [HTTPPOST] and that was it.
Final Ajax Call:
$("#submitContactInfo").on("click", function () {
if ($('#contact-form').valid() === true) {
$.ajax({
url: '/Home/SendEmailAsync',
type: "GET",
data: {
"name": Name.value,
"lastName": LastName.value,
"email": Mail.value,
"phone": Mobile.value
},
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (result) {
if (result === "1") {
...
}
else {
...
}
}
});
}
});
My Controller
public async System.Threading.Tasks.Task<ActionResult> SendEmailAsync(string name, string lastname, string email, string phone)
{
var value = 0;
...
return Json(value, JsonRequestBehavior.AllowGet);
}
If you have a better solution or any remarks to make, feel free. I'm open to suggestions.
I'm using bootstrap 3 and jquery to develop my app. My question is, why i got null object if not using JSON.stringify instead formValues?
Before using JSON.stringify
var that = this;
var formValues = {
userId: 315,
locale: "en",
};
this.collection.fetch({
type: "POST",
contentType: 'application/json',
dataType: "json",
data: formValues,
success: function(collection, response) {
var template = _.template(accountsSummaryTemplate, {
accounts: that.collection.models
});
that.$el.html(template);
console.log(that.collection);
},
error: function(collection, response) {
console.log(that.collection);
}
});
After using JSON.stringify
var that = this;
function formToJSON() {
return JSON.stringify({
"userId": 315,
"locale": "en",
});
}
this.collection.fetch({
type: "POST",
contentType: 'application/json',
dataType: "json",
data: formToJSON(),
success: function(collection, response) {
var template = _.template(accountsSummaryTemplate, {
accounts: that.collection.models
});
that.$el.html(template);
console.log(that.collection);
},
error: function(collection, response) {
console.log(that.collection);
}
});
Thanks a lot in advance.
If the data property is an object, jQuery serializes it with $.param:
> $.param({userId: 315, locale: "en"});
"userId=315&locale=en"
If you pass in a string instead, jQuery doesn't serialize it. Look at the requests using your web browser's developer tools.
Because that's not a proper data string.
var formValues = "userid=5&locale=en";
Because JS object is not JSON. JSON is string, JS object is an object. If fetch uses jQuery.ajax, it expects either a JS object, or a query string (which is not JSON): "userId=315&locale=en".
I'm returning a JSON string with an Ajax call in jQuery, I'd like to pump that data into a bar chart using jqPlot.
I got the JSON conversion code from another Stack-Overflow post, but can't understand why this isn't working. My code:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO), //JSON.stringify(AnDParms), combined,
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
//do chart stuff here.
var line1 = [];
for (var prop_name in data.d) {
line1.push([prop_name, data[prop_name]])
}
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [line1], {
title: 'Admits & Discharges',
series: [{ renderer: $.jqplot.BarRenderer}],
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
//to prove the flow is working...
//alert("Data: " + data.d);
}, //end of success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown + ' ' + XMLHttpRequest);
} //end of error
}); //end of ajax call
In Firebug, the value of line1 is (going from 0 to 32):
[["0", undefined],["1", undefined],...["31", undefined],["32",
undefined]]
While the value of data is:
Object { d="{"Admits":"35","Discharges":"36"}" }
Thanks for any help you can offer...
The problem is your JSON structure:
{
"Admits": "35",
"Discharges": "36"
}
You are providing a JSON object, but jqplot needs array instead:
[
["Admits", 35],
["Discharges", 36]
]
I finally figured it out with the help of Dave Ward of Encosia.com...if you've not checked out his blog, head straight there right now...it's great for all your .Net/jQuery needs.
Here is my javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO),
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
var jqPlotData = $.map(data.d, function (value, key) {
if (key != "__type") {
return [value]; //was key, value
}
});
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [jqPlotData], {
title: 'Admits & Discharges',
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
rendererOptions: { varyBarColor: true },
pointLabels: { show: true }
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
},
highlighter: { show: false }
});
Also, I removed the JSON serialization from my web service, and just returned the object. Hopefully this will help others.
I have tried this alot but always I am getting the failure problem .Can any one guide how can we read the json file using jQuery?I have a json file in my project as given in this image
i have written the code as given below
$(document).ready(function () {
$('#btnLoad').click(function () {
$.ajax({
url: "example.json",
dataType: "text/json",
type: "GET",
contentType: "application/json;charset=utf-8",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
But It is always AjaxFailed is firing.
dataType should be 'JSON'
There are only 4 accepted values for dataType, which you can see here:
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
Also, your error function takes 3 parameters:
errorFn(jqXHR, textStatus, errorThrown) {
// your code
}
Additionally, this:
success: function (msg) {
AjaxSucceeded(msg);
},
Can be this:
success: AjaxSucceeded
Your success function also takes 3 parameters:
success(data, textStatus, jqXHR)
For reference on $.ajax parameters: http://api.jquery.com/jQuery.ajax/
public function actionajaxSearch() {
$data_fetched=Person::model()->findByAttributes (array('Code'=>'Cust0001'));
echo CJSON::encode($data_fetched); }
$('#searchResult').live('pageshow', function(e,info)
{
$.post('?r=mobile/ajaxSearch',$('form').serialize(),
function(res)
{
arrayvalue =res;
$.each(arrayvalue, function(i, profile) {
alert(i);
alert(profile);
});
}
});
I am getting the output as json encode one.
In traversing alert i am getting the value each character not by key or value.
Any help?
Adding the datatype and contenttype solved the problem. Added the complete code for other's ref.
public function actionajaxSearch() {
$data_fetched=Person::model()->findByAttributes (array('Code'=>'Cust0001'));
echo CJSON::encode($data_fetched); }
$('#searchResult').live('pageshow', function(e,info)
{
$.ajax({
beforeSend: function() { $.mobile.showPageLoadingMsg(); },
complete: function() { $.mobile.hidePageLoadingMsg() },
url: '?r=mobile/ajaxSearch',
data: $('form').serialize(),
type: 'POST',
ContentType: "application/json",
dataType: "json",
success:function(res) {
if(res !='')
{
$.each(res, function(key, value) {
var li='<li>'+value['Code']+'</li>';
$("#mylist").append(li); //append li to ul of id list
}); //eachfunction
$('#mylist').listview();
$('#mylist').listview('refresh');
}//sucess
});