Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while json creation in php

I am trying to fetch data from mysql into php and returning it in json format to an controller(angular).

While json creation, some unwanted string is getting appended because of which i am getting error while traversing the json.

Following is my php code:

$json_response = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $row_array["name"] = $row["name"];
    $row_array["quantity"] = $row["quantity"];
    array_push($json_response,$row_array);
}
echo json_encode($json_response);

And following is the console output after printing the json(console is in controller) :

{itemData:{"data":[{"name":"item1","quantity":"10"},{"name":"item2","quantity":"20"},{"name":"item3","quantity":"25"}]      

<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->

}}

Above the highlighted part is coming in the json, because of which the error is happening.

Please help me to resolve the issue.

like image 597
Rohan Kangale Avatar asked Sep 28 '22 04:09

Rohan Kangale


1 Answers

Ok, After having a little research I can confirmed that my comment is right. Your code is fine and the json string that is being created by your code is alright.

However, the unwanted appended string:

<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->

Is being appended by your server. I believe that it's a free server and therefore they allow themselves to inject their own code into your website. They have a mechanism that append that script into every request that is being made from your server (including ajax requests).

Since this code is being added by the server, it seems that there's nothing you can do in your code to overcome it. It seems that the only option is to look for another hosting company or having a paid plan.

Update - You can try and use the exit(); function right after printing the json string. It might break the host's injection.

like image 68
Ofir Baruch Avatar answered Oct 12 '22 23:10

Ofir Baruch