-1

I want to submit my form data when I click the save1 button without refreshing the page using ajax and jquery. I'm new at it, please help. This is my script for jquery and ajax. Here I'm storing all the data fields inside array as my form fields can be generated dynamically. When I skip the jquery and ajax part, and submit the form data using form action='savedata.php' then the data is being inserted into database. But then the page is being redirected to the savedata.php file.

<script type="text/javascript">
  $(document).ready(function()

{

            $('input[name="instituteName[]"]').each(function(){ 
              instituteName.push($(this).text());
            });
            var universityName= [];
            $('input[name="universityName[]"]').each(function(){
              universityName.push($(this).text());
            });
            var duration= [];
            $('input[name="duration[]"]').each(function(){
              duration.push($(this).text());
            });
            var division= [];
            $('input[name="division[]"]').each(function(){
              division.push($(this).text());
            });
            var obtained= [];
            $('input[name="obtained[]"]').each(function(){
              obtained.push($(this).text());
            });
            var course_type= [];
            $('input[name="course_type[]"]').each(function(){
              course_type.push($(this).text());
            });
            var major= [];
            $('input[name="major[]"]').each(function(){
              major.push($(this).text());
            });
            var roll_no= [];
            $('input[name="roll_no[]"]').each(function(){
              roll_no.push($(this).text());
            });
            var building_no= [];
            $('input[name="building_no[]"]').each(function(){
              building_no.push($(this).text());
            });
            var city= [];
            $('input[name="city[]"]').each(function(){
              city.push($(this).text());
            });
            var state= [];
            $('input[name="state[]"]').each(function(){
              state.push($(this).text());
            });
            var pin= [];
            $('input[name="pin[]"]').each(function(){
              pin.push($(this).text());
            });
            var landline= [];
            $('input[name="landline[]"]').each(function(){
              landline.push($(this).text());
            });
            var mark_sheets= [];
            $('input[name="mark_sheets[]"]').each(function(){
              mark_sheets.push($(this).text());
            });
            var degree_certificate= [];
            $('input[name="degree_certificate[]"]').each(function(){
              degree_certificate.push($(this).text());
            });
            var provisional_degree= [];
            $('input[name="provisional_degree[]"]').each(function(){
              provisional_degree.push($(this).text());
            });

            $.ajax({
              
              url:"save_secondary_details.php",
              method:"POST",
              data:{instituteName:instituteName, universityName:universityName, duration:duration, division:division, obtained:obtained, course_type:course_type, major:major, roll_no:roll_no, building_no:building_no, city:city, state:state, pin:pin, landline:landline, mark_sheets:mark_sheets, degree_certificate:degree_certificate, provisional_degree:provisional_degree},
              success:function(data)
              {
                alert(data);

              }
            });

          });

  });
  
  
</script>

I'm trying to pass all the values stored in my form inputs to ajax and then store it into database.

This is my PHP code:

<?php 
              include('../includes/dbconnection.php');
              //error_reporting(0);
              if(isset($_POST['save1']))
              {
                $email="farhan.khan@ifim.edu.in";
                $instituteName= $_POST['instituteName'];
                $universityName= $_POST['universityName'];
                $duration= $_POST['duration'];
                $division= $_POST['division'];
                $obtained= $_POST['obtained'];
                $course_type= $_POST['course_type'];
                $major= $_POST['major'];
                $roll_no= $_POST['roll_no'];
                $building_no= $_POST['building_no'];
                $city= $_POST['city'];
                $state= $_POST['state'];
                $pin= $_POST['pin'];
                $landline= $_POST['landline'];
                $mark_sheets= $_POST['mark_sheets'];
                $degree_certificate= $_POST['degree_certificate'];
                $provisional_degree= $_POST['provisional_degree'];

                foreach ($instituteName as $key => $value) {
                  $save= "INSERT INTO `candidate_secondary_education`(`email`,`inst_name`,`board`,`duration`,`percentage`,`obtained`,`course_type`,`majored_in`,`reg_no`,`street`,`city`,`state`,`pin`,`contact`,`mark_sheet`,`degree`,`provisional_degree`) VALUES ('$email','$value','$universityName[$key]','$duration[$key]','$division[$key]','$obtained[$key]','$course_type[$key]','$major[$key]','$roll_no[$key]','$building_no[$key]','$city[$key]','$state[$key]','$pin[$key]','$landline[$key]','$mark_sheets[$key]','$degree_certificate[$key]','$provisional_degree[$key]')";

                  $query = mysqli_query($con, $save);
                  if(!$query)
                  {
                    echo mysqli_error($con);
                  }
                  else
                  {

                    echo '<script type="text/javascript">'; 
                    echo 'alert("Saved.");'; 
                    
                    echo '</script>';
                  }
                }
              }
            ?>

But the data is not being inserted into database.

This is my HTML file:

<div class="row">


                    <div class="col-md-12 col-sm-12 ">
                    <div class="x_panel tile " > 
                    <div class="x_title">
                      <h2>Secondary Education Details</h2>
                    <ul class="nav navbar-right panel_toolbox">
                      <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>    </li>
                      </li>
                    </ul>
                      <div class="clearfix"></div>
                      </div>
                        <div class="x_content">
                        
                        <form class="form-horizontal form-label-left" method="post" id="secondary_education_details" action="save_secondary_details.php">

                        <div class="form-group row">
                        
                          <label class="col-form-label col-md-3 col-sm-3 label-align" for="institute-name">Name of the Institute/School/College: <span class="required">*</span>
                          </label>
                          <div class="col-md-6 col-sm-6 ">
                          <input type="text" name="instituteName[]" required="required" class="form-control  ">
                          </div>  

                        </div>


                        <div class="form-group row">
                          <label class="col-form-label col-md-3 col-sm-3 label-align" for="university-name">Board/University: <span class="required">*</span>
                          </label>
                          <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="universityName[]" required="required" class="form-control ">
                          </div>
                        </div>


                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="duration">Duration of Study (specify month & year): <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="duration[]" required="required" class="form-control ">
                        </div>
                      </div>

                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="division">Division/Class/% : <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="division[]" required="required" class="form-control  ">
                        </div>  
                      </div>

                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="degree-obtained">Degree Obtained : <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                            <p style="
                            margin-top:8px;">
                                Yes:
                                <input type="radio" class="flat" name="obtained[0]"  value="yes" required="required" /> 
                                No:
                                <input type="radio" class="flat" name="obtained[0]"  value="no" />
                            </p>
                        </div>  
                      </div>

                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="course-type">Course Type: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                            <p style="
                            margin-top:8px;">
                                Regular:
                                <input type="radio" class="flat" name="course_type[0]"  value="regular" required="required" /> 
                                Distance:
                                <input type="radio" class="flat" name="course_type[0]"  value="distance" />
                            </p>
                        </div>  
                      </div>

                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="major">Majored in:<span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="major[]" required="required" class="form-control  ">
                        </div>  
                      </div>

                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="roll-no">Student ID/Enrolment/Registration/Roll No: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text"  name="roll_no[]" required="required" class="form-control  ">
                        </div>  
                      </div>
                      <br><h4><center>Address of Institute/School/College</center></h4><br>
                      <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="building-no">Building No & Street: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <textarea class="form-control"  name="building_no[]" required="required" ></textarea>
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="city">City: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text" class="form-control"  name="city[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="state">State: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text" class="form-control"  name="state[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="pin">PIN: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text" class="form-control"  name="pin[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="landline">Landline: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="text" class="form-control"  name="landline[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="mark-sheets">Mark Sheets: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="file"  name="mark_sheets[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="degree-certificate">Degree Certificate: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="file"  name="degree_certificate[]" required="required" >
                        </div>
                        </div>
                        <div class="form-group row" >
                        <label class="col-form-label col-md-3 col-sm-3 label-align" for="provisional-degree">Provisional Degree certificate: <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 ">
                          <input type="file"  name="provisional_degree[]" required="required" >
                        </div>
                        </div>
                      <div id="001">
                        
                      </div>
                      <div class="row">
                      <span id="result"></span>
                      </div>
                      <div class="row" style="margin-top:40px;">
                        <div class="col-md-6 offset-md-9">
                          <button type="button" name="add1" value="Add more" id="add1" class="btn btn-success btn-lg" style=" padding: 12px;
                                width: 154px;border-radius: 10px;
                                ">Add more</button>
                          <button type="submit" name="save1" id="save1" value="Save1"  class="btn btn-info btn-lg" style=" padding: 12px;
                                width: 154px;border-radius: 10px;background-color: #3f51b5;
                                ">Save</button>
                        </div>
                      </div>
                      
                        
                          
                        
                      

                      </form>
                      
                    
                    </div>
                  </div>
                </div>
  • Welcome to [StackOverflow](https://stackoverflow.com)! We hope you like it here. Please take the Tour: stackoverflow.com/tour and provide a Minimal, Reproducible Example: stackoverflow.com/help/minimal-reproducible-example. What is the difference between `savedata.php` and `save_secondary_details.php`? – PeterKA Aug 16 '20 at 11:24
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 16 '20 at 12:23
  • actually it is save_secondary_details.php only, there's no file like savedata.php. – Farhan Khan Aug 17 '20 at 17:05

2 Answers2

0

change button type to "button":

<button type="button" name="save1" id="save1" value="Save1"  class="btn btn-info btn-lg" style=" padding: 12px;
                                width: 154px;border-radius: 10px;background-color: #3f51b5;
                                ">Save</button>

or prevent default:

document.getElementById("save1").addEventListener("click", function(e){
  e.preventDefault()
});
Ehsan
  • 766
  • 10
  • 17
0

A simple AJAX call should do it!

//another way to write $(document).ready(function() {
$(function() {
    $('form').on('submit', function(event) {
        //stop default form submission
        event.preventDefault();
        //submit form via AJAX
        $.post('savedata.php', $(this).serialize())
        //show response when done
        .done(function(data) {
            console.log( data );
         });
    });
});

Reference

DEMO

I am now including a demo with 3 forms - of course, you can have as many as you need - but only the first one has an event handler. And since we have event.preventDefault() there will be no redirection upon submission. However, the other two forms will attempt to redirect since they do not have an event handler with event.preventDefault().

$(function() {
    $('#form1').on('submit', function(event) {
        event.preventDefault();
        const data=$(this).serialize();
        console.log('READY TO SUBMIT #form1 DATA VIA AJAX');
        console.log( data );
        //AJAX CALL
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" placeholder="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" placeholder="Doe"><br><br>
  <label for="gender">Gender:</label><br>
  <input type="radio" id="male" name="gender" value="male">
  <label for="male">Male</label><br>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label><br><br>
  <input type="submit" value="Submit">
</form>
<hr>
<form id="form2">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" placeholder="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" placeholder="Doe"><br><br>
  <label for="gender">Gender:</label><br>
  <input type="radio" id="male" name="gender" value="male">
  <label for="male">Male</label><br>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label><br><br>
  <input type="submit" value="Submit">
</form>
<hr>
<form id="form3">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" placeholder="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" placeholder="Doe"><br><br>
  <label for="gender">Gender:</label><br>
  <input type="radio" id="male" name="gender" value="male">
  <label for="male">Male</label><br>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label><br><br>
  <input type="submit" value="Submit">
</form>
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • I have tried it by keeping the action="" property empty, in that case the page is reloading after I click submit button and no data is inserted in database. When I keep the action="save_secondary_details.php" property as this, the form gets redirected to php page and data is inserted into database. But I don't want it to redirect to another page. – Farhan Khan Aug 17 '20 at 16:07
  • (1) Confirm that you're using the correct selector for the form. (2) How many forms do you have on the page? (3) Check for errors on the console in your browser developer tool tabs. – PeterKA Aug 17 '20 at 18:05
  • (1) I'm using form id as selector which is #secondary_education_details in place of 'form' (as in your answer). (2) I have 5 forms on the page, all with different ids and different submit buttons. – Farhan Khan Aug 17 '20 at 19:02