Reputation: 95
I have a method I'm trying to write that can post data to a php file and get the results and return the output in a variable. For some reason, my block of code is not working.
function post_get(){
var result = null;
$.post("modules/data.php", { "func": "getNameAndTime" },
function(data){
result = JSON.parse(data);
}, "json");
return result;
}
I get this error when using this method
SyntaxError: JSON Parse error: Unexpected identifier "undefined"
Upvotes: 0
Views: 353
Reputation: 95031
This is how your code should be written to take advantage of the asynchronous nature of ajax.
function post_get(){
return $.post("modules/data.php", { "func": "getNameAndTime" }, "json");
}
post_get().done(function(data){
// do stuff with data
console.log(data);
}).fail(function(){
console.log(arguments);
alert("FAIL.\nCheck the console.");
});
// Do not attempt to bring data from inside the above function to out here.
Upvotes: 7
Reputation: 173532
If your server returns proper JSON encoded output and sets the correct headers (Content-Type: application/json
), you can use data
immediately:
$.post("modules/data.php", {
"func": "getNameAndTime"
},
function(data){
console.log(data);
}, "json");
// btw, at this point in the code you won't have access to the return value
In fact, even if it didn't return proper data, the console.log(data)
should provide you with enough information to figure out why it wasn't working in the first place.
Upvotes: 1