JSON - Why I got null object when not using JSON.stringify? - json

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".

Related

IformFile in the action controller takes the value as null, value is pass to the action controller using ajax request

I am trying to get the value passed from the ajax request into one of the method in the controller but IFormFile files is null every time.
Here is my ajax request :
uploadFile: function (field, value)
{
var me = this;
var view = me.getView();
var fileuploadControl = me.lookupReference('ImportFile');
var file = fileuploadControl.fileInputEl.el.dom.files[0];
var param = new FormData();
param.append('files', file);
var ajax = Ext.Ajax.request(
{
url: './../XYController/ImportCSVFile',
data: param,
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: { 'accept': '*/*' },
processData: true,
success: function (response, options) {
var result = JSON.parse(response.responseText);
if (mask) {
mask.destroy();
}
Ext.Msg.alert("File Upload Successful");
}
});
},
And this is my Action Controller :
[HttpPost]
[Route("XYController/ImportCSVFile")]
public IActionResult ImportCSVFile(IFormFile files)
{
if(files!=null)
{
//do something
}
}
For file upload , The contenttype needs to be set to false along with the processData option. Otherwise jQuery will not see this as a file upload :
processData: false,
contentType: false,
See code samples from here , that should be same no matter use ExtJS or other Jquery wrapper library .

How to perform an Ajax call from a partial view. Asp.net MVC

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.

How to parse this json file with key and value pair?

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

jqPlot and JSON formatted Data

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.

Jquery Autocomplete with json and using parameters

I am trying to do an autocomplete input field. Everytime a user type a letter in that field, the value of the field is sent to the server and the server answer with words that match.
var acOptions = {
source:function (request, response) {
$.ajax({
url: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw",
type: "GET", dataType: "json",
data: { expr: request.term},
success: function (data) {
response($.map(data, function (item) {
return item.value;
}))
}
})
},
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
This is an example of data from the server:
[{"value":"Greater"},{"value":"great"},{"value":"greatly"},{"value":"Greater-Axe"}]
The previous code do the right request to the server (and the server answer right) but it does not display anything in the text field.
I tried to do the autocomplete without an explicit ajax object but then I couldn't send the current value of the field (parameter "expr" of the request) to the server:
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=",
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
Thank you for your help!
You can use jQuery to pull the value of your field to add it to URL parameter string.
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=" + $('#ID_OF_YOUR_TEXTBOX').val(),
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);