0

can someone point me out how can I send JavaScript variables with AJAX.

JavaScript:

var d=new Date();
document.write(d);

AJAX:

$.ajax
        ({
          type: 'POST',
          url: 'save.php',
          cache: false,
          data: { document.write(d); // Just for example
},

Everything else works great. Thanks.

3 Answers 3

2

You can't send "variables". You can only send strings (or things which can be turned into strings). (You can store those strings in variables).

A date object (which you store in d) can be converted into a string, so you could send that.

The return value of document.write() will always be undefined, so it doesn't make much sense to send that.

You appear to be using jQuery. The data property expects a standard JavaScript object. An object consists of a bunch of key/value pairs. You need to provide a key for your value.

data: { date: d }
Sign up to request clarification or add additional context in comments.

Comments

1

you could pass the value to any parameter name you want like date parameter in this example:

$.ajax({
    type: 'POST',
    url: 'save.php',
    cache: false,
    data: { date: new Date()}
});

Or you could just use the variable like this:

    var d = new Date();
    $.ajax({
        type: 'POST',
        url: 'save.php',
        cache: false,
        data: { date: d}
    });

Comments

-1

Use JSON.stringify() to convert your objects to JSON format:

$.ajax
    ({
      type: 'POST',
      url: 'save.php',
      cache: false,
      data: JSON.stringify(d)
},

On the server side, of course, you would have to use a JSON parser to interpret the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.