简体   繁体   中英

insert form data using ajax and php with page id and session data

i am making a school book library web project where students can select books and send request to librarian to request book to borrow. Unfortunately i am new to jquery so its hard for me to handle problems .

my code is viewbook.php

    <form method="post" action="" id="contactform">
      <div class="form-group">
        <label for="name">Name:</label>
         <input type="text" class="form-control" id="name">
      </div>
      <div class="form-group">
         <label for="email">Email Address:</label>
         <input type="email" class="form-control" id="email">
      </div>
      <button type="submit" class="btn btn-primary">Submit</button>
  </form>

<div id="code" class="result">

</div> 

javascript code is

        <script>
   $(document).ready(function () {
   $('.btn-primary').click(function (e) {
   e.preventDefault();
   var name = $('#name').val();
   var email = $('#email').val();
   $.ajax
    ({
      type: "POST",
      url: "submit.php",
      data: { "name": name, "email": email },
      success: function (data) {
        $('.result').html(data);
        //$('#contactform')[0].reset();
      }
       });
     });
  });

submit.php

      <?php
       require_once "db.php";   
       //insert into database
        if(!empty($_POST['email'])) {
        $name = htmlspecialchars(trim($_POST['name']));
        $email = htmlspecialchars(trim($_POST['email']));


if (strlen($name) < 4) {
    $errors['name'] = "*Name Is Short ! atleast 2 character*";
}
if (count($errors) === 0) {
    $insert_user = "INSERT INTO book_requests (`name`, `email`, `bookid`, `user`)VALUES (:name,:email,:bookid,:userid)";
    $result = $conn->prepare($insert_user);
    $result->bindParam(':name', $name, PDO::PARAM_STR);
    $result->bindParam(':email', $email, PDO::PARAM_STR);
    $result->bindParam(':bookid', $bookid, PDO::PARAM_STR);
    $result->bindParam(':user', $user, PDO::PARAM_STR);

    $name = htmlspecialchars(trim($_POST['name']));
    $email = htmlspecialchars(trim($_POST['email']));
    $bookid= $_GET['bookid'];
    $user = $_SESSION['login'];

    $result->execute();
    if ($result) {
      echo "done<br>" ;
    } else {
        echo "not done<br>";
    }
}
}
 }
  ?>

my problem is bookid which is stored in $bookid= $_GET['bookid'] and userid which is stored in $user = $_SESSION['login'] which are on page 'viewbook.php' how to store them into database with form data using ajax.

please help me in this

The first thing you want to do is to use session_start(); in EVERY php page (also submit.php) that you use (assuming you don't use a controller pattern / other frameworks which handle the session). By using this you should be able to access $_SESSION['login'] in your submit.php. Next thing would be to handle the $_get['bookid'] . The issue is you are trying to access the get Array which is not present / filled with any values in your current implementation. My suggestion would be to send the bookid also in the ajax submit. To do so you need to extract the parameter.

 const query = window.location.search; //assuming your url looks something like this https://example.com/viewbook.php?bookid=5 const urlParams = new URLSearchParams(query); const bookid = urlParams.get('bookid') //now build the ajax query $.ajax({ type: "POST", url: "submit.php", data: { "name": name, "email": email, "bookid": bookid }, success: function(data) { $('.result').html(data); //$('#contactform')[0].reset(); } });

I would also suggest to not simply return echo "done<br>" ; but rather rturn a status code for example header("HTTP/1.1 200 OK"); and a valid json response containing a message and potential additional information (up to you). If you have any questions feel free to add a comment.

submit.php should look like the following

<?php
require_once "db.php";
//insert into database
session_start();
if (!empty($_POST['email']))
{
    
    $name = htmlspecialchars(trim($_POST['name']));
    $email = htmlspecialchars(trim($_POST['email']));
    $bookid = htmlspecialchars(trim($_POST['bookid']));
    $user = $_SESSION['login'];
    if (strlen($name) < 4)
    {
        $errors['name'] = "*Name Is Short ! atleast 2 character*";
    }
    if (count($errors) === 0)
    {
        $insert_user = "INSERT INTO book_requests (`name`, `email`, `bookid`, `user`)VALUES (:name,:email,:bookid,:userid)";
        $result = $conn->prepare($insert_user);
        $result->bindParam(':name', $name, PDO::PARAM_STR);
        $result->bindParam(':email', $email, PDO::PARAM_STR);
        $result->bindParam(':bookid', $bookid, PDO::PARAM_STR);
        $result->bindParam(':user', $user, PDO::PARAM_STR);

        $result->execute();
        if ($result)
        {
            echo "done<br>";
        }
        else
        {
            echo "not done<br>";
        }
    }
}
?>

If you want to redirect if there is no valid session you could simply put the following code on top of submit.php and viewbook.php. Please always put the die (or exit) at the end of a header call. Also consider vulnerabilities like CSRF when implementing sessions.

session_start();
if(!isset($_session['login'])){
header("Location: https://example.com/login.php");
die();
}

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