Sending a parameter from Javascript to a controller - javascript

I'm modifying an ASP.NET project that I didn't worked on before.
I added a datepicker object :
<input id="datepicker" />
<script>
$("#datepicker").kendoDatePicker({
value: new Date()
change: UpdateVehiculesSurSite
});
</script>
And tried to modify the "UpdateVehiculesEnAttente" method to send the date picked to my controller :
function UpdateVehiculesEnAttente(){
var datepicker = $("#datepicker").data("kendoDatePicker");
console.log(typeof datepicker);
if (datepicker!==null && typeof datepicker !== "undefined"){
var value = datepicker.value();
console.log(value);
value = kendo.toString(value,"dd/MM/yyyy")
alert(value);
$(document).ready($.ajax({
url: 'Entrees_Sorties/Get_Vehicules_EnAttente',
type: 'POST',
data: {'date' : value},
contentType: 'application/json',
success: function (retour) {
$("#DivVehiculesEnAttente").html(retour);
console.log("update attente success");
},
error: function (xhr, status, error) {
montrerNotificationNoConnexion();
}
}));
//}
return false;
}
The first problem is that the project run the javascript file first, so the datepicker isn't initialized. To try my Controller method, I gave "value" a date.
My controller method is the following :
public ActionResult Get_Vehicules_EnAttente([DataSourceRequest] DataSourceRequest request, string date){
try{
List<List<Vehicule>> Data = new List<List<Vehicule>>();
DateTime dt = Convert.ToDateTime(date);
Data.Add(Models.Vehicule.Get_Vehicules_EnAttente_ByDate(dt, true));
return PartialView("VehiculesEnAttente", Data);
} catch (Exception e) {
WorkflowWCF.Log.enregistrer_erreur(new Exception("Une erreur est survenue lors de la récupération des véhicules planifiés", e));
return Json(new List<Vehicule>().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
}
The result is that my Ajax request return error and launch the "montrerNotificationNoConnexion" method.
Any idea why ?
EDIT :
Using Firebug, I get this
Do you think the problem could be that "date" contain "17%2F02%2F2016" instead of "17/02/2016" ?
EDIT2 : One of the problem was the string format. I changed it to "02/17/2016" but still not working.

You are defining your content type as contentType: 'application/json',
and then send data as simple text.
You should remove so that jquery uses the default 'application/x-www-form-urlencoded; charset=UTF-8' type.

You have to send the date in ISO 8601 format, then the MVC modelbinder can bind it.
var GlobalJsHelpers = GlobalJsHelpers || {};
/// <summary>
/// Takes a utc js date and converts it to a iso8601 utc string
/// </summary>
GlobalJsHelpers.Iso8601FromUtc = function(utcDate) {
//create a two digit month string (01-12)
var month = ('0' + (utcDate.getUTCMonth() + 1)).substr(-2);
//create a two digit day string (01-31)
var day = ('0' + utcDate.getUTCDate()).substr(-2);
return utcDate.getUTCFullYear() + '-' + month + '-' + day;
};
Usage:
data: {'date' : GlobalJsHelpers.Iso8601FromUtc(dateValueInUtc)}

Related

How to fix a MultiValueDictKeyError

I am trying to get the time spent on each page in a Django project using Javascript. I keep getting an error so I am trying to fix it
the error:
MultiValueDictKeyError at /backendurl/
'timeSpent'
Highlighted line of error in views.py:
timeSpent = request.POST['timeSpent']
Here is the javascript in template:
<script>
$(document).ready(function() {
var startDate = new Date();
$(window).unload(function() {
var endDate = new Date();
$.ajax({
type: POST,
url: "backendurl", // be mindful of url names
data: {
'timeSpent': endDate - startDate || 'none' // defaults to a string
},
success: function(response) {
// unpack response:
status = response.status
}
})
</script>
Here is the views.py:
def my_view_function(request):
timeSpent = request.POST['timeSpent']
response = json.dumps({
'timeSpent' : timeSpent,
})
return HttpResponse(response)
Here is the url.py
path('backendurl/', views.my_view_function, name='backendurl'),
In most probability, the key 'timeSpent' is not present in request.POST.
To get the key's value from request.POST dict you need to use the MultiValuedDict's get method.
You can also put a default to know that you have not got the key in your request, -1 in this case below.
timeSpent = request.POST.get('timeSpent', -1)

Json date to Javascript date in Asp.net core

net core 3.1 mvc web app. On my server I do:
[HttpGet]
public IActionResult LastDate()
{
DateTime send = DateTime.Now;
try
{
send = _db.MySend.ToList().Max(x => x.Date).GetValueOrDefault().AddDays(1);
}
catch { }
return Json( new { date = send });
}
then on my Front-end I do:
var link = 'MYLINK';
var args = {};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
var my_date = data.date;
document.getElementById('Dateee').value = my_date;
},
error: function () {
alert("Error.");
return;
}
});
I have tried to convert Json date to Javascript but I am unable. Thanks for any help.
EDIT: 1. I am using Microsoft.AspNetCore.Mvc Json.
2. My localization that affects date:
var supportedCultures = new[]{
new CultureInfo("cs-CZ")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("cs-CZ"),
SupportedCultures = supportedCultures,
FallBackToParentCultures = false
});
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("cs-CZ");```
The JSON specification does not prescribe any particular representation for date+time values (annoyingly...).
So there are a variety of formats and approaches for sending .NET DateTime and JS Date values via JSON.
Such as sending the UNIX time in milliseconds.
Or sending an ISO 8601-formatted string
Or the horrible format that ASP.NET AJAX used between 2005 and ~2012 that looked like "/Date(12345)/" (what on earth where they thinking?!).
Absent any further information in your post, I recommend serializing the value using an ISO 8601 string, which has the advantage of being compatible with HTML5's <input type="date" /> via the Date constructor and the valueAsDate property.
While we're at it, let's make your controller action async (as it looks like you're using Entity Framework).
And let's make your client-side code use async fetch.
PLEASE EVERYONE STOP USING JQUERY IT'S 2020 FOR TIM BERNERS-LEE'S SAKE STOP USING IRRELEVANT AND OBSOLETE CLIENT-SIDE LIBRARIES FROM 10 YEARS AGO AIAIIEIEIEIEIEIIE
Like so:
[HttpGet]
public async Task<IActionResult> LastDate()
{
DateTime value = await this._db.MySend.MaxAsync( x => x.Date );
DateTime send = value.AddDays(1);
String formatted = send.ToString( "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture );
return this.Json( new { date = formatted } );
}
Client-side:
try {
const resp = await fetch( link );
if( resp.status === 200 ) {
const obj = await resp.json();
const dateStr = obj.date; // string
const date = new Date( dateStr );
document.getElementById('Dateee').valueAsDate = date;
}
}
catch( err ) {
alert( "Error: " + err );
}

$.parseJSON(data, true) throws

I am working in ASP.NET MVC 5.
I am trying to deserialize dates coming from the server in JSON format. The JSON arrives and when I try to deserialize the dates the debugger just stops and don't show any errors other the in the console, which I can't understand.
This is my code so far:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '/Home/GetDates',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (dates) {
var date = dates[0];
var desDate = $.parseJSON(date, true);
console.log(desDate);
}
});
});
Here are some pics on the errormessage and that a have data coming in.
Here is a link to the docs I have been looking at. Docs
The data returned from the ajax call is already parsed, so dates is an array containing strings, and dates[0] is the string/Date(14984....)/ etc.
To parse the string, remove everything but the numbers, and use that timestamp to create a Date object.
$(document).ready(function () {
$.ajax({
type : 'GET',
url : '/Home/GetDates',
dataType : "json",
contentType : "application/json; charset=utf-8",
success: function (dates) {
var d = dates[0];
var unix = +d.replace(/\D/g, '');
var date = new Date(unix);
var desDate = date.getFullYear() + '/' +
(date.getMonth()+1) + '/' +
date.getDate();
console.log(desDate);
}
});
});
You need to execute the JavaScript inside your string variable as
var dateVar = eval(dates[0]);
This will give you the date but not in a proper format which you want. For the proper format user either moment.js or simply create your own lines of code like
var finalDate = new Date(dateVar).toISOString().split('T')[0];
console.log(finalDate);
The new Date() is again needed here so that we can make use of toISOString() and get the proper date format.
Because you are referring to this jQuery parseJSON automatic date conversion for Asp.net and ISO date strings you need to include the jQuery extension defined there.
Indeed, in jQuery parseJSON(jsonString) accepts only one argument while you are using an extension.
Moreover, your dates variable is an array of string, and not a json string.
//
// Look at the end....
//
/*
* jQuery.parseJSON() extension (supports ISO & Asp.net date conversion)
*
* Version 1.0 (13 Jan 2011)
*
* Copyright (c) 2011 Robert Koritnik
* Licensed under the terms of the MIT license
* http://www.opensource.org/licenses/mit-license.php
*/
(function ($) {
// JSON RegExp
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var dateISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z/i;
var dateNet = /\/Date\((\d+)(?:-\d+)?\)\//i;
// replacer RegExp
var replaceISO = /"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?Z"/i;
var replaceNet = /"\\\/Date\((\d+)(?:-\d+)?\)\\\/"/i;
// determine JSON native support
var nativeJSON = (window.JSON && window.JSON.parse) ? true : false;
var extendedJSON = nativeJSON && window.JSON.parse('{"x":9}', function (k, v) {
return "Y";
}) === "Y";
var jsonDateConverter = function (key, value) {
if (typeof(value) === "string") {
if (dateISO.test(value)) {
return new Date(value);
}
if (dateNet.test(value)) {
return new Date(parseInt(dateNet.exec(value)[1], 10));
}
}
return value;
};
$.extend({
parseJSON: function (data, convertDates) {
/// <summary>Takes a well-formed JSON string and returns the resulting JavaScript object.</summary>
/// <param name="data" type="String">The JSON string to parse.</param>
/// <param name="convertDates" optional="true" type="Boolean">Set to true when you want ISO/Asp.net dates to be auto-converted to dates.</param>
if (typeof data !== "string" || !data) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim(data);
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (rvalidchars.test(data
.replace(rvalidescape, "#")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, ""))) {
// Try to use the native JSON parser
if (extendedJSON || (nativeJSON && convertDates !== true)) {
return window.JSON.parse(data, convertDates === true ? jsonDateConverter : undefined);
}
else {
data = convertDates === true ?
data.replace(replaceISO, "new Date(parseInt('$1',10),parseInt('$2',10)-1,parseInt('$3',10),parseInt('$4',10),parseInt('$5',10),parseInt('$6',10),(function(s){return parseInt(s,10)||0;})('$7'))")
.replace(replaceNet, "new Date($1)") :
data;
return (new Function("return " + data))();
}
} else {
$.error("Invalid JSON: " + data);
}
}
});
})(jQuery);
var date = '{"date": "\\/Date(1498435200000)\\/"}';
var desDate = $.parseJSON(date, true);
console.log(desDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to send a MySQL parameter

Hello I have the following trigger:
CREATE TRIGGER `update` AFTER UPDATE ON `table 1`
FOR EACH ROW INSERT INTO table 2 (
Id,
Revision,
Purpose,
Change
)
VALUES
(
OLD.Id,
OLD.Revision,
OLD.Purpose,
#purpose_change /* user variable */
);
$$
DELIMITER ;
I am using C# WebService, Ajax, and JavaScript. Here is my C# methods for update (at the moment doesnt work)
"UPDATE table 1 SET Revision=#revision, Purpose=#purpose, #purpose_change=#change WHERE (Id =#id)";
Here starts the problem, because I dont know exactly how to send #purpose_channge.
Here is my Web Method.
[WebMethod(EnableSession = true)]
public string ActualizarAlerta(int id, string revision, string purpose, string change, int op)
{
string respuesta = "An Error Has Ocurred.";
try
{
UpdateAlert ua = new UpdateAlert(id, revision, purpose, change);
int resp = conn.UpdateAlerta(ua, op);
if (resp > 0)
respuesta = "Works!.";
}
catch (Exception ex)
{
respuesta = "An Error Has Ocurred: " + ex.Message;
}
return respuesta;
}
And here is my JavaScript with AJAX call.
$.ajax({
type: "POST",
url: urlServer + "ws_alerts.asmx/ActualizarAlerta",
data: '{' +
'"id":' + id +
',"revision":"' + rev +
'","purpose":"' + pur +
'","change":"' + change +
'","op":' + op + '}',
dataType: "json",
contentType: "application/json",
timeout: 60000,
error: function (xhr) {
bootbox.alert("Ocurrio un error al procesar la peticion.");
},
success: function (data) {
bootbox.alert(data.d);
}
});
id, rev, change, etc. Are $('#MyId').val()
I know that all the problem is in the Update query but I dont know how to do it correctly, how can I do that?
That is a mysql user variable, you must run a raw query before UpdateAlerta()
SqlCommand cmd = new SqlCommand("set #purpose_change = 'Purpose change to 1';", conn);
cmd.ExecuteNonQuery();
ps (I remember another related question here )

How to pass json data via ajax?

I am working a visual studio 2012 MVC program.
I use ajax to send data to a controller and wish the controller returns a body of html. the data is in json format. the data is a string name and decimal TotFees.
I found that the parameters value in the public ActionResult ImmPay(string Name) in the controller are always null. Finally I tried just to pass name, but the value of name in the controller side is still null.
what is wrong in my code, and how to solve the problem? Thank you.
View:
function ImmPay()
{
var name = "ASP";
var TotFees = 100.01;
//var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "\'}";
//var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "m\'}";
dd = "{\'b\':\'" + b + "\'}";
dd = JSON.stringify(dd);
$.ajax({
url: '#Url.Action("ImmPay", "Consult")',
type: 'GET',
async: true,
data: dd,
contentType: 'application/json',
context: document.body,
success: function (response, textStatus, jqXHR) {
$("#dialog-immpay").html(response);
$("#dialog-immpay").dialog("open");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
},
complete: function () {
;
}
});
}
Controller:
public ActionResult ImmPay(string Name)
{
do something here
}
JSON.stringify takes an object or an array and converts it into JSON, so you can build your data into an object and stringify it like so
dd = JSON.stringify({b: b});

Categories