0

I want to send the values in the HTML form to a php script, which should be able to read those values.

HTML:

 <form id="details" method="POST" onsubmit="return submit(n,i,p,e,img)">

        Full name: <strong name="name_1"></strong><br><br>
        ID No:<strong name="org_number_1"></strong><br><br>
        Mobile No:<strong name="ph_number_1"></strong><br><br>
        
        E-mail: <strong name="email_1"></strong><br><br>
        ID Card: <img src="" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>

        <button id="go" type="submit">It's correct</button>
        
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="preview_back_end.js" async></script>

Javascript:

function submit(n,i,p,e,img){

    console.log("Going into submit()")

    $.ajax({
        type : "POST",  //type of method
        url  : "database_registration.php",  //your page
        data : { name_1 : n, email_1 : e, image : img, org_number_1: i, ph_number_1: p },// passing the values
        success: function(){  
                                //do what you want here...
                                alert(data);
                }
    });

    return false;
}


var arr=document.cookie.split(';')
for(var i=0; i<arr.length; i++){

    var c=arr[i].split('=');
    if (c[0].trim()=='name'){
        
        document.getElementsByName("name_1")[0].innerHTML=decodeURIComponent(c[1]);
        var nme=decodeURIComponent(c[1]);
    }
    else if(c[0].trim()=='ID No'){
        
        document.getElementsByName("org_number_1")[0].innerHTML=decodeURIComponent(c[1]);
        var id=decodeURIComponent(c[1]);
    }
    else if(c[0].trim()=='Mobile No'){
        
        document.getElementsByName("ph_number_1")[0].innerHTML=decodeURIComponent(c[1]);
        var phone=decodeURIComponent(c[1]);
    }
    else if(c[0].trim()=='Email'){
        
        document.getElementsByName("email_1")[0].innerHTML=decodeURIComponent(c[1]);
        var email=decodeURIComponent(c[1]);
    }
}

const image = localStorage.getItem("Image");
document.getElementsByName("image")[0].src=image;
var img=image
submit(nme,id,phone,email,img);

php:

 <?php

// Server name is localhost 
$servername = "localhost"; 
  
// In my case, user name will be root 
$username = "root"; 
  
// Password is empty 
$password = ""; 

//current date
$date = date("Y-m-d");

// get values

$name=$_POST['name_1'];
$org_number=$_POST['org_number_1'];
$ph_number=$_POST['ph_number_1'];
$email=$_POST['email_1'];
$image=$_POST['image'];


echo $name ."<BR>";
echo $org_number ."<BR>";
echo $ph_number ."<BR>";
echo $email ."<BR>";
echo $image ."<BR>";

 
// Creating a connection 
$conn = new mysqli($servername,  
            $username, $password, "Employee_information"); 
  
// Check connection 
if ($conn->connect_error) { 
    die("Connection failure: " 
        . $conn->connect_error); 
}  
  
// Creating a table Employees 
$sql="CREATE TABLE IF NOT EXISTS Employees(Sl_no int AUTO_INCREMENT PRIMARY KEY, Full_name varchar(30) NOT NULL, 
      ID_no INT(2) NOT NULL, Contact INT(10) NOT NULL, Email varchar(30) NOT NULL, registration_date DATE, 
      ID_preview blob(10M))";
$conn -> query($sql);

// Inserting records
$stmt = $conn->prepare("INSERT INTO Employees (Full_name, ID_no, Contact, Email, 
                                    registration_date, ID_preview) 
                                    VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("siissb", $name, $org_number, $ph_number, $email, $date, $image);
$stmt->execute();

if($stmt->execute())
    echo "records inserted";
else
    echo $stmt->error;
  
// Closing connection 
$stmt->close();
$conn->close(); 
?>

When I run this, I get an error in the php script:

Warning: Undefined array key "name_1" 
Warning: Undefined array key "org_number_1" 
Warning: Undefined array key "ph_number_1"
Warning: Undefined array key "email_1"

Along with that, I get this error in my console:

POST http://127.0.0.1:5500/database_registration.php 405 (Method Not Allowed)

Why are the array keys undefined? What does the console error mean? How do I fix this?

EDIT: Tried to print the $_POST array, using:

<?php
    echo 'Post variables:<br />';
    print_r($_POST);
?>

Array is completely empty:

Post variables:
Array ( ) 
  • u can use $.ajax to post through a java script instead of form, and you can use $_get in php to get the elements values – Burham B. Soliman Jan 10 '21 at 04:04
  • you can find your answere [here](https://stackoverflow.com/a/44105591/8134014) for the $.ajax part, and about the $_get you can read more about php get and post methods [here](https://www.w3schools.com/php/php_forms.asp) – Burham B. Soliman Jan 10 '21 at 04:09
  • I tried using `$_POST['name_value']` in php, but I get an `Undefined array key "name_value" ` warning. –  Jan 10 '21 at 04:11
  • u already uses post method in your form so you have to receive the result into the php file using `$_POST['name_1']` using the input name – Burham B. Soliman Jan 10 '21 at 04:16
  • It says `Undefined array key "name_1"` –  Jan 10 '21 at 04:25
  • the onsubmit calls a javascript function before the form can be submitted to php. So try to import the javascript file in the same page as the form location and put the js code you wrote in a function, then call this function with the onsubmit – Charbelalam Jan 10 '21 at 07:23
  • u have to load jquery libs in your header using script tags `` – Burham B. Soliman Jan 10 '21 at 14:23
  • @BurhamB.Soliman Tried that too, doesn't work. –  Jan 10 '21 at 15:43

2 Answers2

0

You should return false when you submit the form. It's submitting the default form. Please try this:

<form id="details" method="POST" onsubmit="return submit(n,i,p,e,img)">
      <!-- Your code here -->
</form>




  <script>
    function submit(n,i,p,e,img){
        //Your Ajax request here
    
    
    
        return false;
    }
   </script>
Shakil Anwar
  • 141
  • 1
  • 10
0

The problem is that you don't prevent the traditional submit acction.

Generally is better to use addEventListener than then old onsubmit HTML attribute.

I modified your code so that it works:

HTML

 <form id="details" method="POST">

        Full name: <strong name="name_1">1</strong><br><br>
        ID No:<strong name="org_number_1">2</strong><br><br>
        Mobile No:<strong name="ph_number_1">3</strong><br><br>
        
        E-mail: <strong name="email_1">4</strong><br><br>
        ID Card: <img src="" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>

        <button id="go" type="submit">It's correct</button>
        
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="preview_back_end.js" async></script>

preview_back_end.js

function submit(n,i,p,e,img){

    console.log("Going into submit()")

    $.ajax({
        type : "POST",  //type of method
        url  : "database_registration.php",  //your page
        data : { name_1 : n, email_1 : e, image : img, org_number_1: i, ph_number_1: p },// passing the values
        success: function(){  
                                //do what you want here...
                                alert("ok");
                }
    });

    
}

const dForm = document.getElementById('details');          
dForm.addEventListener('submit', function(e) {
    e.preventDefault()
    submit(nme,id,phone,email,img);
});


var arr=document.cookie.split(';')
for(var i=0; i<arr.length; i++){

    var c=arr[i].split('=');
    if (c[0].trim()=='name'){
        
        document.getElementsByName("name_1")[0].innerHTML=decodeURIComponent(c[1]);
        var nme=decodeURIComponent(c[1]);
    }
    else if(c[0].trim()=='ID No'){
        
        document.getElementsByName("org_number_1")[0].innerHTML=decodeURIComponent(c[1]);
        var id=decodeURIComponent(c[1]);
    }
    else if(c[0].trim()=='Mobile No'){
        
        document.getElementsByName("ph_number_1")[0].innerHTML=decodeURIComponent(c[1]);
        var phone=decodeURIComponent(c[1]);
    }
    else if(c[0].trim()=='Email'){
        
        document.getElementsByName("email_1")[0].innerHTML=decodeURIComponent(c[1]);
        var email=decodeURIComponent(c[1]);
    }
}

const image = localStorage.getItem("Image");
document.getElementsByName("image")[0].src=image;
var img=image

Andrei O.
  • 116
  • 1
  • 1
  • 5
  • Be sure that your cookie is set correctly. For example, if you add the email assignment into `var email="test"` after the line `const image = ...` then you will see that the variable will get passed. If the value of the variables in the data object of the ajax call will be null/false/undefined then they will not be sent it is normal behavior. – Andrei O. Jan 11 '21 at 18:07
  • I made a screen recording here: https://youtu.be/IVAS6Qp-uAc maybe it helps. – Andrei O. Jan 11 '21 at 18:26