HTML Form not submitting to database can AJAX cause this

<html>
    <head>
    
    
    <script type="text/javascript">
<!-- onchange event to change dropdown 1 and 2 -->
    function change_type()
    {
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","ajax.php?catdd="+document.getElementById("catdd").value,false);
        xmlhttp.send(null);
        //alert(xmlhttp.responseText);
        document.getElementById("stype").innerHTML=xmlhttp.responseText;
    }

</script>
    
    
    </head>
    <body>

        <form action ="" name="submit"  method="post">
            
            
            <p>Please Select The Type Of Defect</p>      
            <select id ="catdd"  name="types" onChange="change_type()">

                <option disabled="" selected="" value="">-- Please Select The Type Of Defect -- </option>

    <?php   
        $query = "SELECT * FROM category"; 
        $result = mysqli_query($link,$query);
        mysqli_error($link);
        while($row=mysqli_fetch_array($result)){


    ?>   

        <option value= "<?php echo $row["id"];?>"><?php echo $row["type"];?></option>

<?php
            
}
           
   ?>              
   
</select>
   
<div id="stype">
    
    <p>Please select the type of Defect you wish to report</p>
       
    <select>
        <option>select</option>
        
    </select>
        </div>
  
    
            
    <P>Please select the urgency of the request</P>
            
    <select name="urgency">
        
    <option disabled="" selected="" value="">-- Please select the urgency -- </option>
   
        <?php echo $options2?>
        
    </select>
    
    <p>Please enter a short description of the Defect</p>
   
    <textarea class="tbox" name = "description" style="height:100px; width:350px" value="" placeholder="Please enter Short Description">
            
    </textarea>
    
   
    <p>Please Enter The Closest Door Number</p>
            
        <input type="textbox" name="door" value =""/> 
       
        <p>Please Specify The Area </p>
            
        <select name="area">
            
        <option disabled="" selected="" value="">-- Please Select The Area -- </option>
            
            <?php echo $options3?>
            
        </select>
     
    
        <p>This Defect Was reported By</p>
            
        <select name="designation">
            
            <option disabled="" selected="" value="">-- Please Select Title -- </option>
            
                <?php echo $options4
            ?>

    </select>
            
 
        
    <p>Name And Surname Of Client Reporting The Defect</p>
        
        <input type="textbox" name="reportedby" value =""/> 
       
 
            
        <p>Contact number of Client</p>
            
            <input type="textbox" name="contactnumber" value =""/>
    
    
 <input type ="submit" name ="submit" value= "Submit Defect"/>
       
           </form>   
   
    
        
<?php
     error_reporting(E_ALL);
    $link6 = mysqli_connect("localhost" ,"root","","newdefects");
        
        if($link6 === false){
                die("ERROR: Could not connect. " . mysqli_connect_error());
        }
     
        
if(isset($_POST['types'])&&isset($_POST['stype'])&&isset($_POST['urgency'])&&isset($_POST['description'])&&isset($_POST['door'])&&isset($_POST['area'])&&isset($_POST['designation'])&&isset($_POST['reportedby'])&&isset($_POST['contactnumber'])) {
    
    $types= mysqli_real_escape_string ($link6, $_REQUEST['types']);
    $stype= mysqli_real_escape_string($link6,$_REQUEST['stype']);
    $urgency = mysqli_real_escape_string($link6,$_REQUEST['urgency']);
    $description = mysqli_real_escape_string($link6,$_REQUEST['description']);
    $door= mysqli_real_escape_string($link6,$_REQUEST['door']);
    $area= mysqli_real_escape_string($link6,$_REQUEST['area']);
    $designation = mysqli_real_escape_string($link6,$_REQUEST['designation']);
    $reportedby= mysqli_real_escape_string($link6,$_REQUEST['reportedby']);
    $contactnumber = mysqli_real_escape_string($link6,$_REQUEST['contactnumber']);
    
    
    
   
    if(!empty($type)&&!empty($stype)&&!empty($urgency)&&!empty($description)&&!empty($door)&&!empty($area)&&!empty($designation)&&!empty($reportedby)&&!empty($contactnumber)){
        
       $sql ="INSERT INTO defects (type,dtype,urgency,descr,doornum,area,reportedby,namesurname,contact) VALUES ('$types', '$stype','$urgency','$description','$door','$area','$designation','$reportedby','$contactnumber')";
     
    
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link6);
         

   if(mysqli_query($link6, $sql)){
    
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link6);
}
   }
}
        
mysqli_close($link);
    
        ?>
      
       
            </body>
    
    
</html>

just need the form info to submit to database, i believe AJAX is refreshing the page, not that clued up on AJAX

Or Maybe just something stupid , any assistance is appreciated.

To start with, you have everything in just one page. You need to separate logic from presentation. So in your form, or through jquery, call a php file to handle the insert: e.g.

<form action ="insert.php" name="submit"  method="post">

and then in insert.php:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
	// first here you should check if all required fields are not empty and if they are not then do the insert
	
	 if(!empty($type)&&!empty($stype)&&!empty($urgency)&&!empty($description)&&!empty($door)&&!empty($area)&&!empty($designation)&&!empty($reportedby)&&!empty($contactnumber)){	 
	
		$types= mysqli_real_escape_string ($link6, $_REQUEST['types']);
		$stype= mysqli_real_escape_string($link6,$_REQUEST['stype']);
		$urgency = mysqli_real_escape_string($link6,$_REQUEST['urgency']);
		$description = mysqli_real_escape_string($link6,$_REQUEST['description']);
		$door= mysqli_real_escape_string($link6,$_REQUEST['door']);
		$area= mysqli_real_escape_string($link6,$_REQUEST['area']);
		$designation = mysqli_real_escape_string($link6,$_REQUEST['designation']);
		$reportedby= mysqli_real_escape_string($link6,$_REQUEST['reportedby']);
		$contactnumber = mysqli_real_escape_string($link6,$_REQUEST['contactnumber']);
		
		$sql ="INSERT INTO defects (type,dtype,urgency,descr,doornum,area,reportedby,namesurname,contact) VALUES ('$types', '$stype','$urgency','$description','$door','$area','$designation','$reportedby','$contactnumber')";
		
		if(mysqli_query($link6, $sql)){
			echo "Records added successfully."
		} else {
			echo "Error message"
		}}
	} else{
		// Error something went wrong
	}
} else {
	// Error was not a post request
}
1 Like

Thanks, let me do that first as it seems like good practice in any case :slight_smile:

1 Like

While you’re doing that, change it to use prepared statements rather than just string substitution. It’s a straightforward bit of code to change.

1 Like

should i only seperate my CSS from the main.php or should my PHP, Css,HTML all be in seperate files and just include where needed ?

I removed my CSS and put my insert function into a seperate php file.

everything working fine but submit still not working, and it is not even checking my !empty

<?php
include('dbconnection.php');
error_reporting(E_ALL);
    $link6 = mysqli_connect("localhost" ,"root","","newdefects");
        
        if($link6 === false){
                die("ERROR: Could not connect. " . mysqli_connect_error());
        }
     
  if ($_SERVER['REQUEST_METHOD'] == 'POST'){
      
 if(!empty($type)&&!empty($stype)&&!empty($urgency)&&!empty($description)&&!empty($door)&&!empty($area)&&!empty($designation)&&!empty($reportedby)&&!empty($contactnumber)){	 
	
		$types= mysqli_real_escape_string ($link6, $_REQUEST['types']);
		$stype= mysqli_real_escape_string($link6,$_REQUEST['stype']);
		$urgency = mysqli_real_escape_string($link6,$_REQUEST['urgency']);
		$description = mysqli_real_escape_string($link6,$_REQUEST['description']);
		$door= mysqli_real_escape_string($link6,$_REQUEST['door']);
		$area= mysqli_real_escape_string($link6,$_REQUEST['area']);
		$designation = mysqli_real_escape_string($link6,$_REQUEST['designation']);
		$reportedby= mysqli_real_escape_string($link6,$_REQUEST['reportedby']);
		$contactnumber = mysqli_real_escape_string($link6,$_REQUEST['contactnumber']);
		
		$sql ="INSERT INTO defects (type,dtype,urgency,descr,doornum,area,reportedby,namesurname,contact) VALUES ('$types', '$stype','$urgency','$description','$door','$area','$designation','$reportedby','$contactnumber')";
		
		if(mysqli_query($link6, $sql)){
			echo "Records added successfully.";
		} else {
			echo "Error message";
            
        }
 }
  }
<?php error_reporting(E_ALL); ini_set('display_errors', 1); ?>
<link rel="stylesheet" type="text/css" href="display.css">
<?php
include ('dbconnection.php');


?>


<html>
    <head>
        
    <script type="text/javascript">
        //Function onchange to populate second dropdown
    function change_type()
    {
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","ajax.php?catdd="+document.getElementById("catdd").value,false);
        xmlhttp.send(null);
        document.getElementById("stype").innerHTML=xmlhttp.responseText;
    }

</script>
    
    
    </head>
    <body>

        <form action ="insert.php" name="submit"  method="POST">
    
           
            <p>Please Select The Type Of Defect</p>      
            <select id ="catdd"  name="types" onChange="change_type()">

            <option disabled="" selected="" value="">-- Please Select The Type Of Defect -- </option>

    <?php  
                
        $query = "SELECT * FROM category"; 
        $result = mysqli_query($link,$query);
        mysqli_error($link);
        while($row=mysqli_fetch_array($result)){


    ?>   

        <option value= "<?php echo $row["id"];?>"><?php echo $row["type"];?></option>

<?php
            
}
           
   ?>              
   
</select>
   
            <!--Populated by Query seperate PHP file-->
            
<div id="stype">
    
    <p>Please select the type of Defect you wish to report</p>
       
    <select>
        <option>select</option>
        
    </select>
        </div>
  
    
            
    <P>Please select the urgency of the request</P>
            
    <select name="urgency">
        
    <option disabled="" selected="" value="">-- Please select the urgency -- </option>
        
   <?php
        
        $query2 = "SELECT * FROM urgent";
        $result2= mysqli_query($link2,$query2);
        $options2="";
        while($row2 =mysqli_fetch_array($result2)){
    
        $options2=$options2. "<option> $row2[0]</option>";
}
         echo $options2;
    ?>
        
    </select>
    
    <p>Please enter a short description of the Defect</p>
   
    <textarea class="tbox" name = "description" style="height:100px; width:350px" value="" placeholder="Please enter Short Description">
            
    </textarea>
    
   
    <p>Please Enter The Closest Door Number</p>
            
        <input type="textbox" name="door" value =""/> 
       
        <p>Please Specify The Area </p>
            
        <select name="area">
            
        <option disabled="" selected="" value="">-- Please Select The Area -- </option>
            
            <?php
                    $query3="SELECT * FROM areas";
                    $result3=mysqli_query($link3, $query3);
                    $options3="";
                    while($row3 =mysqli_fetch_array($result3)){
                    $options3=$options3. "<option> $row3[0]</option>";
}
             echo $options3;
        ?>
            
        </select>
     
    
        <p>This Defect Was reported By</p>
            
        <select name="designation">
            
            <option disabled="" selected="" value="">-- Please Select Title -- </option>
            <?php
                 
                $query4 = "SELECT * FROM titletype";
                $result4=mysqli_query($link4,$query4);
                $options4="";
                while($row4 =mysqli_fetch_array($result4)){

                $options4=$options4. "<option> $row4[0]</option>";
}
                 echo $options4;
            ?>

    </select>
            
 
        
    <p>Name And Surname Of Client Reporting The Defect</p>
        
        <input type="textbox" name="reportedby" value =""/> 
       
 
            
        <p>Contact number of Client</p>
            
            <input type="textbox" name="contactnumber" value =""/>
    
    
 <input type ="submit" name ="submit" value= "Submit Defect"/>
       
        <?php include('insert.php');?>     
  
        </form>   
            </body>
    
    
    
</html>

Any help appreciated

 if(!empty($type)&&!empty($stype)&&!empty($urgency)&&!empty($description)&&!empty($door)&&!empty($area)&&!empty($designation)&&!empty($reportedby)&&!empty($contactnumber)){

Where are all these variables coming from? If this is your complete code (surround it with back-ticks, please, it’s virtually impossible to read in one block) I can’t see where you have created them prior to this line of code, and because you only do the insert if none of them are empty, then because they don’t exist that would mean it doesn’t run.

1 Like

What happens if you leave the if statement out? I mean forget the validation for now

Edit: Why do you include insert.php in your form?

Hi

those variables are from my inputs ie…

Please Specify The Area

 <select name=**"area">**

hence the variable &&!empty($area) as one example

then i do the $area= mysqli_real_escape_string($link6,$_REQUEST[ā€˜area’]); on my input

unless im very very confused.

this just as one example of my variables. hope it clears it up a bit

But they need to be extracted from the $_POST array before you use them. When variables come from a form

<select name="area">

they appear either as $_POST['area'] or $_GET['area'], depending on your submit method, not just as a variable named the same as the form field. I see you’re using $_REQUEST, which may encompass both of those submit methods, I’ve not tried it myself.

You’re testing to see that variables exist before you create them. So they don’t exist at that point, and the code inside your if() clause doesn’t execute as a result.

i took it out and now it gives me undifined indexes as if i did not declare my variables
//without the IF

$types= mysqli_real_escape_string ($link6, $_REQUEST['types']);
		$stype= mysqli_real_escape_string($link6,$_REQUEST['stype']);
		$urgency = mysqli_real_escape_string($link6,$_REQUEST['urgency']);
		$description = mysqli_real_escape_string($link6,$_REQUEST['description']);
		$door= mysqli_real_escape_string($link6,$_REQUEST['door']);
		$area= mysqli_real_escape_string($link6,$_REQUEST['area']);
		$designation = mysqli_real_escape_string($link6,$_REQUEST['designation']);
		$reportedby= mysqli_real_escape_string($link6,$_REQUEST['reportedby']);
		$contactnumber = mysqli_real_escape_string($link6,$_REQUEST['contactnumber']);

With the IF it does not give undefined.

the Include was a silly beginners error

That’s only because it’s actually executing the code now.

What happens if you var_dump($_REQUEST) - do you see the correct variables in there?

Do you get an error message for every field, or just some of them? Is your Ajax code just the short function to populate the ā€œstypeā€ div, or is there more of it somewhere?

You should always check for form variables existing before you try to use them. So you could use empty() as you were, or exist(), but use it on the correct variables.

\This is the PHP function the script calls it works fine for populating my dropdowns

i will try var_dump to see, but no i dont get any other errors

thanks for your assistance greatly appreciated

<?php
 error_reporting(E_ALL);

$link5=mysqli_connect("localhost", "root", "", "defecttypes");
if($link5 === false){
                die("ERROR: Could not connect. " . mysqli_connect_error());
}
$value= $_GET["catdd"];
 



 $query5 = "SELECT * FROM defects where defect_id=$value";
$result5=mysqli_query($link5,$query5);
?>
<p>Please select Specific details of Defect to report</p>
<select>
     
<?php
    
while($row5 =mysqli_fetch_array($result5)){
     
?>
   
<option> 
<?php 
    echo $row5['type'];
}
    ?>  
    </option>

    
 </select>

Just did Vardump Request and it shows my variables correctly

Got IT working

thanks all for the help and guidance…

feeling relieved :slight_smile:

it seems like it is also important to Include your PHP page onto my HTML page :):slight_smile:

You shouldn’t need to include the code that processes the form submission, as noted above by @donboe.