Skip to content
Advertisement

Ajax request json PHP – jsondata mixed with other prints (echoes)

I have an ajax-script that retrieves jsondata from php – so far ok, but the data could not be parsed since other outputs (echoes) comes along with the jsonstring. I searched this issue and it seems one should add header information when sending relevant output (json) from php back to clientside (ajax). When I do that nothing is sent back. How could I solve this?

this is how it looks like on the client side retrieving json (together with other prints)

connected to database { jsondata comes here .. } success

So, how to isolate the jsondata sending it back?

clientside (ajax) , snippet

    $(function(){
            $.ajax({
                type:'POST',
                url: 'endpoint.php?function=getJson',
                data: {name: 'Stockholm'},
                success: function (data){
                console.log('success',data);
                
                var jsonData = JSON.parse(data); //error here when parsing!!!

 

serverside (php), snippet

//header('Content-Type: application/json'); //if I add thos row no data is sent back
$result =  $_GET['function']($_POST['name']);
echo $result;


function getJson($name) {

  ...
  return $json;
}

Advertisement

Answer

I solved the problem by cleaning stdout (output buffer), putting the function call just a line before echo $result

that is:

$result =  $_GET['function']($_POST['name']);   
ob_clean(); // this call solved the problem
echo $result;

source:

https://www.php.net/manual/en/function.ob-clean.php

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement