Michael Barney
Michael Barney

Reputation: 1

Very simple code using $.post of jquery is showing the entire code instead of the echo

The code is supposed to change the writing on the div from "Click here" to "hello", but instead, it show the entire code of the php document.

HTML:

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
</head>

<body>
    <div id="target">
      Click here
    </div>

    <script type="text/javascript" src="jcode.js"></script>
</body>
</html>

Javascript:

$( "#target" ).click(function() {
  $.post(
        'test.php', {name:"Donald"}, 
        function(data){
            $('#target').html(data);
        }
    );
});

PHP:

<$php
if(isset($_POST['name'])){
    $name = $_POST['name'];
    echo $name;
}
echo 'hello';
$>

Upvotes: 0

Views: 40

Answers (2)

Marios Fakiolas
Marios Fakiolas

Reputation: 1545

Force php to return data in json format and of course the relevant header so they can understand each other really well. Try using this method:

PHP

<?php header('Content-Type: application/json');

    if(isset($_POST['name']))
    {
        $name = $_POST['name'];

        $response = [
            'name' => $name
        ];
    }

    echo json_encode($response);
?>

Javascript:

$( "#target" ).click(function() {
    $.post('test.php', {name:"Donald"}, 
        function(data){
            $('#target').html(data.name);
        }
    );
});

Upvotes: 0

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60577

<$php and $? are not PHP tags, <?php and ?> are. Use the folowing.

<?php
    if(isset($_POST['name'])){
        $name = $_POST['name'];
        echo $name;
    }
    echo 'hello';
?>

Upvotes: 3

Related Questions