0

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');
        }
    });
    }
});
2
  • Um, your test.php file includes non json data.... so the response from that file would be an html document, thus unparsable. Try taking off the dataType: 'json' and console.log(output) to see what you get. Then you can start the process of manipulating the output to match what you want. Commented May 5, 2015 at 17:37
  • @Taplar I think that I am going to change it into dataType; 'html' and see how things work out because my PHP code is part of an HTML file. Still working out how to get the $final_value from HTML though. Commented May 5, 2015 at 17:44

1 Answer 1

1

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');
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

ahh I see. If I use dataType: 'html', how would I get it to detect the $final_value part of php?
Put the response in a DIV, and then use $("#div").find("strong").text() to get the value.
There is no need for ajax in this case then. We can directly detect the value from the HTML file. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.