Pass null value to controller - javascript

I have a variable which I want to pass to controller, it's a date format which I want to send it as seconds,
var f = $("#from").val(); var from_mili = Date.parse(f);
Here is my AJAX request:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("EventEntries", "Turbine")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"from": (from_mili / 1000) }),
success: function (result) {
debugger;
}
});
The problem is when I divide it by 1000 to get seconds out of it in controller I get null but when I send without the division I get the value.
public JsonResult EventEntries(long? from = null)

To complete the #phuzi answer, there's another mistake in your code.
The first is the division of a Date with a number. #phuzi's answer gives a solution for this issue.
The second issue is that you use stringify in you ajax call which is useless because of your contentTypeset to json.
So your code should look like this:
var f = $("#from").val();
var from_mili = Date.parse(f);
var from = Math.floor(from_mili / 1000);
var data = { from: from };
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("EventEntries", "Turbine")",
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
debugger;
}
});
Then, the default value for your fromargument in C# is useless: you're using a nullable type. It does not solve an issue but it's an advice about something which is useless.
public JsonResult EventEntries(long? from)

Your variable from_mili appears to be getting set incorrectly: f is being set to a string which comes out as NaN when passed to Date.parse() which then breaks when divided by 1000.
Try this instead:
var f = $('#from').val();
var from_mili = Date.parse (parseInt (f));
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("EventEntries", "Turbine")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"from": (from_mili / 1000) }),
success: function (result) {
debugger;
}
});

You're trying to divide a Date object by a number!
Change
var from_mili = Date.parse(f);
to
var from_mili = Date.parse(f).valueOf();

Related

Data is lost after ajax call

I've got one ajax call after two previous. I need to pass results of those calls to the new one, so I do the following
$.when(getRespData(), getAxisComponents()).done(function (respData, axisData) {
var a = respData; //everything is ok
var b = axisData; //everything is ok
$.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName+ '&type=' + 'VAL',
success: (function (data) {
var c = respData; //everything is ok
var d = axisData; // Uncaught ReferenceError: axisData is not defined
}
but I've got Uncaught ReferenceError when I try to get my axisData inside my new ajax call, although operations with respData are ok.
My first 2 ajax calls look like
function getRespData() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName + '&type=' + 'RESP',
success: (function (data) {
return data;
})
});
}
function getAxisComponents() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload/axis?runName=' + runName,
success: (function (data) {
return data;
})
});
}
where runName, type, taskName are some params of function which contains all these ajax calls.
How can I fix this error, so that I would be able to access both respData and axisData ind my inner ajax call?
i solved it putting async false and declaring an array out of ajax call, like this
let array = [];
$.ajax({
url: path,
type: 'GET',
async: false,
dataType: 'json',
success: function(response){
array = response;
}
});
return array;
You're calling data in your success function but data isn't set before this.
In a jQuery .ajax function, data is the data that is sent to the server when performing the Ajax request, which is why you may think it is lost (because it was never there).
Consider the following:
$.ajax({
data: {"data": data},
dataType: "json",
url: 'yourURl',
success: function(data){
return data;
}

The returned code not stopping on ajax call

this is my ajax call function
$.ajax({
url: "webservices/mywebserveice.vb",
data: "{'myactivity':'" + myactivity + "','myproddate':'" + mynewprddatee + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data) {
var obj = jQuery.parseJSON(data.d);
//obj[0]["ColumnName"]
var returnlist = new Array();
my vb. code returns some data and pass I to ajax call using
Return New JavaScriptSerializer().Serialize(rows) .It stops at var obj in ajax call for some data but it is not stopping when i pass some other data in vb file. even if i have identical dataset result.
here is a part of vb code
'Convert Dataset to DataReader
Dim dr As DataTableReader = ds.Tables(0).CreateDataReader()
If dr.HasRows Then
Do While dr.Read()
row = New Dictionary(Of String, Object)
For c As Integer = 0 To dr.FieldCount - 1 '//fieldcount gives the column count.
row.Add(dr.GetName(c), dr.GetValue(c)) '//getname->gets the column name; getvalue->gets the col value.
Next
rows.Add(row)
Loop
End If
Return New JavaScriptSerializer().Serialize(rows)
I also tried asycn = false/ture , same issue ..
Any help appreciate

Using two different ajax call

I have two different ajax calls . First one connects to one method of a web service . if it gets any null value for a specific field then it should call the other method from same web service . Here are the codes ..
$.ajax({
url: "webservices/ProdMonitorService.asmx/GetEstTimePrelimFinalCur",
data: "{'myactivity':'" + myactivity + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data) {
var obj = jQuery.parseJSON(data.d);
for (var i = 0; i <= obj.length - 1; i++) {
var dur_time_formated = '';
var mytimedur = obj[i].time_duration;
if (mytimedur != null) {
dur_time_formated = mytimedur.replace('.000000', '');
}
else {
//only one time check for this
$.ajax({
url: "webservices/ProdMonitorService.asmx/GetEstTimePrelimFinalCurTotalProcessing",
data: "{'myactivity':'" + myactivity + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data2) {
var obj2 = jQuery.parseJSON(data2.d);
dur_time_formated = obj2[0].total_processtime.replace('.000000', '');
}, error: function (result) {
//alert("Error: Please contact administrator for help: " + result.responseText);
}
});
}
For the first ajax call , it gets obj[0]......obj[7] but let say obj[0].time_duration comes null then it should go to second ajax call ,but even method "GetEstTimePrelimFinalCurTotalProcessing" returns some result , dur_time_formated varialbe comes null;, it is not even go thru second ajax call completely after first one.
Should use done function after first one is completed ?
You should try "async: false" instead of "async: true" here. This will work in your case.
bear in mind that ajax call is async. it means that dur_time_formated will be set later after your for-loop. so to solve the problem you can use any array variable outside your loop or sync ajax request

List from Javascript to Post Method c#

Hi everyone i have a problem on javascript for pass the list from the result of form to post method in c#.
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('#runProcess').click(function() {
var request = new WebPay();// is only a method where i take the result from the fiel of the form
var list = new Array();
list.push(JSON.stringify(request));
var jsonstr = {'':list};
$.ajax({
type: "POST"
url: "http://localhost:4556/Pay_Info"
datatype: "JSON",
data: jsonstr,
traditional: true,
success:function (data,textStatus, jqHr){
//build a grid with jquery
The post method is :
public HttpResponseMessage Pay_Info([FromBody] List Pay)
The fields are good i mean when i take the result from a form i have the right Json String but when i pass the array (list) in the post method the fields are empty i mean i have only the default fields of the form and not my json string result. The problem is when i pass the array to the post method.
Can you help me ??
list.push(JSON.stringify(request));
var jsonstr = {'':list};
You can not have object with empty key.make it like
list.push(request);
var jsonstr = JSON.stringify(list);
So with:
var list = new Array();
list.push(JSON.stringify(request));
var jsonstr = { '' : list };
$.ajax({
type: "POST",
url: "http://localhost:4556/Pay_Info",
dataType: "json",
data: jsonstr,
traditional: true,
something pass in the post method but the fields are with default values and not with my json string value. When i debug the count of the list is 1
With:
list.push(request);
var jsonstr = JSON.stringify(list);
$.ajax({
type: "POST",
url: "http://localhost:4556/Pay_Info",
dataType: "json",
data: jsonstr,
traditional: true,
In the list of post method the count was 0 and nothing pass
With:
var jsonstr = {Key:list}; or var jsonstr = {"Pay":list};
The count of the list in post method is 0 so nothing is passed

Invalid JSON Primitive when using a variable

I have code that makes an AJAX call to an MVC controller method and it'll work without a hitch if I do this:
var obj = '{"titlename":"whatever"}';
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
But if I do this:
var stringed="whatever"
var obj = '{"titlename":stringed}';
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
It craps out on me with an "invalid JSON primitive" error. I keep trying various single and double quote permutations, but they all keep giving me the same error. How can I insert a string variable into a JSON object?
Try this:
var stringed = "whatever";
var obj = '{"titlename": "' + stringed + '"}';
Also you may want to take a look at a JSON2 library, which can stringify your data automatically.
Why are you declaring your object as a String?
Have you tried doing:
var stringed="whatever";
var obj = {
"titlename":stringed
};
var obj = {"titlename":stringed};
This is probably what you need.
Try this:
var stringed="whatever";
var obj = {"titlename": stringed};
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
What you had was just a string that contained the the string "stringed", you need a object literal.
jQuery can take an object and it'll take care of sending the json string to the server instead.
You should do:
var stringed="whatever";
var obj_as_object = {titlename: stringed};
var obj_as_string = JSON.stringify(obj_as_object);
...
data: obj_as_string //This goes in your ajax call
With this, we're auto encoding the obj with JSON.
JSON.stringify will work in modern browsers. If you want support to an older browser (for example, IE6) you should use a library such as json2 from http://json.org.
Hope this helps. Cheers
This isn't a great way to do it but..
var stringed="whatever"
var obj = '{"titlename":'+stringed+'}';
Or
var obj = {
"titlename":stringed
}

Categories

Resources