Return response and continue work

Hello Everybody, I’m using slim framework3, and need to configure that via ajax request, return success or error response, and continue backend process

Hello Ibrahim,

Do you mean creating a AJAX request to process something in the background and then display the results on the web page?

You can use Slim to handle the request for the backend process and have it return the success or error response. I would use JSON for the message payload as it is easy to parse in Javascript. You can use a 500 status code to indicate that the response is an error.

The \Slim\Http\Response class has a handy withJson() method you can use to return a PHP array as JSON. It also sets the correct JSON content type header for the response.

The route in Slim would like something look:

// route for ajax request
$app->post('/process', function($request, $response) {
    // insert call to backend process here
    // ...
    if ($success) {
        return $response->withJson(['status' => 'ok', 'answer' => 'Yes, it is.']);
    } else {
        return $response
            ->withJson(['status' => 'error', 'error' => 'Something went wrong processing this.'])

And here is an example of calling the process using Ajax in the background using javascript and jQuery:

$(function() {
    $('#my-button').click(function() {
        var $button = this;
        $button.disabled = true;

        // Ajax request to server using /process route
            .done(function(data) { console.log('Success! The answer is ' + data.answer); })
            .fail(function(req) { console.log('Fail! Message: ' + req.responseJSON.error); })
            .always(function() { $button.disabled = false; });

Hope that helps,