1

I'm trying to use JSON, I'm getting the information from the server so I've written this PHP file:

     include("db_connect.php");

      mysql_connect($host,$username,$password);
      @mysql_select_db($database) or die( "Unable to select database");

      $result = mysql_query("SET NAMES utf8");
      $query = "SELECT * FROM models WHERE models.product_id='".$product_selected."'";
      $result = mysql_query($query);
      $json_object =  "{ \"model\": [";

       while($result_row = mysql_fetch_row($result)) {
         $json_object .= " {\"model_name\" : \"".$result_row[1]."(".$result_row[2].")";
         $json_object .= "\"},";

        }
           $json_object = substr($json_object,0,strlen($json_object)-1);
           $json_object .= " ]};";

           echo  json_encode($json_object);

?>

The output of the PHP file is in JSON format like this:

{ "model":
           [
              {"model_name" : "xxxxx "},
              {"model_name" : "xxxxx "},
              {"model_name" : "link2(U)"},
              {"model_name" : "xxxxx)"}
           ]
  };

But i'm getting this response in Ajax like:

var my_JSON_object = {};
var xmlHttp = createXmlHttpRequestObject();
  try {
         xmlHttp.open("GET", "ajaxproduct_new.php?product_id=" product_id,true);
         xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
              my_JSON_object = JSON.parse( xmlHttp.responseText );

             alert(my_JSON_object.model[0].model_name);
              }
  }
             xmlHttp.send(null);

   } catch (e){
           alert("Can't connect to server:\" e.toString());
}

But when I'm doing alert of my_JSON_object.model[0].model_name it showing the error as my_JSON_object.model is undefined.

Why is it coming like this? I have tried all the stuffs. Can any one please tell me?

4
  • How are you constructing the JSON Commented Mar 23, 2011 at 7:30
  • Can you edit and add the responseText to your question. Maybe it's malformed. Commented Mar 23, 2011 at 7:33
  • That’s not JSON. The ; is illegal in JSON. Commented Mar 23, 2011 at 7:34
  • at very first, the browser displays all the product name, then when user clicks on the particular product, all the models related to that product will gets displayed, i'm using ajax call to get the corresponding models as u see the above php file for getting the models from mysql database Commented Mar 23, 2011 at 8:04

3 Answers 3

2

You are creating a string that looks like JSON and pass this to json_encode, which is wrong. json_encode accepts an object or an array. So, create an array instead of a string:

$data = array();

while(($result_row = mysql_fetch_row($result))) {
    $data = array('model_name' => $result_row[1] . '(' . $result_row[2] .')');
}

echo json_encode(array('model' => $data));

Your JavaScript code looks ok.

Sign up to request clarification or add additional context in comments.

6 Comments

thankz a lot!!! now it working , but in this line of code there is some error , so the correct code should be like this $data[] = array('model_name' => $result_row[1] . '(' . $result_row[2] .')'); once again thankzzzzzzz
@SivaRamakrishnan: Oh yes, I missed the closing parenthesis :) Fixed. Don't forget to accept this answer by clicking on the tick outline next to it ;)
how to find out the length of the particular json array when i'm doing alert(my_JSON_object.length) it showing me undefined
@SivaRamakrishnan: Because my_JSON_object is an object and not an array. It has no property length. my_JSON_object.model contains the array, so you have to do my_JSON_object.model.length.
@SivaRamakrishnan: :D Just keep on practicing and reading :) Happy coding!
|
1

Attempting to do anything with data.model[0].model_name before you know what data is sounds bad to me. And even if it just for testing something, eval won't really help you.

So, the first step in debugging this would be to alert the xmlHttp.responseText variable!

  • If it doesn't look like you expect it to do, then the server is the issue.

  • If it does look like you expect it to do, then you have some problem client side (or you've missed something about what's valid in json).

That being said, Felix's answer is probably the right way to go.

Comments

0

try the following lines of codes var data = eval("(" + xmlHttp.responseText + ")"); alert(data.model[0].model_name)

6 Comments

eval is not recommended but for now to get quick result use eval, if the problem is still exist then try to explore your server side code
No i had tried the same error is coming data.model is undefined
If this does not work: eval("var data ="+xmlHttp.responseText); alert(data.model[0].model_name); then there is a data issue
And what useful thing could the eval tell us that a simple alert could not?
Assuming the data looked correct, and we all assumed it did until we learned otherwise, the eval would give errors if the json was malformed as it turned out to be.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.