Home > Net >  insert form data using ajax and php with page id and session data
insert form data using ajax and php with page id and session data

Time:07-12

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 >
        <label for="name">Name:</label>
         <input type="text"  id="name">
      </div>
      <div >
         <label for="email">Email Address:</label>
         <input type="email"  id="email">
      </div>
      <button type="submit" >Submit</button>
  </form>

<div id="code" >

</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

CodePudding user response:

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.

  • Related