0

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?

1

2 Answers 2

1

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"
});
Sign up to request clarification or add additional context in comments.

3 Comments

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!
You don't need to say function(data){ callback(data); }, you can just say callback, can't you?
Yes if you've already got a named function sitting around, that's fine!
0

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.

1 Comment

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

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.