3

I am trying to make a functionality where I am sending Name and Age using ajax. The same is gathered by PHP and then stored to DB. I think I am doing it correctly but data not saved in database. Can someone help me out?

HTML

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('button').click(function(){
        $.ajax({
            url: 'addData.php',
            type: 'POST',
            dataType: "json",
            data: {
                name: $('#name').val(),
                age: $('#age').val(),
            }
        })
    });
});
</script>
</head>
<body> 
<input id="name" type="text" />
<input id="age" type="text" />
<button>Click</button>
</body> 
</html> 

PHP

<?php

//Parameters for connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test1";

//Reading json
$data_back = json_decode(file_get_contents('php://input'));

// set json string to php variables
$name = $data_back->{"name"};
$age = $data_back->{"age"};

// Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);

//Creating Query
$sql = "INSERT INTO table1 (name, age) VALUES ($name, $age)";

//Running Query
$conn->query($sql);

//Closing Connection
$conn->close();

?>

ERROR

enter image description here

11
  • 1
    can you share your error from console.? Commented Mar 5, 2016 at 20:56
  • You'll want to parameterize your query, just inserting $name and $age into the query produces invalid SQL (and a good chance for someone to insert their own potentially malicious SQL) Commented Mar 5, 2016 at 20:56
  • @K.Uzair - shared it! Commented Mar 5, 2016 at 20:59
  • 1
    you need to put quotes around strings in INSERT: ...('$name', '$age')... Commented Mar 5, 2016 at 21:04
  • 1
    and you get no error in console now? did you output you values if they are posted from ajax request.? Commented Mar 5, 2016 at 21:07

3 Answers 3

1

Even though you're sending data with jquery as json, php is still recieving it as a $_POST object. So, this should work:

$name = $_POST['name'];
$age = $_POST['age'];
Sign up to request clarification or add additional context in comments.

1 Comment

This did it for me ... ;)
1

I think your object $data_back is empty because of errors in parsing of data by function json_decode. You should try to use var_dump($data_back); exit; after json_decode or more advanced methods such as debugging.

1 Comment

Yes, I was getting blank rows inserted +1 for this analysis.
0

I believe this is the proper way to access data post json_decode

$name = $data_back->name;

I also recommend looking into prepared statements for the database query execution...Ok, I HIGHLY recommend you look into it.

Edit: Maybe try this as well: Replace file_get_contents() with $_POST;

1 Comment

You can also do json_decode($data,true) to return an associative array like this: $name = $json['name'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.