views:

55

answers:

2

I want to have a simple function where i can insert a sqlQuery and get a database answer in json-format like this:

  function ExecuteQuery(query){
    $.post("sql.php", { "query": query },
     function(data){ return data;  },
     "json");
   }

The response i get is undefined, I think i have misunderstood something quite basic but i don't know what, can anybody give me a hint?

A: 

You need to do something with the data - you can't just return it. The outer function returns instantly, but the inner function returns later, after the server round-trip. Try doing alert(data) to see how it works.

Skilldrick
Yes it works well but the ting is i want to return the data, i have tried to save the data too but same problem
Cinaird
+1  A: 

The problem is that you want something you cannot have :-) Instead of thinking in terms of a function that returns a value, write yourself a function that takes another function as an argument and calls it when the data is available.

function ExecuteQuery(query, callback){
  $.post("sql.php", { "query": query },
   function(data){ callback(data);  },
   "json");
 }

Now, when you call that function, you'll pass it a function that can take the server response and do something with it.

ExecuteQuery("whatever", function(results) {
  // do something with "results"
});
Pointy
That was my first solution but i thought i could make it like a return-function. But you kind of solved my problem, now i don't need to try it any more, thanks!
Cinaird
You don't need to say `function(data){ callback(data); }`, you can just say `callback`, can't you?
Skilldrick
indeed you can Skilldrick
redsquare
Yes if you've already got a named function sitting around, that's fine!
Pointy