Stelios
Stelios

Reputation: 71

Send data to the server with AJAX

I want some help with the following issue. The following code is not working for me. Is there anyone who can help me with that? I've watched this in a youtube video and i can't find why it is not running.. I want to inform you that i am running a WAMP Server at 127.0.0.1 and it is very weird that the browser does not give me any response for errors, etc..

Here is my PHP code:

<?php
$host="127.0.0.1";
$username = "root";
$password = "";
$db = "data";

$conn = mysqli_connect($host, $username, $password, $db);


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

    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $gender = $_POST['slct'];

    $query = "Insert into users (firstname, lastname,gender) Values(?,?,?))";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('sss', $fname, $lname, $gender);
    $stmt->execute();

    if(mysqli_affected_rows($conn) > 0){
        echo "insert";
    }
    else{
        echo "no";
    }

}
?>

Here is my html code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<h3> Insert Data into Database</h3>
<form id="form1" method="post">
<p> Enter FirstName</p>
<input type="text" name="fname" class="form-control">
<br>
<p> Enter lastName</p>
<input type="text" name="lname" class="form-control">
<br>
<p>Enter Gender</p>
<select class="form-control" name="slct">
<option value="Male">Male </option>
<option value="Female">Female</option>
</select>
<br><br><br>
<button class="btn btn-primary" onclick="insertData()">Submit</button>

</form>


</body>

<script>
    function insertData(){

        var formData = $('#form1').serialize();

        $.ajax({
        url:'http://127.0.0.1/PHP/insert.php',
        data:formData,
        type:'Post',
        success:function(response){
        console.log(response);

        },
        error:function(err){
            console.log(err);

        }

        })

    }
</script>

</html>

Any help will be appreciate. Thank you in advance!

Upvotes: 1

Views: 42

Answers (1)

DataVader
DataVader

Reputation: 780

Your insert-command is incorrect. Change ...(?,?,?))"; to ...(?,?,?)";

Better use an IDE like netbeans, because they would highlight such errors. Also you should switch from mysqli to PDO. And you don't need to check affected rows. The $stmt->execute() returns a boolean

Upvotes: 1

Related Questions