Ajax always refesh page on success

I have built a successful the implementation of Ajax on my Java Web App on a registry of Contacts, but when I registry a new contact on the success of the ajax my page refreshes! I don't want my page to refresh on success, I just want to show a success message. Here is my code:

alta: function () {
        $.ajax({
            type: "POST",
            cache: false,
            timeout: 30000,
            dataType: "json",
            url: "altaContacto.con", //servlet
            data: {
                name: $("#name").val(),
                email: $("#email").val(),
                phone: $("#phone").val(),
                company: $("#company").val(),
                subject: $("#subject").val(),
                message: $("#message").val()
            },
            success: function (data)
            {
                if (data.estatus === "OK")
                {
                    alert("Tnx for registry.");
                } else
                {
                    alert("Error");
                }
            } //END OF SUCCESS
        });
    }

Is there something I'm missing? Many Thanks!

Upvotes: 1

Views: 72

Answers (2)

user4787666
user4787666

Reputation:

When you call this function you must also stop default propagation of the form. For example:

$('#submit').on('click', function () {
    alta(); // call the function
    return false;
});

That's all

Upvotes: 2

I think, you must add in your function 'alta' the event handler i.e,. alta : funtiton(event), and after that you added the event handler, in the end, you need cancel the event without stopping further propagation of the event. Proof this code:

alta: function (event) { $.ajax({ type: "POST", cache: false, timeout: 30000, dataType: "json", url: "altaContacto.con", //servlet data: { name: $("#name").val(), email: $("#email").val(), phone: $("#phone").val(), company: $("#company").val(), subject: $("#subject").val(), message: $("#message").val() }, success: function (data) { if (data.estatus === "OK") { alert("Tnx for registry."); } else { alert("Error"); } } //END OF SUCCESS }); event.preventDefault(); }

I hope help you. For more information, visit this web: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

Upvotes: 1

Related Questions