简体   繁体   中英

Having trouble in sending the results from pdo to ajax

I want to do is if the user successfully registered the pdo will provide an information and send it to ajax and the ajax will message if the user is registered or not. It was working properly after i put this condition in my pdo and now it wont insert no more and ajax tells "error registering user!" all the time.

script:

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

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

        var data = {};
        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) {
            if (Number(response) == 1)
                {
                alert("User successfully registered");
                }
                      else
                {
                alert("Error registering user!");
                }
            }
        });
            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();
    $results ? echo "1"; : echo "2"; ;
?>

It seems that you have error in :

$results ? echo "1"; : echo "2"; ;

yours demo

try like this :

echo  $results ? "1" : "2";

working demo

you can see here a tutorial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM