2

I am trying to make a query to an SQL database and I can't figure out why my code won't work. When I call the javascript function:

function calledfunction(){
var date = new Date(document.getElementById("datetime1").value);
var dateformat = "'"+date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " + date.getHours() +":" + date.getMinutes()+"'";
        alert("Value is: " + dateformat);
                microAjax("genjsonphp.php?stdt="+dateformat, function(data) {
                     //edited out
      }

I get the alert: Value is: '2011-12-6 0:0'

When I copy the value in the alert and paste it so the above code becomes:

function calledfunction(){
var date = new Date(document.getElementById("datetime1").value);
var dateformat = "'"+date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " + date.getHours() +":" + date.getMinutes()+"'";
        alert("Value is: " + dateformat);
dateformat = '2011-12-6 0:0';

                microAjax("genjsonphp.php?stdt="+dateformat, function(data) {
                     //edited out
      }

Then the code works fine. Does anyone have an idea what is going wrong?

1
  • As a side note, I think you should make your query string more URL "formatty". It might mess up your ajax otherwise microAjax("genjsonphp.php?stdt="+encodeURIComponent(dateformat), function(){}); Commented Apr 3, 2012 at 16:41

2 Answers 2

4

You're explicitly quoting the variable string:

 "'"+date.getFullYear() ...

so you're sending

genjsonphp.php?stdt='2011-12-6 0:0'

(note the single quotes)

In the second case you're sending:

genjsonphp.php?stdt=2011-12-6 0:0
Sign up to request clarification or add additional context in comments.

3 Comments

console.log the url's and you will see that Alex K. is correct.
so, var dateformat = '2011-12-6 0:0'; and var dateformat = "'"+date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " + date.getHours() +":" + date.getMinutes()+"'"; do not produce the same thing?
Nope; var X = 'A' is the 1 character string A whereas var X = "'" + 'A' + "'" is the 3 character long string 'A'
1

this "genjsonphp.php?stdt="+'2011-12-6 0:0' parses to: "genjsonphp.php?stdt=2011-12-6 0:0" while "genjsonphp.php?stdt="+dateformat parses to: "genjsonphp.php?stdt='2011-12-6 0:0'"

Watch the quotes.

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.