Please help with Error in parsing json obj created by PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
harshadmehta
Forum Newbie
Posts: 2
Joined: Mon Jul 25, 2011 8:08 pm

Please help with Error in parsing json obj created by PHP

Post by harshadmehta »

I have a HTML-java script which invokes php script.
php script goes and retrieves certain records from mysql DB and returns JSON Object.
But back in the javascript i always get error in parsing json object.
i have tried various options with eval but nothing works.
Let me know if you find what i am doing wrong.

Thanks in advance

Response from PHP Script is -

Code: Select all

{"users":[{"id":"1","name":"john"},{"id":"2","name":"test"},{"id":"3","name":"anou"}]}
HTML PAGE -
-------------------------------------

Code: Select all

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Ajax - PHP example</title>
    </head>

<script language="javascript" type="text/javascript">
    var httpObject = null;
    var my_JSON_object = {};

    function getHTTPObject(){
        if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
        else if (window.XMLHttpRequest) return new XMLHttpRequest();
        else {
              alert("Your browser does not support AJAX.");
               return null;
        }
    }

	function setOutput(){
	    if(httpObject.readyState == 4){
	     var myObject = eval( "(" + httpObject.responseText + ")" );         //THIS IS WHERE I get Syntax ERROR
	     //var myObject = JSON.parse('(' + httpObject.responseText + ')');
	       for (var i in myObject) {
			alert(i + ': ' + myObject[i]);
		}
	    }
	}


    function doWork(){
        httpObject = getHTTPObject();
        if (httpObject != null) {
            httpObject.open("GET", "http://localhost:7777/testjson.php", true);
            httpObject.setRequestHeader("Content-Type", "application/json");
            httpObject.send(null);
            httpObject.onreadystatechange = setOutput;
       }
    }
    </script>

   <body>
     <form name="testForm">
         Input text: <input type="text" onkeyup="javascript:doWork();" name="inputText" id="addDisplay" />
        Output text: <input type="text" name="outputText" id="outputText" />
     </form>
    </body>
    </html>
--------------------------------------

PHP SCript
-----------------------------------------

Code: Select all

<?php

# Define MySQL Settings
define("MYSQL_HOST", "localhost");
define("MYSQL_USER", "xxxx");
define("MYSQL_PASS", "xxxx");
define("MYSQL_DB", "xxxx");
$conn = mysql_connect("".MYSQL_HOST."", "".MYSQL_USER."", "".MYSQL_PASS."") or die(mysql_error());
mysql_select_db("".MYSQL_DB."",$conn) or die(mysql_error());
$sql = "SELECT * FROM name";
$res = mysql_query($sql);

$arr = array();
while ($field = mysql_fetch_object($res))
{
	$arr[] = $field;
}
 echo '{"users":'.json_encode($arr).'}';
?>
-----------------------------
Last edited by Benjamin on Tue Jul 26, 2011 3:49 am, edited 1 time in total.
Reason: Added [syntax=php|sql|css|javascript] and/or [text] tags.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Please help with Error in parsing json obj created by P

Post by Benjamin »

Without knowing the error, I believe this would fix it.

Code: Select all

echo json_encode(array('users' => $arr));
harshadmehta
Forum Newbie
Posts: 2
Joined: Mon Jul 25, 2011 8:08 pm

Re: Please help with Error in parsing json obj created by P

Post by harshadmehta »

This did not work.
Tried a few other things , executed php script directly and used its output in HTML directly , populating outputText box , worked fine (like below)-
var myJSONObject = {"users":[{"id":"1","name":"john"},{"id":"2","name":"test"},{"id":"3","name":"anou"}]};
document.getElementById('outputText').value =myJSONObject.users[0].name;

going back to calling PHP from webpage and using callback and populating the same Text Box, i always get '''' populated. seems like echo from php is not making it in the httpObject.responseText.
Also I don't see any error in the Error Console.

In the callback function code -
if(httpObject.readyState == 4){
var temp = JSON.stringify(httpObject.responseText);
document.getElementById('outputText').value =temp;
}

outputText box is populated with - ''''
(same php script that i mentioned above echo's json encoded object using
echo '{"users":'.json_encode($arr).'}'; OR echo json_encode(array('users' => $arr));

Any ideas........
Post Reply