0

HeyHo,

I'm entering a name in the following website and submit this name with a button.

HTML Code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>AJAX</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
        <script type="text/javascript" src="js/jquery.js"></script>
    </head>
    <body>
        <div><input type="button" id="ajaxButton" value="start"></div>
        <div><input type="text" id="name"></div>
        <div id="content"></div>
    </body>
</html>

If I'm clicking the button, jQuery sends the AJAX request to my PHP script, which creates my respond.

jQuery Code:

$(document).ready(function() {
    $('#ajaxButton').click(function() {
        var name = encodeURIComponent($('#name').val());
        $.ajax({
            url         : "js/script.php",
            type        : "POST",   
            data        : "name="+name,
            dataType    : "json",
            success : function (data) {
                alert(data['hello']);
                var json = $.parseJSON(data);
                alert(json.hello);
                $("#content").html(json.hello);
            }
        });
    });
});

My PHP script creates a respond and encodes it as a JSON array.

PHP Code:

<?php

if (isset($_POST['name'])) {
    $ret = Array("hello" => "Hallo " . $_POST['name']);
    echo json_encode($ret);
}
?>

When I'm running my code, only alert(data['hello']); pops up and alert(json.hello); doesn't. What am I doing wrong?

Cheers ei.schinken

1
  • use data.hello instead json.hello Commented Feb 24, 2012 at 9:52

1 Answer 1

5

var json = $.parseJSON(data); is not neccessary.

dataType property of $.ajax has been set to json, therefore any response will be interpreted as json.

Use alert(data.hello);

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

Comments

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.