General Ajax Response Handling

I thought about the idea to unify the response handling of AJAX requests.

E.g. When an AJAX request fails it would be nice if Yii2 could display the exception in a modal window, Alert-DIV or JavaScript alert.

Or are there already improvements implemented?

That really depends on the app. Modal isn’t always what’s desired.

This should be configurable for sure, and merely applies to Exceptions.

But it’s also worth to think about a common return format of AJAX requests where parts could be automatically forwarded to the configured option (modal, alert, user-flash, etc …).




{  

  status: 200  

  message: "It worked!"  

  data: {

    ....  

  }

}


{  

  status: 500

  message: "Request failed!"  

  data: {

    ....  

  }

}



I use something very similar to what you proposed. But instead of using the HTTP status code (which can be retrieved from the response object itself), I use an explicit success indicator:




{

  success: true,

  message: 'Ok',

  data: [1, 7, 9]

}


{

  success: false,

  message: 'There was an error handling your request. Please try again in a few minutes.',

  data: null

}



I think it also would make sense then to have something like


$this->renderAjax($success, $message, $data) 

in Controller.

We now have the Response object which supports different output formats, including JSON.

For AJAX requests, we recommend using JSON as the data communication format. By setting the response format to be JSON, you can simply return the data to be sent back as the return value of actions. If there’s any problem, you can throw an exception, and the exception will be automatically turned into a JSON result.

Sounds good.

But I searched the sources for “ajax” but haven’t found the code you describe, could you post a link? Thanks in advance.

This is not specific for AJAX. The relevant code is the web\Response and ErrorHandler class.

You may try: Yii::$app->response->format = ‘json’;, and then see how the result and exception will be sent to the browser.

Looks awesome!

And sorry, I was looking at outdated code in my fork.