Reputation: 2018
I've got this code:
function nameToCode(nameGroup) {
$.post("execute.php", { something: sendSomething }, function(data) {
return data;
});
}
variable = nameToCode("some text");
But only thing I get to variable is undefined, any ideas? Thanks.
Upvotes: 0
Views: 3231
Reputation: 429
You cant get callback like this. There is a async problem. You can use.ajax instead of .post;
function nameToCode(nameGroup, callback) {
$.ajax({
url: 'execute.php',
type: 'POST',
aysnc:false,
data: 'something=sendSomething',
success: function(data) {
return data;
}
});
this will work.
you mean, it doesn't work or you don't like the solution?
It's about javascript working process. js does not wait any sync operation. you could do your work in success function block or you have to use async:false parameter. I suggested do whatever you want in success function block. If you use aysnc:false, it will block your browser for a short time.
Upvotes: -1
Reputation: 121
The fourth parameter for $.post
is the dataType.
You can set this to JSON for your return data to be parsed into a JavaScript object or array.
$.post(
"execute.php",
{ something: sendSomething },
function(data){ return data; },
'json');
In your execute.php file, you can do something like
<?php
$return_data=array('nameToCode'=>'some text');
header('Content-Type: application/json');
echo json_encode($return_data);
exit();
Upvotes: 1
Reputation: 16718
The result won't be available immediately, so you'll have to structure your code a bit differently:
function nameToCode(nameGroup, callback) {
$.post("execute.php", { something: sendSomething }, function(data) {
callback(data);
});
}
nameToCode("some text", function(variable)
{
/* use variable here */
});
Upvotes: 4