-1

I just can't get my head around it. What do I need to write in my php file to return something to the $.post function?

<script type="text/javascript">
    function SubmitToDatabase(uName, uComment)
    {
        $.post("write_something_to_mysql_b.php", {name: uName, comment: uComment});
        return false;
    }
</script> 

This works, but there is no return value from the PHP file

hohner
  • 11,498
  • 8
  • 49
  • 84
wubbewubbewubbe
  • 711
  • 1
  • 9
  • 20
  • 1
    This is nothing to do with PHP; this is the basic properties of the asynchronous nature of AJAX requests; http://stackoverflow.com/questions/562412/return-value-from-function-with-an-ajax-call – Matt Jan 19 '13 at 15:26
  • Read up on [jQuery.post()](http://api.jquery.com/jQuery.post/). There are a ton of working examples. – SeanWM Jan 19 '13 at 15:26
  • 1
    use complete callback ... as noted read in docs how to do it – charlietfl Jan 19 '13 at 15:27

3 Answers3

2
// php:
$output['result']    = 'hello!!!';
echo json_encode($output); // json encode here
exit;

// jquery:
$.post(
"write_something_to_mysql_b.php",
{
    name : uName,
    comment : uComment
},
function(output) { // callback function to catch your php output
    // console.debug(output['result']);
    alert(output['result']);
    // output hello!!!
},
'json'); // json requirement here

json is just one of the possibilities to require data from backend side. Others are: xml, json, script, text, html. For each one of these formats you must to return data from backend in a suitable way. For example for text just echo 'hello!!!; exit;

Igor Parra
  • 10,214
  • 10
  • 69
  • 101
1

First of all, make sure jQuery is hitting your PHP file. Use the developer tools in Chrome or download Firebug for Firefix, go to the 'Network' tab and when your JavaScript function SubmitToDatabase() is executed, check to see any network activity. If it's accessing the wrong PHP page, it'll show a 404.

If it's accessing the correct PHP page, check Firebug to see what value is returned. To return a value in PHP for a JavaScript call, you need to make sure you're using echo rather than return.

hohner
  • 11,498
  • 8
  • 49
  • 84
1

See jQuery.post(). You must add a success function, if you want to do something with the PHP result

function SubmitToDatabase(uName, uComment)
{
    $.post("write_something_to_mysql_b.php", {name: uName, comment: uComment},
        function(data) { alert(data); });
    return false;
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198