blank_kuma
blank_kuma

Reputation: 345

Need help on passing PHP variable to jQuery using AJAX

I have a variable in the PHP code called $final_value. I am trying to pass it into a jQuery file using $.ajax but I am unable to do so. Any help will be appreciated.

HTML (test.php)

<body>
    <h1>Test</h1>
    <p class="result">
    <?php            
        $final_value = 27.00;            
        echo '<strong>'.$final_value.'</strong>';
        echo json_encode($final_value);
    ?>
    </p>
    <p id="test"></p>        
</body>

jQuery

$(document).ready(function(){
    createValue();

    function createValue(){        
    $.ajax({
        url: 'http://localhost/test.php',
        method: 'post',            
        dataType: 'json',
        success: function(output){
            $('#test').append(output);
        },
        error: function(){
            alert('error');
        }
    });
    }
});

Upvotes: 0

Views: 33

Answers (1)

Barmar
Barmar

Reputation: 780724

Your PHP script returns HTML, not JSON. So use dataType: 'html' in the AJAX call. But you shouldn't have <body> around the HTML -- it's going to get inserted into a DIV that's already in the body, and you can't have multiple <body> tags in the same document.

You can get rid of echo json_encode($final_value); in the PHP, it's not needed.

Or change the PHP so it only echoes the JSON -- get rid of all the HTML around it. Then your jQuery code will need to wrap the response into HTML and add it to the DOM:

$.ajax({
    url: 'http://localhost/test.php',
    method: 'post',            
    dataType: 'json',
    success: function(output){
        $('#test').append("<strong>" + output + "</strong>");
    },
    error: function(){
        alert('error');
    }
});

Upvotes: 1

Related Questions