0

trying to understand all this about AJAX, first of all I wanted to know how to refresh a page and keep my position on the page, which was possible, however, that was not the case on form post, that just jumped me right back to the top.

So after searching around on how to solve that, posting with AJAX seems to be my solution, I just can't seem to get all of it.

<form method="post" action="~/getAJAX.cshtml" id="ajaxform">
        <input type="text" name="kg" id="kg"  />
        <input type="submit" />
</form>
<script type="text/javascript">
    $(function () {
        $('#ajaxform').submit(function (event) {
            event.preventDefault(); // Prevent the form from submitting via the browser
            var form = $(this);
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize()
            }).done(function (data) {
                // Optionally alert the user of success here...
            }).fail(function (data) {
                // Optionally alert the user of an error here...
            });
        });
    });
</script>

This is the code I have so far. The thing I do not understand is what exactly should be on my "action" page?

At the moment I put this on my action page.

var db = Database.Open("Database");

var getKG = Request.Form["kg"];

var query = "SELECT * FROM Test WHERE kg = @0";
db.Execute(query, getKG);

This is just a test, I don't really know what to expect or anything, I would like to show the results on the page I post from, any guiding for this please?

Note that this is not a MVC project, therefore my problems with finding any good solutions or help, it's just normal CSHTML files.

Pontus Svedberg
  • 285
  • 1
  • 3
  • 20
  • Sounds to me that you're bit mixing Ajax and Form functionality. Traditionally you can post form data to some e.g. server side PHP script that processes your form via action option. However since you included also Ajax I assume you have a REST api that you would like to utilize to process data instead. – Janne Feb 18 '17 at 21:24
  • Well, actually im not sure, I would just like to post my form and get my result by ajax to avoid a page reload, if that makes sense? @Janne – Pontus Svedberg Feb 18 '17 at 21:26
  • 1
    Check here then: http://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax – Janne Feb 18 '17 at 21:35
  • I'm sure thats a good read for someone who is not as stupid as me, but I have absolutely zero clue as what code goes on my action page, all info I can find is either PHP or MVC and no one really explains the called action page that contains the actual code that I assume even makes the ajax call work? – Pontus Svedberg Feb 18 '17 at 21:46

0 Answers0