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.

3
  • Where is dataType: "json" in your code? Commented Nov 14, 2014 at 7: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? Commented Nov 14, 2014 at 7:19
  • I am not able to post. The PHP does not read the $_POST['Year']. The echo is just for debugging. Commented Nov 14, 2014 at 19:18

2 Answers 2

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();
        });
    });
 });
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

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.