ei.schinken
ei.schinken

Reputation: 127

jQuery, JSON and PHP

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

Upvotes: 0

Views: 238

Answers (1)

N.B.
N.B.

Reputation: 14060

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);

Upvotes: 5

Related Questions