G
G
Grigory Vashkevich2015-03-19 00:46:31
JavaScript
Grigory Vashkevich, 2015-03-19 00:46:31

How to handle ajax form response?

The page has a table and a form that allows you to add an entry to the database. The form is sent to the server with an ajax request. You need to validate the form on the server. If there are errors in it, pass the model from the controller back to the form and display a description of the errors. If there are no errors in the form, update the table.

This is how the controller works:

[HttpPost]
        public ActionResult Add(NewsViewModel news)
        {
            if (ModelState.IsValid)
            {
                //сохраняем все в бд...
                
                return View('NewsList', db.News);
            }
            return View(news);
        }


How to differentiate between these 2 responses on the client side so I know what to do with them?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor Pushkarsky, 2015-03-19
@RainMEN

Use JSON to pass data from the script.
For example :

var success = 'Ваше сообщение успешно доставлено! </br> Благодарим за обращение :)'


$('form').submit(function(e){

    var form = $(this);

    $.ajax({
        type: form.attr('method'),
        data: form.serialize(),
        dataType: "json",
        url: form.attr('action'),
        beforeSend: function() {
            //alert('Подождите');
            //показываем загрузку если она нужна
            //можем выключать кнопку отправки
        },
        success: function(data) {
            if (data == 1){
                form.children('.alert').removeClass('danger').addClass('success').html(success);
            }
            else {
                form.children('.alert').removeClass('success').addClass('danger').html(data.errors);
            }
        }
    });

    e.preventDefault();

});

from PHP pass something like this
$data = ['errors' => 'сюда пишите ошибку'];
                return json_encode($data);

G
Grigory Vashkevich, 2015-03-19
@konar

Did the asp.net mvc tag confuse you?
OK. Then tell me how to get the partial view markup string in the controller...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question