0

So I tried a lot to fix my web problem. I hope to find here a solution. The problem is that the ajax success function work and in the network section it has a status code of 200 with the data input but it has no response and the data is not inserted into the database.

html form:

        <form action="./includes/systemcheck.inc.php" id="reg1" method="post">
            <input type="text" id="reg_fname" name="fullName" class="mr_fni">
            <input type="number" id="reg_uid" name="userID" class="mr_idi">
            <input type="number" id="reg_pnumber" name="phoneN" class="mr_pni">
            <input type="submit" name="register1" id="reg1_sub_butt" value="next" 
            class="cim_gSubmmit">
        </form>
        <p id="reg1_result"></p>

php:

   if(isset($_POST['register1'])){

   $fullName = $_POST['fullName'];
   $userID = $_POST['userID'];
   $phoneN = $_POST['phoneN'];
   if(!empty($fullName) || !empty($userID) || !empty($phoneN)){
    $sql = "INSERT INTO `hotelsystem` (`fullName`, `phoneNumber`, `id`) 
            VALUES ('$fullName', '$phoneN', '$userID')";
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
   }
   else{
    echo "fill all fields please";
   }

ajax:

window.onload = function(){
 
    $('#reg1_sub_butt').click(function (e) {
        var formData = {
            'fullName' : $('#reg_fname').val(),
            'userID': $('#reg_uid').val(),
            'phoneN': $('#reg_pnumber').val()
        }
        
        if(formData.fullName == '' || formData.userID == '' || formData.phoneN == ''){
            $('#reg1_result').html('Please fill all fields');
        } else {
            //if no issues attempt to push code
            submitData(formData);
            $('#reg1_result').show();
        }
        
        return false;
        
    });
}

function submitData(formData){
    console.log(formData);
    $.ajax({
        type: 'POST',
        url: './includes/systemcheck.inc.php',
        data: formData,
        contentType: 'charset=UTF-8',
        async: false,
        success: function(response) {
            $('#reg1_result').html(response + "work");
        },
        error: function() {
            $('#reg1_result').html('There was an error');
        }
    });
}
Suresh Mangs
  • 705
  • 8
  • 19
Lidor
  • 21
  • 4
  • Is `$_POST['register1']` set? (You should see it in `console.log(formData);` if it is). – Nigel Ren May 09 '21 at 08:37
  • `formData` doesn't contain a field called `register1` so the code doesn't enter the first `if`, and there's no `else` on that one to provide any alternative output. – ADyson May 09 '21 at 08:39
  • P.s. `async: false` is deprecated, it degrades the user experience and there is no reason to use it in this code or anywhere else. In some browsers you'll get a warning about it in the console – ADyson May 09 '21 at 08:41
  • @ADyson well i didn't understand what you mean that formdata doesn't contain a field called register1 can you give an example how it should look like please – Lidor May 09 '21 at 08:50
  • What's not to understand? Take a look at your code line `var formData = {...` do you see a field named "register1" in that object? – ADyson May 09 '21 at 08:51
  • And, do you understand what this line `if(isset($_POST['register1']))` in your PHP does? – ADyson May 09 '21 at 08:52
  • @ADyson yes its mean that when you press the button register1 it run the code inside – Lidor May 09 '21 at 08:54
  • well i dont see no register1 in the var formdata so i need to add like register1, like this? – Lidor May 09 '21 at 08:55
  • 1
    If you just do `submitData($('#reg1').serialize())`, it will pass all elements in that form. Then you also won't need to update your JS if you add some input at some point. – M. Eriksson May 09 '21 at 08:57
  • 1
    You have a serious security issue though. You're _wide open_ for [SQL injection attacks](https://owasp.org/www-community/attacks/SQL_Injection)! Learn how to use [prepared statements with bound parameters](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) instead of injecting user data directly into your queries like that. Never ever trust data that isn't explicitly hard coded into your code. – M. Eriksson May 09 '21 at 09:00
  • @MagnusEriksson ty for your answers but first i want it to work – Lidor May 09 '21 at 09:04
  • 1
    If you change your code to what I suggested in my first comment, it should work. – M. Eriksson May 09 '21 at 09:04
  • @MagnusEriksson well its doing the same job with the same problem – Lidor May 09 '21 at 09:10
  • 1
    `yes its mean that when you press the button register1 it run the code inside`...not exactly. It means that when the $_POST data contains a value in the "register1" field it will run that code. PHP only sees the POST values in the HTTP request, it doesn't know anything about buttons or forms or browsers or anything like that. So if you want it to see that variable, you have to send it. It isn't sent automatically in the AJAX request. – ADyson May 09 '21 at 09:12
  • 1
    Actually, I just tested it and `.serialize()` doesn't seem to include submit-buttons. – M. Eriksson May 09 '21 at 09:20

1 Answers1

2

The formData variable which you send via AJAX doesn't contain a field called register1 so the code doesn't enter the first if block (if(isset($_POST['register1']))), and there's no else on that one to provide any alternative output.

You can send that field by simply adding it to the formData object. Its content doesn't matter, it simply needs to exist. For example:

var formData = {
    'fullName' : $('#reg_fname').val(),
    'userID': $('#reg_uid').val(),
    'phoneN': $('#reg_pnumber').val(),
    'register1': true
}

Alternatively, you could leave the formData as it was and just have the PHP check for one or more of the other required fields, for example:

if(isset($_POST['fullName'])){

P.S. You should remove async:false from your code as it's deprecated and unnecessary. contentType: 'charset=UTF-8' also isn't valid or useful, you can remove that too.

And you should fix the SQL injection vulnerability in your mysqli code - in fact, regardless of SQL injection someone could break your query simply by putting ' in one of the input fields, so that's another good reason to sort it out.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Does it not also need a `event.preventDefault();` to stop the form submitting normally? – RiggsFolly May 09 '21 at 09:45
  • @RiggsFolly the `return false` at the end of the validation function should achieve the same effect. – ADyson May 09 '21 at 10:07
  • it steel not working to me. i took all advices but its steel the same problem as it was. ajax success function is running, the server statuscode is 200 but has no response and the data is not inserted into the database. – Lidor May 14 '21 at 04:43
  • @Lidor did you debug it in any more detail than just "it doesn't work"? What path does it take through the PHP code when it runs - does it enter all the `if` blocks as it needs to? Are all the $_POST variables populated as you expected? Does the SQL query command definitely run? Did you fix the SQL injection issues? You'll never fix small problems with your code if you don't learn to analyse the code and debug it properly. Add some logging to your PHP to help you do that. If you need our help, please update the question to show the latest version of your code. – ADyson May 14 '21 at 06:20
  • @ADyson yes i did try your solution and there is no bugs in the code. is going like this pressing the submit button the eventlistening work getting into the else statement because i fill all the fields after it runs the ajax that is getting all the info from the inputs, in the devtools at the network tab is statuscode 200 with all the ajax info but there is no response! that is the problem – Lidor May 14 '21 at 10:25
  • Ok so it sounds like you debugged the Javascript. But none of that description sounds like you debugged the PHP – ADyson May 14 '21 at 10:36
  • @ADyson the php is working fine alone its inserting the data from the page but when i turn on the ajax is not working no more – Lidor May 16 '21 at 20:03
  • I made a demo of your client-side code: https://jsfiddle.net/0yp7nq2o/ . If you watch the network tab in the Developer Tools when you submit the form, you'll see it posts all the data correctly. There's nothing wrong with that code (the version you've shown above, including the change I showed in my answer). – ADyson May 17 '21 at 09:30
  • well you have the same Eshoo as me that there is no response from the server at the success function in the ajax there is response + "work" the response is empty and the info dos not inserted to the data base – Lidor May 17 '21 at 15:30
  • Well I wouldn't expect a response in mine, since I sent it to a dummy endpoint! The point was that it _sends_ correctly. If you don't get the expected response from yours then that's probably the result of a server-side problem. If the data isn't inserted into the DB, that's also a server-side problem. So whatever debugging you did, it wasn't very effective. – ADyson May 17 '21 at 15:37
  • http://www.phpknowhow.com/basics/basic-debugging/ has a simple guide to debugging with PHP. – ADyson May 17 '21 at 15:38