Handle Server Response Differently When Saving Model Via Ajax


I have a page with a form displayed in a modal window to create a model.

I would like to post my form asynchronously via an AJAX link, and handle the server response differently based on whether the model was successfully saved or not.

If the model is saved successfully, my controller redirects to an action called ajaxView which uses renderPartial to return an HTML view of the newly saved model. I want the client to close the modal form window and insert the ajaxView into my document.

If the model is not saved (due to validation error, etc…), the controller returns via renderPartial the model’s form view and I want the client to insert the form view into the modal window.

My challenge is that in both case, my AJAX calls are treated as successful, and they both return fully formed HTML content. I don’t know how to implement a logic to handle the server’s response differently based on whether the HTML returned is an error form view or a model view.

Do you have any tip that would allow me to achieve this?

Thank you.


Instead of returning a string containing the HTML of your rendered view, you can return a JSON object containing an indicator to what you want the client to do.

Otherwise, have you considered / tried returning just the validation errors in case there are? See this thread to see what I mean: http://www.yiiframework.com/forum/index.php/topic/37075-form-validation-with-ajaxsubmitbutton/

yes, it’s a good idea. I could have my controller return a JSON object and then have the client send a request to either get the ajax view or the form with error, but it’s a bit cumbersome to add this extra logic on the client side.

I suppose I’ll do this if there isn’t any other option.

Thanks for the suggestion.

That’s not what I really meant :) You return the JSON object AND the html at the same time. The indicator just tells you what to do with the HTML.

oh, you mean have two properties in JSON object response, one for success and one for the HTML view?

That’s a great idea. I’ll try that. Thank you.