Nick Nick - 6 months ago 12
Ajax Question

Form post but do not reload the page

I am stuck in this like I have never before.

My situation : I am making a shopping cart. When user click "Add" button, it posts the form and in the server side i.e inside if(IsPost){....}, corresponding item gets added to the the the cart table in my database.

Everything is fine, except it reloads the page and scrolls back to top. With a little research, I got to know that may be Ajax could help. Then I created a new .cshtml page add-to-cart.cshtnl. Now my current page doesn't reload but it opens add-to-cart.cshtml which is not how I wanted. Now I even tried to learn AJAX and try doing things looking at examples. Nothing helps. Please help!

Here is what my code looks like : P.S I am using razor in webmatrix.

<form method="post" id="productForm" action="~/add-to-cart.cshtml">
<input ............"Input Something.............../>
<button type="submit" id="add-button" >ADD</button>
</form>


At my add-to-cart.cshtml, I don't have anything on the UI. It just processes data.I don't want that page to ever load. It looks something like this:

ifIsPost(){
............ADD item to the cart table of database..............
}


Now I am convinced, AJAX is my solution but how????
Please don't give me incomplete answers. I have already wasted 3 days in it :/

Answer

Try this

$('#productForm').submit(function(e) {
    e.preventDefault();

    $.ajax({
       type: 'POST',
       url: $(this).attr('action'),
       data : $(this).serialize(),
       success : function(response) {
           //write your code here
       },
       error : fucntion(response) {
           //write your code here
       }
   });
});

Put this script into <script> tag.

Note: Don't forgot to include jquery in your page.

Comments