Search code examples
phpjqueryajaxpostxmlhttprequest

PHP: How can I return data as response from $.post request?


I'm trying to create a simple post function with jQuery. The input is the name of the client and the response is it's information (address, phone, age, etc.). So far, I've got this:

Script:

$(document).ready(function(){
    $("#getClientInfo").on('click', function(){
        $.post("getClientInfo.php", {
            name: $('#name').val()
        }) .done(function(data){
            console.log(data);
        }) .fail(function(xhr){
            errorShow(xhr.responseText);
        })
    });

PHP:

$connection = include('dbConnection.php');
$name = $_POST['name'];
$query = mysqli_query($connection, "SELECT * FROM clients WHERE name = 
    $name");
$result = mysqli_fetch_array($query);
return $result;

I know it's really simple and it doesn-t implement exceptions or prevents SQL injections, but for now, I would only like to print the resulting array in console with the .done() function. However, it returns no response.

Any ideas? thank you in advance.

Edit: I want the array to be the response of the request so it's displayed here in Chrome:

Picture


Solution

  • You're not getting any output from your PHP file because your script has no lines that produce output.

    From the return manual page:

    If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call.

    So return does not produce output, but will assign a value to whatever is calling a function:

    function getSomething() {
        return 'something';
    }
    $something = getSomething();
    

    or will assign a value to whatever is including another file.

    index.php:

    <?php
    $value = include('otherpage.php');
    // $value == 'hello'
    

    otherpage.php:

    <?php
    return 'hello';
    

    Instead you need to do something like:

    echo json_encode($result);