1

What I want to do is save all the data - after the user has filled all the forms - using Ajax and PDO.

My problem is that my Ajax won't send to user.php. I got an error in the console after I click the button says "data is not defined". Can anyone help me fix my code?

HTML

<form method="post" enctype="multipart/form-data">  
<img id="picture" data-src="#" /> <br />
<input type='file' name="image" id="imgInp" accept="image/*" /><br />
Name: <input type="text" id="name" name="name" /><br />
Age: <input type="text" id="age" name="age" /><br />
Address: <input type="text" id="address" name="address" /><br />
<input type="radio" name="gender" id="gender" value="male" />Male
<input type="radio" name="gender" id="gender" value="Female" />Female<br />
<input type="submit" name="submit" id="submit" value="submit" />
</form>

Ajax

<script type="text/javascript">
$(document).ready(function() {

   $('#submit').click(function (e) {
       e.preventDefault();


        data.name = $('#name').val();
        data.age = $('#age').val();
        data.gender = $('#gender').val();
        data.address = $('#address').val();
        data.image = $('#imgInp').val();


        $.ajax({
            type: "POST",
            url: "user.php",
            data: data,
            cache: false,
            success: function (response) {

            }
        });
            return false;
    });

});
</script> 

user.php

<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";

$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$name = @$_POST['name'];
$age = @$_POST['age'];
$address = @$_POST['address'];
$gender = @$_POST['gender'];
$imageName = @$_FILES['image']['name'];


 $q = "INSERT INTO students(name, age, address, gender, imageName ) VALUES(:name, :age, :address, :gender, :image)";

    $query = $dbc->prepare($q);
    $query->bindParam(':name', $name);
    $query->bindParam(':age', $age);
    $query->bindParam(':address', $address);
    $query->bindParam(':gender', $gender);
    $query->bindParam(':image', $imageName);


    $results = $query->execute();

?>
2

2 Answers 2

1

Looks like you forgot to define your data variable.

var data = {};
data.name = $('#name').val();
Sign up to request clarification or add additional context in comments.

Comments

0

You should initialize your data object as followed var data = {};.

Also consider to rename data to something like param. Just to not interfere with reserved names within the $.ajax({});-function. It's just a tip from a developer perspective.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.