Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery omits Date values in params() and ajax()

I have a simple Javascript object like this:

var data = { date: new Date(), plainText: "test" };

when I user $.params(data) to build a query string I get this:

plainText=test

Meanwhile the date value is omitted.

Likewise when I use $.ajax() the date value is missing as well.

Is there a way to get jQuery to include the date value as a parameter?

date.toString() or date.toJSON() would both be fine with me.

like image 793
Timm Avatar asked Oct 09 '22 16:10

Timm


2 Answers

$.params(data, true) will convert the date .toString() and it will appear in the result, but do you really want a textual represenation of the date? There's no one standard for converting dates into query strings, just choose the format you want and convert your date into it before sending it to the server...

Or convert to JSON.

like image 155
ori Avatar answered Oct 11 '22 07:10

ori


Use JSON.stringify(new Date()).

var data = { date: JSON.stringify(new Date()), plainText: "test" };

Note: This will get the time part from the date also.

JSON library is natively supported in all the browsers but for browsers which do not support it you can include this js file http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js

You can also use (new Date()).toJSON().

var data = { date: (new Date()).toJSON(), plainText: "test" };

If you just want the date part to be sent then you can use this.

var date = new Date();
//change the format as per your need, this is in mm/dd/yyyy format
date = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();

var data = { date: date, plainText: "test" };
like image 20
ShankarSangoli Avatar answered Oct 11 '22 05:10

ShankarSangoli