0

I don't really understand why my code ins not working. I am simply taking values from a form and I want to insert them into a database using JSON and AJAX. Is there anything that I am doing wrong?

        $(document).ready(function() {
            $("#insert").click(function() {
                var email = $("#email").val();
                var password = $("#password").val();
                var name = $("#name").val();
                var bio = $("#bio").val();

                var postData = {"email":email,"password":password,"name":name,"bio":bio};
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: "http://**************/php-code/insert.php",
                        data: {myData:postData},
                        crossDomain: true,
                        cache: false,
                        beforeSend: function() {
                            $("#insert").val('Connecting...');
                        },
                        success: function(data) {
                            if (data == "success") {
                                alert("inserted");
                                $("#insert").val('submit');
                            } else if (data == "error") {
                                alert("error");
                            }
                        }
                    });
                return false;
            });
        });

And PHP file that sits on the server:

 include "db.php";
 if(isset($_POST['myData'])) {
 $email=$_POST['email'];
 $password=$_POST['password'];
 $name=$_POST['name'];
 $bio=$_POST['bio'];
 $q=mysqli_query($con,"INSERT INTO 'user' ('email','password','name', 'bio') VALUES ('$email','$password','$name','$bio')");
 if($q)
  echo "success";
 else
  echo "error";
 }
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
notFake7
  • 140
  • 1
  • 12
  • have you included jquery? – Sugumar Venkatesan Mar 06 '17 at 13:20
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Mar 06 '17 at 13:22
  • 1
    **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Mar 06 '17 at 13:22
  • [You may want to consider this before posting an answer for this question](http://meta.stackoverflow.com/q/344703/), it may change your mind. – Jay Blanchard Mar 06 '17 at 13:22
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Mar 06 '17 at 13:22

2 Answers2

1

your insert query should be as follows :

$q=mysqli_query($con,"INSERT INTO `user` (`email`,`password`,`name`, `bio`) VALUES ('$email','$password','$name','$bio')");

notice the use of (`) instead of (')

and it's a high recommended to use prepared statement instead of your past statement to prevent sql ejections

$q=mysqli_prepare($con,"INSERT INTO `user` (`email`,`password`,`name`,`bio`) VALUES (:email,:password,:name,:bio)");
mysqli_stmt_bind_param($q, "ssss", $email, $password, $name, $bio);
mysqli_stmt_execute($q);

and in your ajax you are assigning your either need to change it or need to update your php code again ,

if you need to keep your ajax , so php should be as follows :

$email=$_POST['myData']['email'];
$password=$_POST['myData']['password'];
$name=$_POST['myData']['name'];
$bio=$_POST['myData']['bio'];

if you want to keep your php , so your ajax should be follows :

var postData = {"myData":postData,"email":email,"password":password,"name":name,"bio":bio};

then this line data: {myData:postData},

should be as follows :

data: postData,
hassan
  • 7,812
  • 2
  • 25
  • 36
  • you are absolutely right , just a fault , i've updated it – hassan Mar 06 '17 at 13:26
  • 1
    You missed the portion with sending the values via AJAX and your placeholders should only be `?` You're using placeholders PDO style. – Jay Blanchard Mar 06 '17 at 13:27
  • i've updated my answer – hassan Mar 06 '17 at 13:36
  • Hi, sadly this method is not working, no data is inserted – notFake7 Mar 06 '17 at 14:00
  • what's the error ? – hassan Mar 06 '17 at 14:07
  • Undefined index of these: $email=$_POST['myData']['email']; $password=$_POST['myData']['password']; $name=$_POST['myData']['name']; $bio=$_POST['myData']['bio']; I got this to work without using 'myData' however now I dont get succes message back. Data is inserted – notFake7 Mar 06 '17 at 14:15
  • you are sending data as `data: {myData:postData}` or `data: postData` ? – hassan Mar 06 '17 at 14:17
  • data: postData . – notFake7 Mar 06 '17 at 14:18
  • use this instead `data: {myData:postData}` – hassan Mar 06 '17 at 14:19
  • Okey I know why it dosnt work! my db connection is not a PDO style. I guess I will use simple method because I am trying to learn, security is not important for me atm. The only problem that I have is that When I submit my data, the echo 'success' dosnt work and I am not sure why. Because of that my j.query button value is stuck on 'connecting'. Thank you or help – notFake7 Mar 06 '17 at 15:16
1

Your data does not need to be send with 'myData:...'.

It is already in a key value pair format and is ready to send.

Just replace data: {myData:postData}, with data: postData,

And in you php code remove the check to myData and only check the fields you want to get. (email, password, etc.)

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

As stated in the comment, your code is highly vulnerable and should use prepared statements!

cb0
  • 8,415
  • 9
  • 52
  • 80