0

My javacript looks like this:

namespace ContactPage {
$(() => {

    //contact info
    let $firstName = $('#first-name'), $lastName = $('#last-name'), $email = $('#email');
    //form
    let $form = $('#main-form');
    $form.submit(() => {
        let data = $form.serialize();
        var post = $.post('/contact', data, function () {
            console.log('posted');
        });

        post.done(function (data) {
            console.log('done', data);
        })
        .fail(function (data) {
            console.log('fail', data);
        })
        .always(function (data) {
            console.log('always', data);
        });
    });
});

}

The MVC .net C# controller receives the data successfully (code shown below), however, the javascript doesn't wait for the response and the browser ends up displaying the Json. What am I missing?

    [HttpPost]
    public ActionResult Index(ContactModel model)
    {
        var cl = seretContext.ContactLogs.Create();

        cl.Email = model.email;
        cl.Comment = model.message;

        seretContext.Set<ContactLog>().Add(cl);
        seretContext.SaveChanges();

        return Json(new { redirectTo = "/" });
    }

And the cshtml has a submit button as below:

<div class="text-center">
                <button id="orderForm" class="btn btn-success btn-lg" type="submit" >Send</button>
            </div>

The browser immediately displays the raw Json...instead of receiving the Json so it can be processed.

Browser displays {"redirectTo":"/"}

  • Please add a [mcve] which shows the actual problem (but I would guess that you don't prevent the submission of the form). – Andreas Feb 27 '19 at 18:18
  • OK i've added the complete typescript file and the cshtml - the typescript contains the suggestion below from @Nicolay – Matt Forrester Feb 27 '19 at 21:41

2 Answers2

0

Can you try something like this to catch all of the possible results?

var post = $.post('/contact', function(){
    console.log('posted');
});

post.done(function(data) {
    console.log('done', data);
})
.fail(function(data) {
    console.log('fail', data);
})
.always(function(data) {
    console.log('always', data);
});
NickAndrews
  • 496
  • 2
  • 9
  • i've modified as you sugget but the console remains blank and the browser still displays just the raw json - i'm sure it must be something obvious but i can't figure it out – Matt Forrester Feb 27 '19 at 21:42
  • It's possible that your submit button is causing a post back, you can remove the type=submit and add an onclick handler to either button or in your jquery code. – NickAndrews Feb 27 '19 at 23:01
0

Turns out was a very dumb mistake - my apologies - the id of the form was misspelled and so the javascript wasn't even getting the form.

  • [How can I debug my JavaScript code?](https://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code) – Andreas Feb 28 '19 at 07:10