1

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;  

1
  • did you mean to GET or POST? Your options object looks a little confused. Commented Feb 7, 2013 at 3:06

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But now a new problem arises. How do I return the GET data? What I mean is now that I can access the data in my php, how do I return it to the $.ajax function to work with the response?
@copilot0910 it depends .. wildly. What would be best for you to have in ReturnData? An object like {username: "username", password: "password"}? If so, use json_encode(array('username' => $_GET['username'], 'password' => $_GET['password']))
I need to return the array, so yes.
But still the problem arrises. When I try to alert anything after the data comes back from the PHP, I am getting nothing.

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.