Home > Software design >  Ajax function returning echo instead of value
Ajax function returning echo instead of value

Time:10-23

I need to update a span element with a value from an update PHP function (that performs mySQL queries), triggered after a button click. I used jQuery/Ajax to achieve this, via a function in another file.

Apparently PHP logs in this case require the following form:

echo '<script> console.log("My message"); </script>';

So I put these in my PHP function file, which looks like the following:

if(isset($_POST['myAction'])) {
    if ($_POST['myAction'] == "right_action") {
        echo '<script> console.log("ENTERED"); </script>';
        update(...)
        ...
    }
}

function init()
{       
    ...
    echo '<script> console.log("Successfully connected to database"); </script>';
    return ...;
}

function fetch(...) {
    init();
    ...
    echo '<script> console.log("Database fetch successful"); </script>';
    echo '<script> console.log(' . result . '); </script>'; // equals 49
    return ...;
}

function update(...) {  
    init();
    ... 
    echo '<script> console.log("Database update successful"); </script>';   
    return fetch(...);
}

On the one hand, the logs appear properly while the PHP is executing.

However it seems that the return value of the update PHP function, from the perspective of the Ajax function, contains all the logs. Here is the Ajax function:

$.ajax({
            method: "POST",
            url: "my_php_file.php",
            data: { myAction: 'myAction',
                    (params) },
            success: function(result) {
                console.log("Success at Ajax transfer-to-PHP");
                console.log("RESULT: "   result);
                spanElement.load(result);       
            },
            error: function(error) {
                console.log("Error at Ajax transfer-to-PHP: "   error);
            }
        });

And the Ajax log:

RESULT
<script> console.log("ENTERED"); </script><script> console.log("Successfully connected to database"); </script><script> console.log("Database update successful"); </script><script> console.log("Successfully connected to database"); </script><script> console.log("Database fetch successful"); </script><script> console.log(49); </script>

The same behavior happens when I print in Ajax the content of the span element, initially filled with the result from the fetch PHP function. It prints all the logs; but then it does print the value (while the update mechanic above doesn't even).

CodePudding user response:

I think you are approaching this very unusually, and making things quite hard for yourself. I've never seen PHP returning Javascript to do console.log() before. I'm sure it works, and maybe it really suits what you need, but it seems very Rube Goldberg-ish to me.

If you want to generate logs of what your PHP is doing, just do it in PHP on the server. You can then monitor your application log on the server.

If you want a response from your PHP that your browser can handle and use to update your page, just return the response as text, or better yet as JSON, so you can include eg a status as well as a message. If you really want to pass log messages back to the browser, you could structure the response to include a log element which will be logged to the console, along with a message element to display to the user. You might want to include a status or success element, which is true or false.

There are thousands of examples here on SO, here's a highly ranked one, here's a simpler one, but searching for anything like "php ajax example" will turn up plenty more for inspiration.

As to why your result includes multiple msgs, just trace through what your PHP is doing - each step echoes a message, one after the other. They're all part of the content returned to your Javascript.

I see one bug in your Javascript - .load() loads content from the specified URL. You've already loaded content with your .ajax(), and result is not a URL, so that isn't doing what you expect and won't work.

Here's some clunky pseudo-code which skips over some specifics but gives you a general idea. If you want to keep a running log of each step as you are currently, you'll have to pass your $response array around to/from your functions, or if this is a PHP class make it a class property to avoid that. If you just log to the server you can avoid that, since you only need the final result of your update().

$response = [];

if(isset($_POST['myAction'])) {
    if ($_POST['myAction'] == "right_action") {
        
        // If you really want to return log msgs to the browser 
        $response['log'][] = 'ENTERED';
        
        // More appropriate might be to just log them in PHP.  How you do that is
        // up to you, eg if you are using a library or just your own simple fopen(),
        // fwrite() etc.  Though you might not want this level of detail after initial
        // development.
        // myLogger('Entered'); 
        
        // In this pseudo-code you'll have to include $response as parameter passed 
        // to your functions so they can update it, and they'll have to return it
        update(...)
        ...
    }
}

// Return your response as JSON which is easy for JS to work with
header('Content-Type: application/json');
echo json_encode($response);

function init()
{
    ...
    $response['log'][] = 'Successfully connected to database';
    // myLogger('Successfully connected to database')
    return ...;
}

function fetch(...) {
    init();
    ...
    $response['log'][] = 'Database fetch successful';
    $response['message'] = $result;
    // myLogger('Database fetch successful')
    return ...;
}

function update(...) {
    init();
    ...
    $response['log'][] = 'Database update successful';
    // myLogger('Database update successful')
    return fetch(...);
}

Then your Javascrtipt can do something like:

$.ajax({
    method: "POST",
    url: "my_php_file.php",
    data: {
        myAction: 'myAction',
        (params)
    },
    success: function(result) {
        console.log("Success at Ajax transfer-to-PHP");

        // Log your log msgs
        console.log("RESULT:");
        console.dir(result.log);

        // .load() will load the specified remote content, similar to .ajax()
        // spanElement.load(result);

        // You can use .html() or .text() to update your span
        // https://api.jquery.com/html/
        spanElement.html(result.message);
    },
    error: function(error) {
        console.log("Error at Ajax transfer-to-PHP: "   error);
    }
});
  • Related