1

I am trying to create admin panel. I have created 2 forms on same page and I am handling them using Ajax and PHP.

I have written the code but the data is not being saved in database.

Data_entry.php

This is the front-end code file where I have created the tabs and its content.

<ul class="nav nav-tabs">
            <li class="active"><a data-toggle="tab" href="#course">Course Entry</a></li>
            <li><a data-toggle="tab" href="#exam">Exam Entry</a></li>
            <li><a data-toggle="tab" href="#topic">Topic/Section Entry</a></li>
          </ul>
          <br>
          <div class="tab-content">
            <!-- Course Entry -->
            <div id="course" class="tab-pane fade in active tab_wrapper">
              <h3>Course Entry:</h3><hr>
              <div id="message_course"></div>
              <div id="message_course_success"></div>
              <div class="form_entry">
                <form>
                 <div class="form-group">
                   <label for="course_name">Course Name:</label>
                   <input type="text" class="form-control" id="course_name">
                 </div>
                 <button type="submit" name="course_submit" id="course_submit" class="btn btn-primary">Submit</button>
                </form>
              </div>

            </div>
            <!-- Exam Entry -->
            <div id="exam" class="tab-pane fade in tab_wrapper">
              <h3>Exam Entry</h3><hr>
              <div id="message_exam"></div>
              <div id="message_exam_success"></div>
              <div class="form_entry">
                <form>
                 <div class="form-group">
                   <label for="course_name">Exam Name:</label>
                   <input type="text" class="form-control" id="exam_name">
                 </div>
                 <div class="form-group">
                   <label for="exam_course_name">Course Name:</label>
                   <input type="text" class="form-control" id="exam_course_name">
                 </div>
                 <button type="submit" name="exam_submit"  id="exam_submit" class="btn btn-primary">Submit</button>
                </form>
              </div>

            </div>
            <!-- Topic/Section Entry -->
            <div id="topic" class="tab-pane fade tab_wrapper">
              <h3>Topic Entry</h3>
              <p>Some content in menu 2.</p>
            </div>
          </div>

Data_entry.js

Here I have written the javascript/Ajax part to handle the form data.

    $(document).ready(function(){

  $("#course_submit").click(function(){

    var cname = $("#course_name").val();

    $.ajax({
      type: "POST",
      url: "data_entry_backend.php",
      data: {coursename: cname, action: "course_submit"},
      success: function(result){
        if(result == 'true'){
          $("#message_course_success").html("Successfully entered the data.");
          $("#message_course").hide();
          $("#message_course_success").fadeIn(700);
        }else{
          $("#message_course").html(result);
          $("#message_course_success").hide();
          $("#message_course").fadeIn(700);
        }
      }
    });

    return false;
  });

  $("#exam_submit").click(function(){

    var ename = $("#exam_name").val();
    var ecname = $("#exam_course_name").val();

    $.ajax({
      type: "POST",
      url: "data_entry_backend.php",
      data: {examname: ename, examcoursename: ecname, action: "exam_submit"},
      success: function(result){
        if(result == 'true'){
          $("#message_exam_success").html("Successfully entered the data.");
          $("#message_exam").hide();
          $("#message_exam_success").fadeIn(700);
        }else{
          $("#message_exam").html(result);
          $("#message_exam_success").hide();
          $("#message_exam").fadeIn(700);
        }
      }
    });

    return false;
  });

});

data_entry_backend.php

This is where I have written back end code to store data in database

    <?php

include 'core/init.php';
$con = $GLOBALS['con'];       //$GLOBALS NOT $GLOBAL

$errors = array();

if(isset($_POST) === true && empty($_POST) === false){

  if(isset($_POST['action']) && $_POST['action'] === "course_submit"){

    $coursename = strtolower(sanitize($_POST['coursename']));

    if(course_exists($coursename) === true){
      echo "Course already exists!";
    }
    if(empty($coursename) === false){
      echo "Please enter a value!";
    }

      $count_err = count($errors);

      if(!empty($errors)){                  // if there are errors then return them one by one to login.js and print them
          for($i=0;$i<$count_err;$i++){     // else set the session by crosschecking username and password with database
            echo $errors[$i].'<br>';
          }
      }
      else{

        mysqli_query($con,"INSERT INTO `courses` (`course_name`) VALUES('$coursename')");
        $query_run = mysqli_query($con,"SELECT `course_id` FROM `courses` WHERE `course_name` = '$coursename'");
        $query_result = mysqli_num_rows($query_run);

        if($query_result == 1){
          echo 'true';
        }else{
          echo 'Could not enter the data';
        }

      }

  }

  else if(isset($_POST['action']) && $_POST['action'] === "exam_submit"){

      $examname = strtolower(sanitize($_POST['examname']));
      $examcoursename = strtolower(sanitize($_POST['examcoursename']));

      if(exam_exists($examname) === true){
        $errors[] = "Course already exists!";
      }

        $count_err = count($errors);

        if(!empty($errors)){                  // if there are errors then return them one by one to login.js and print them
            for($i=0;$i<$count_err;$i++){     // else set the session by crosschecking username and password with database
              echo $errors[$i].'<br>';
            }
        }
        else{

          $result = mysqli_fetch_assoc(mysqli_query($con,"SELECT `course_id` FROM `courses` WHERE `course_name` = '$examcoursename'"));
          $course_id =$result['course_id']

          mysqli_query($con,"INSERT INTO `exams` (`exam_name`,`course_id`) VALUES('$coursename','$course_id')");
          $query_run = mysqli_query($con,"SELECT `exam_id` FROM `exams` WHERE `exam_name` = '$examname'");
          $query_result = mysqli_num_rows($query_run);

          if($query_result == 1){
            echo 'true';
          }else{
            echo 'Could not enter the data';
          }

        }
    }

}

?>
  • 1
    Any errors? Does the PHP return anything? – jonmrich Mar 14 '17 at 19:09
  • 3
    SO WHAT exactly is the problem – RiggsFolly Mar 14 '17 at 19:12
  • He already told the problem "I have written the code but the data is not being saved in database." – Black Mar 14 '17 at 19:18
  • I would use multiple php files instead of only `data_entry_backend.php`. Rather use `exam_form.php` and `course_form.php` – Black Mar 14 '17 at 19:20
  • Have you checked your error logs? You're making an assumption the query is working. Add error reporting to the top of your file(s) right after your opening ` – Jay Blanchard Mar 14 '17 at 19:27
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Mar 14 '17 at 19:28
  • jonmrich No Sir, not even one error has popped up.If I use only code for "course" part and not the other one, then the code is working fine but it is not working if I use both of them together (data_entry_backend.php) – Vishwas Vyas Mar 14 '17 at 19:29

1 Answers1

1

Try it like this:

  1. Remove the <form> Wrap, you don't need it, since you are sending via jquery and ajax.
  2. Change Button Type from submit to button.
  3. Make sure to include your scripts at the bottom before the closing </body> tag.

Now the server will finally receive the ajax request and can handle it. Now you have to check If your data_entry_backend.php is good to go.

Data_entry.php

<ul class="nav nav-tabs">
            <li class="active"><a data-toggle="tab" href="#course">Course Entry</a></li>
            <li><a data-toggle="tab" href="#exam">Exam Entry</a></li>
            <li><a data-toggle="tab" href="#topic">Topic/Section Entry</a></li>
          </ul>
          <br>
          <div class="tab-content">
            <!-- Course Entry -->
            <div id="course" class="tab-pane fade in active tab_wrapper">
              <h3>Course Entry:</h3><hr>
              <div id="message_course"></div>
              <div id="message_course_success"></div>
              <div class="form_entry">

                 <div class="form-group">
                   <label for="course_name">Course Name:</label>
                   <input type="text" class="form-control" id="course_name">
                 </div>
                 <button type="button" name="course_submit" id="course_submit" class="btn btn-primary">Submit</button>

              </div>

            </div>
            <!-- Exam Entry -->
            <div id="exam" class="tab-pane fade in tab_wrapper">
              <h3>Exam Entry</h3><hr>
              <div id="message_exam"></div>
              <div id="message_exam_success"></div>
              <div class="form_entry">

                 <div class="form-group">
                   <label for="course_name">Exam Name:</label>
                   <input type="text" class="form-control" id="exam_name">
                 </div>
                 <div class="form-group">
                   <label for="exam_course_name">Course Name:</label>
                   <input type="text" class="form-control" id="exam_course_name">
                 </div>
                 <button type="button" name="exam_submit"  id="exam_submit" class="btn btn-primary">Submit</button>

              </div>

            </div>
            <!-- Topic/Section Entry -->
            <div id="topic" class="tab-pane fade tab_wrapper">
              <h3>Topic Entry</h3>
              <p>Some content in menu 2.</p>
            </div>
          </div>

<script src="jquery-3.1.1.min.js"></script>
<script src="Data_entry.js"></script>

data_entry_backend.php

You are also missing a semicolon on line 63

$course_id = $result['course_id']

Black
  • 18,150
  • 39
  • 158
  • 271
  • It's still not working .... The data is going to data_entry_backend.php but the query is not passing. – Vishwas Vyas Mar 14 '17 at 19:57
  • But now we finally have the data send to the server. Can you check if the data are ariving successfully? What output do you get if you echo action e.g. `echo $_POST['action'];` Or try to output your post like here for debugging: http://stackoverflow.com/a/7093446/4684797 – Black Mar 14 '17 at 20:12
  • data is arriving successfully... if you `echo $coursename` in data_entry_backed.php then it successfully echos te coursename value – Vishwas Vyas Mar 14 '17 at 20:15
  • And if you use `echo $_POST['action']` of any `if` the it outputs course_submit and exam_submit successfully. – Vishwas Vyas Mar 14 '17 at 20:18
  • You are missing a semicolon at `$course_id =$result['course_id']` in the server script. It should be `$course_id = $result['course_id'];` – Black Mar 14 '17 at 20:20
  • And if I remove the `else` part from `data_entry_backend.php` then it saves the data in database of the part which is not removed For example, if I remove the `else` part then it saves the data for `if` part – Vishwas Vyas Mar 14 '17 at 20:21
  • Probably because of the missing semicolon in the else part. Look my comment above. – Black Mar 14 '17 at 20:22
  • 1
    Alright Thnak you very much for this Black ...I thik that was the error ... It worked. – Vishwas Vyas Mar 14 '17 at 20:27