0

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.

Amey Kelkar
  • 155
  • 2
  • 12
  • Where is `dataType: "json"` in your code? – Manwal Nov 14 '14 at 07:17
  • `data.Name` instead, is this tried? do you get a proper and valid `json` response? why you echoed this `echo $_POST["Year"];` in the same file where you are echoing json? – Jai Nov 14 '14 at 07:19
  • I am not able to post. The PHP does not read the $_POST['Year']. The echo is just for debugging. – Amey Kelkar Nov 14 '14 at 19:18

2 Answers2

0

Please make changes in your code, if your php code working fine.

 $(document).ready(function() {
    var pageLoad = function() {
        $("#submit").click(function(){
          submitClick();
        })
    });
    pageLoad();
 });

if you want submit form/data on click "#submit" then no need to pageLoad function

 $(document).ready(function() {
        $("#submit").click(function(){
          submitClick();
        });
    });
 });
Abhishek Kasera
  • 240
  • 1
  • 12
0

$.getJSON() method does an HTTP GET and not POST. You need to use $.post().

$.post(url, dataToBeSent, function(data, textStatus) {
  //data contains the JSON object
  //textStatus contains the status: success, error, etc
}, "json");

click here for solution more solution

Community
  • 1
  • 1
Selvaraj
  • 68
  • 1
  • 4
  • I tried this, but the problem is that PHP is not able to read the POST variable from the request. Neither in $.ajax method nor in $.post method. – Amey Kelkar Nov 14 '14 at 19:20