-1

I am having issues with my form, it is not posting to MySQL. I am not sure why its not grabbing the data.

Below is my form data with ajax statements:

<div class="container">

    <h2>Add New Asset</h2>
    <form method="post" class='addasset'>
    <table>
        <tr>
                <th>Internal ID:</th>
                <td><input type="text" name="internalid" id="internalid"></td>
        </tr>

    </table>
   
     <input type="button" value="Add" id="Add">
     <input type="reset" value="Cancel" onclick="window.location.href='assetlist.php';">
    </form>
</div>

<script type="text/javascript">



    $(document).ready(function(){

        $('#Add').click(function(event){

        event.preventDefault();
        
        var data = $('.addasset').serialize();
        
        
        var internalid = $("[name='internalid']").val();
                   

if (internalid === "") {$("[name='internalid']").css({"background":"red", "color":"white"});}
  
 else {
    
            $(this).attr("disabled", true);
                       
         $.ajax ({

            data:data,

            url:'processor-assetnew.php',

            type:'post'

        });
        
      function redirect(){

        window.location.href='assetlist.php';

      }
      setTimeout(redirect,500);
 } 

    });
    });
</script>

My processor file is as follows:

<?php

require 'wconnectionfile.php';

$internalID = $_POST['internalid'];

if (!empty($internalID)) {


$sql = "INSERT INTO equipmentlist (InternalID)
VALUES ('$internalID'')";   

}

if ($conn->query($sql) === TRUE) {


}


} else {

    echo "Error: " . $sql . "<br>" . $conn->error;

}

$conn->close();

?>

I have a bunch of variables but I shortened it just for testing. All my variables below, but even with just the one form variable and one post variable, it doesn't populate inside MySQL.

The below is just original / informational purposes:


$ID = mysql_insert_id();
$internalID = $_POST['internalid'];
$reg_date = $_POST['reg_date'];
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$vin = $_POST['vin'];
$type = $_POST['type'];
$location = $_POST['location']
$buassigned = $_POST['buassigned'];
$camera = $_POST['camera'];
$remarks = $_POST['remarks'];


// Lookup Next ID

 $sql = "SELECT * FROM equipmentlist ORDER BY ID DESC LIMIT 1"; 

      $result = $conn->query($sql);
        
          if ($result->num_rows > 0) {           
            
            while($row = $result->fetch_assoc()) { $ID = $row['ID'] + '1' ;   }}
            


if (!empty($internalID)) {


$sql = "INSERT INTO equipmentlist (Year, Make, Model, VIN, Type, Location, BUAssigned, Camera, Remarks, InternalID. Reg_Date, ID)

            VALUES ('$year','$make','$model','$vin','$type','$location','$buassigned','$camera','$remarks','$internalID','$reg_date' '$ID')";   

Miqayel Srapionyan
  • 587
  • 2
  • 5
  • 15
  • 3
    Double single quote? '$internalID'' – sibert Feb 03 '21 at 07:14
  • 2
    Enable [PHP error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) and [MySQL error reporting](https://stackoverflow.com/questions/12227626/how-do-i-display-a-mysql-error-in-php-for-a-long-query-that-depends-on-the-user). Please make sure you have no errors first. If you have any: post the error message. – Definitely not Rafal Feb 03 '21 at 07:15
  • 1
    `mysql_insert_id()` should be `$conn->insert_id` I expect. so, your code is vulnerable to SQL injection attacks... please urgently switch to using prepared statements and parameters in order to protect your database. https://phpdelusions.net/mysqli – ADyson Feb 03 '21 at 08:09

2 Answers2

0

In the snippet below, instead of sending the data and redirecting, I do a console.log for both. The result is

enter image description here

    $(document).ready(function(){

        $('#Add').click(function(event){

        event.preventDefault();
        
        var data = $('.addasset').serialize();
        
        
        var internalid = $("[name='internalid']").val();
                   

if (internalid === "") {$("[name='internalid']").css({"background":"red", "color":"white"});}
  
 else {
    
            $(this).attr("disabled", true);
                       
         /*$.ajax ({

            data:data,

            url:'processor-assetnew.php',

            type:'post'

        });*/
        console.log(data);
        
      function redirect(){

        //window.location.href='assetlist.php';
        console.log("redirecting...");

      }
      setTimeout(redirect,500);
 } 

    });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container">

    <h2>Add New Asset</h2>
    <form method="post" class='addasset'>
    <table>
        <tr>
                <th>Internal ID:</th>
                <td><input type="text" name="internalid" id="internalid"></td>
        </tr>

    </table>
   
     <input type="button" value="Add" id="Add">
     <input type="reset" value="Cancel" onclick="window.location.href='assetlist.php';">
    </form>
</div>

So, your data is grabbed and sent to the server. This means that your issue is on the server-side. You will need to make sure that you are posting at the right place and if so, try running

echo var_dump($_POST);

in your dev env to see what the issue is.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • I will try this out and let you know. I also did not notice my double single quote. I am positive the mysql table / location are correct. – Chaolis Feb 04 '21 at 16:25
  • @Chaolis the double-quotes inside your query are making it syntactically incorrect. You need to try running a query directly against your db, without your app until it works. Then try running the exact same query through your app. If it works, then you exclude the possibilities of connection issues and can gradually convert your hard-coded test query into something more tangible. – Lajos Arpad Feb 05 '21 at 14:57
-1

I change you code to this let me know if you have any question.

EDIT : Okay thank for your concern i think this is the easy way or better way to pass data from ajax to mysql php because if you need to add another data like input textbox no need to declare it or get via ID the new FormData($(this)[0]) will do it for you. thanks

<div class="container">

<h2>Add New Asset</h2>
<form method="post" class='addasset'>
<table>
    <tr>
            <th>Internal ID:</th>
            <td><input type="text" name="internalid" id="internalid"></td>
    </tr>

</table>

 <input type="submit" value="Add" id="Add">
 <input type="reset" value="Cancel" onclick="window.location.href='assetlist.php';">
</form>
$(document).ready(function(){
    $("#addasset").submit(function (event) { 
       event.preventDefault();
       var formData = new FormData($(this)[0]);
       var internalid = $("[name='internalid']").val();
                   
       if (internalid === "") {
       $("[name='internalid']").css({"background":"red", "color":"white"});
       }
       else {
       $(this).attr("disabled", true);
          $.ajax({
                url: 'processor-assetnew.php',
                type: 'POST',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) 
                {
                 window.location.href='assetlist.php';
                }
 });
    });
  • 1
    a) Please format your code properly (https://stackoverflow.com/help/formatting), and b) please explain your answer up-front, for the benefit of everyone. Don't wait for queries... just explain what you've changed and, importantly, why you've changed it in order to solve the problem. Then no-one will misunderstand anything or fail to ask. – ADyson Feb 03 '21 at 11:23
  • 1
    Also there should be no reason to change this to FormData anyway...serialize() should work fine for this simple form. You really only need FormData with a jQuery $ajax call when you're uploading files. This is why you should _explain your answer_ - justify why the code you're replacing wouldn't work and why yours solves the problem. I actually think in this case that there isn't any valid justification, but perhaps you can clarify it? – ADyson Feb 03 '21 at 11:26
  • 1
    `because if you need to add another data like input textbox no need to declare it or get via ID`...sure, but the OP is using jquery's serialize() function, which does exactly the same job. They aren't getting anything by ID. So your code makes no useful improvement. Not does it solve the OP's problem. (It's true that they are writing `$("[name='internalid']").val();`...but that isn't actually used in the AJAX call, it's for a different purpose.) – ADyson Feb 03 '21 at 14:05