简体   繁体   中英

Submitting a form without refreshing page not working

I am trying to submit a form using AJAX to prevent the page from refreshing and then send the data to a MYSQL database in the background but I can't figure out what I am doing wrong. the page will correctly send data if I use action="SuggestionSchemeForm" with the form tag, however i would rather do this with AJAX to stop the page refreshing. I have looked at multiple questions and answers but cant find an answer that relates to my particular problem. can anyone see where I am going wrong with this/

my AJAX looks like this.

<script type="text javascript">
            $(function () 
            {
                $('SuggestionForm').on('submit', function (e) 
                {=det                               
                e.preventDefault();
                $.ajax(
                {
                    type: 'POST',
                    url: 'SuggestionSchemeForm.php',
                    dataType: 'html',
                    data: $('SuggestionForm').serialize(),
                    success: function () 
                    {
                        alert('form was submitted');
                    }
                });
                });
            });
</script>

This is my php file

<?php
if($_POST)
{
  require_once("../config.php");
  require_login(); 
  global $USER;

  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "FTSuggestionTest";
  $firstName = $USER->firstname;
  $lastName = $USER->lastname;
  $currentUser =$USER->currentUser;
  $userId = $USER->id;

  $a=date("Y-m-d H:i:s");



   // Create connection
   $conn = new mysqli($servername, $username, $password, $dbname);
   // Check connection
   if ($conn->connect_error) 
   {
       die("Connection failed: " . $conn->connect_error);
   }

   $sql = "INSERT INTO enquiries (Id, Name, JobTitle, Department, Site,Suggestion, Impact, Processed, Status, Date, Location, BuildingNo)
   VALUES ('$userId', '$_POST[firstname]', '$_POST[jobtitle]', '$_POST[department]', '$_POST[site]', '$_POST[suggestion]', '$_POST[impact]',      'NO', 'Submitted', '$a', '$_POST[location]', '$_POST[buildingNo]')";

    if ($conn->query($sql) === TRUE) 
    {
       echo "New record created successfully for $_POST[firstname]";
    }  
    else 
    {
     echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();


    exit;
    }
  ?> 

however the only way i can get write values to the database when the user clicks the submit button is to include action="SuggestionSchemeForm".

i have check your jquery code. I have found that you have not given exact selector to on submit . Put $('.SuggestionForm') OR $('#SuggestionForm') Instead of $('SuggestionForm')

   <span id="maincontent"></span>
<h2>Submit Suggestion</h2>
<div class="box generalbox center clearfix">
<div class="no-overflow">
    <div class="container" style="background-image: url('http://www.worldmarkacademy.com/OurWorld/EditorBG.png'); -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: repeat; padding-bottom: 5px;">
        <br />
        <div class="mainbody" style="background-image: url('http://www.worldmarkacademy.com/SubmitSuggestion/Notepad.png'); background-repeat: no-repeat; margin-left: auto; margin-right: auto; margin-bottom: 10px; width: 646px; height: 800px !important; min-height: 100%; overflow: hidden;">
            <script>
                 $(function () 
        {
            $('#SuggestionForm').on('submit', function (e) 
            {                             
            //e.preventDefault();
            $.ajax(
            {
                type: 'POST',
                url: 'SuggestionSchemeForm.php',
                dataType: "json",
                data: $('#SuggestionForm').serialize(),
                success: function () 
                {
                    alert('form was submitted');
                }
            });
             return false;
            });
        });
            </script>
            <div class="main-form" style="margin-top: 100px;">
                <form name="SuggestionForm" id="SuggestionForm" method="post" >

                    <div>
                        <label style="display: inline-block; margin-left: 10px; letter-spacing: 2px; color: #007A8E;">
                            <b>Name:</b>
                        </label>
                        <input id="chkBoxAnon"type="checkbox" style=" margin-left: 110px; outline: 1px solid #0078AE;"
                        name="Anonymous" value="Anonymous" onClick="CheckAnon();">
                            <label style="margin-left: 2px; color: #0078AE;">Anonymous</label>
                        </div>

                    <input type="text" id="fname" name="firstname" style="height: 34px; width: 268px; margin-left: 10px; margin-top: 5px; color: #007A8E;
                                    border: 1px solid #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;" value=""
                    <? echo $firstName?> <? echo $lastName?>">


                    <script type="text/javascript">
                        var orginalName = document.getElementById("fname").value;
                        function CheckAnon()
                        {
                        var textname = document.getElementById("fname");
                        if(document.getElementById("chkBoxAnon").checked == true)
                        {
                        textname.value = "Anonymous";
                        }
                        else
                        {
                        textname.value = orginalName;
                        }

                        }
                    </script>



                    <label style="display: block; margin-left: 10px; margin-top: 10px; letter-spacing: 2px; color: #007A8E;">
                        <b>Job Title:</b>
                    </label>
                    <input id="jobTitle" name="jobtitle" style="height: 34px; width: 268px; margin-left: 10px; margin-top: 5px; color: #007A8E; border: 1px solid #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;" type="text" />


                    <label style="display: block; margin-left: 10px; margin-top: 10px; letter-spacing: 2px; color: #007A8E;">
                        <b>Site:</b>
                    </label>
                    <select id="site" name="site" style="margin-left: 10px; margin-top: 5px; height: 34px; width: 268px; color: #007A8E; padding: 5px; font-size: 14px; line-height: 1; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;" type="text">
                        <option value="New york" style="color:#007A8E; ">New york</option>
                    </select>
                    <label style="display: block; margin-left: 10px; margin-top: 10px; letter-spacing: 2px; color: #007A8E;">
                        <b>Area To Which Improvement Relates:</b>
                    </label>
                    <select id="buildingNo" name="buildingNo" style="margin-left: 10px; margin-top: 5px; height: 34px; width: 268px; color: #007A8E; padding: 5px; font-size: 14px; line-height: 1; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;" type="text">
                        <option value="building No.4" style="color:#007A8E; ">Building No.4</option>
                        <option value="building No.6" style="color:#007A8E; ">Building No.6</option>
                    </select>
                </form>
            </div>
        </div>
    </div>
</div>

尝试

<form onsubmit="return false;" >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM