AJAX Form is submitting to itself?

前端 未结 2 1039
别跟我提以往
别跟我提以往 2021-01-28 02:32

I don\'t know what is going on here tonight, but I can\'t seem to get AJAX working. When the form is submitted, it refreshes the page with the values in the URL. I\'m using a va

相关标签:
2条回答
  • 2021-01-28 02:47

    you need to cancel the default behaviour of submit button

    $(".button").click(function(e) {
                e.preventDefault();
                //rest of your code here
                var dataString = "fname=" + $("#firstName").val();
                alert(dataString);
                $.ajax({
    
    0 讨论(0)
  • 2021-01-28 02:51

    You need to cancel the default behaviour of the submit button(submit the form not ajax).
    It can be done with preverntDefault() on the event object or with return false;

       $(".button").click(function(e) {
            var dataString = "fname=" + $("#firstName").val();
            alert(dataString);
            $.ajax({
                type: "POST",
                url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
                data: dataString,
                success: function(result) {
                    if(result == "Success"){
                        alert("Success");
                    }else{
                        alert("Fail");
                    }
                }
            });
            return false; /// <=== that was missing.
            e.preventDefault(); /// Or this.
        });
    

    There is a submit event, so better listen to this event instead of the click button:

       $("#contact_form").submit(function(e) {
            var dataString = "fname=" + $("#firstName").val();
            alert(dataString);
            $.ajax({
                type: "POST",
                url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
                data: dataString,
                success: function(result) {
                    if(result == "Success"){
                        alert("Success");
                    }else{
                        alert("Fail");
                    }
                }
            });
            return false; /// <=== that was missing.
            e.preventDefault();  /// Or this.
        });
    
    0 讨论(0)
提交回复
热议问题