Kr1
Kr1

Reputation: 1303

jQuery ajax: Cannot send dates?

I cannot send any date object through jQuery Ajax, why?

var nid = '99';     
var date = new Date("October 13, 2014 11:13:00");

$.ajax({
        data: { 
            nid: nid, 
            evs: date, 
        },
        type: 'POST',
        url: '/ajax/save_scheduler',
        dataType: "json",
        error:function(xhr,err){        
                return false;
        },
        success: function(res) {
            // console.log(res);
        }   
});

I am familiar with jQuery ajax. Usually I have any problem to send variables through it. But I am stocked there..

In server side, I can then catch $_POST['nid'], but cannot get $_POST['evs'].

$nid = $_POST['nid'];
$evs = $_POST['evs'];

I get this message:

Notice: Undefined index: evs in ajax_save_scheduler()

Can someone explain why?

/***** Edit ******/

In firebug, I cannot see the date in post tab of the query:

enter image description here

If I change the date line like this:

var evs = "October 13, 2014 11:13:00";

It works as usual.

Upvotes: 4

Views: 6114

Answers (3)

Felix Kling
Felix Kling

Reputation: 816364

There is a bug in jQuery 1.7.1 (and before probably) which handles some objects incorrectly. That was fixed in 1.7.2:

#10466: jQuery.param() mistakes wrapped primitives for deep objects

jQuery tried to traverse the properties of every object, even those that don't have any enumerable properties at all. This posed a problem for wrapped primitives, such as String, and Date.

Solution: Upgrade jQuery.

Upvotes: 3

SeFoSeF
SeFoSeF

Reputation: 19

if can you use string type, try toString();

data: { 
    nid: nid, 
    evs: date.toString()
},

Upvotes: 2

nyumerics
nyumerics

Reputation: 6547

You should refrain from sending such platform specific objects. Use only primitives. Change the line

var date = new Date("October 13, 2014 11:13:00");

to

var date = (new Date("October 13, 2014 11:13:00")).toString();

This seems pretty pointless here, but the point here is convert all objects to strings using some rule in your Javascript and parse them on the server-side to create server platform compliant Date object (if available).

Upvotes: 0

Related Questions