I am trying to post values form HTML file through AJAX as a request and get a JSON formatted string as a response from PHP.
I have done the following
The Javascript file:
$(document).ready(pageLoad);
function pageLoad()
{
$("#submit").click(submitClick)
}
function submitClick()
{
var data = {Year:"2005"};
$.getJSON("db/connect.php", data, fetchData);
}
function fetchData(data)
{
$.each(data, function(index, element) {
$("#content").append(data[index].Name + "<br />");
})
}
The PHP file
<?php
$server = "localhost";
$user = "amey";
$pass = "";
$database = "education";
echo $_POST["Year"];
$conn = mysql_connect($server, $user, $pass) or die("Unable to connect to MySQL");
mysql_select_db($database, $conn);
$query = "select * from BabyNames";
$result = mysql_query($query) or die(error_get_last());
$json = array();
while($row = mysql_fetch_array($result))
{
$json[] = $row;
}
echo json_encode($json);
mysql_close($conn);
?>
I can not retrieve the Year value in the PHP file. I've also tried using $.post and $.ajax function. In $.ajax function, when I remove the dataType: "json", the post method works.