I am using the jquery plugin datatables and am trying to take advantage of the fnRender function to manipulate some data.
I have a php script that returns a JSON string from my $.post. Here is a sample response that I get from each post: {"description":"myvalue"}. I got this from the Google Chrome Developer Tools.
Here is my post function:
$.post("functions/getDescription.php", {gpn:oObj.aData[1]},
function(data) {
returnedVal = jQuery.parseJSON(data);
var test = returnedVal.description;
//alert(test);
return test;
});
Here is my php script:
$passedVal = mysql_real_escape_string(($_POST['gpn']));
$descriptionPrint = array('description' => "");
include 'db_include.php';
$getDescription = "SELECT part_number_description, description FROM unit_description
WHERE part_number_description = '$passedVal' ";
$result = mysql_query($getDescription,$db) or die(mysql_error($db));
while ($row = mysql_fetch_array($result)) {
extract($row);
$descriptionPrint = $description;
echo json_encode(array('description' => $descriptionPrint));
}
There is only one value returned from each query.
Every row alerts the right value but returns undefined.
If I replace javascript function with only a return value of a string or any generic value it works fine.
I feel like there has to be something silly I’m missing in all this. Any help is much appreciated and please let me know if you need more information (I know troubleshooting something running in a plugin like datatables can be frustrating). Thanks.
Because
$.postdoes not return the return value of the anonymous callback function you pass to it as its third argument.Since Ajax is asynchronous,
$.posteven returns before the callback function is executed.If you want to do something when the data gets back from the server, then the callback function has to to it (or call another function to do it).
This is the same reason that the following wouldn’t work: