I have my HTML file like this:
<script>
$(document).ready(function () {
$("#btn").click( function() {
var id = $('#id').val();
var name = $('#name').val();
var Address = $('#Address').val();
$.ajax({
url: "http://localhost/connection.php",
type: "POST",
data : { topost: JSON.stringify({id: id, name: name, Address: Address}) },
//I ASSUME HERE IM PASSING MY THREE FIELDS id, name and Address
//IN A STRING CALLED 'TOPOST' TO MY FILE CONNECTION.PHP
//WHICH IS HOSTED ON MY LOCALHOST, IM USING XAMPP.
datatype: "jsonp",
success: function (status) {
if (status.success == false) {
alert("Failure!");
}
else {
alert("Success!");
}
}
});
return false;
});
});
</script>
Now, in my file connection.php
, which is hosted on my localhost, I'm trying to read these three fields so that
I can put all three in a database (MySQL).
However, the error I get is this:
Connected to database!<br />
<b>Notice</b>: Undefined index: topost in <b>C:\xampp\htdocs\connection.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>: Undefined index: topost in <b>C:\xampp\htdocs\connection.php</b> on line <b>29</b><br />
My question is:
Why is 'topost' undefined? How do I make connection.php
understand that I'm sending JSON data from my HTML file in a variable called 'topost'?
So kindly go through the following PHP file and suggest the errors.
The server side PHP file:
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password);
if($con) { echo "Connected to database!"; }
else { echo "Could not connect!"; }
//or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$posteddata = $_POST['topost'];
$thedata= json_decode($_POST['topost']);
echo ($thedata);
mysql_close();
?>