copilot0910
copilot0910

Reputation: 431

AJAX with JSON and PHP not returning any data... I think

Why does my code not work?

I know I am sending data,

But there is no response.

jQuery

    $(document).ready(function(){
            $("form").submit(function () {

                var uname = document.getElementById("username").value;
                var pword = document.getElementById("password").value;
                var postData = {
                    username: uname,
                    password: pword
                };
                var PostDataString = JSON.stringify(postData);
                alert(PostDataString);

            $.ajax({
               url: "test.php",
               type: "GET",
               data: PostDataString,
               dataType: 'json',
               contentType: 'json',
               cache: false,
               success: function (ReturnData) {
                    alert("Yay!");
               } 
            });
    });
    });

PHP

$json = $_GET["PostDataString"];
$jsonarray = json_decode($json, true);
echo $jsonarray;  

Upvotes: 1

Views: 267

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

json_decode is for turning a JSON string into PHP constructs. json_encode does the opposite and is what you want. You are expecting a json data type on the JavaScript side; jQuery will throw an error if it does not get valid JSON in that case.

The JSON.stringify conversion is unnecessary since $.ajax accepts a JavaScript object for its data attribute. In fact, stringifying the JSON prevents it from being sent as any parameter.

If you remove JSON.stringify and just send postData as-is. You can access $_GET['username'] and $_GET['password'], but no others.

Upvotes: 4

Related Questions