1

i have an json array and i want to parse it in java-script but my jquery gives me following error:

JSON.parse: unexpected character 

The code in jquery is,on which the error comes:

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {//error comes on this line.
return window.JSON.parse( data );
} 

My code is:

success: function(msg){
                var test= JSON.parse(msg);
                var question=test.question;
        document.getElementById('question').value=question;

I am using the latest version of jquery

 <script src="http://code.jquery.com/jquery-latest.js"></script>

I am getting this in function(msg):

[Object { question=

"What is your religious affiliation?"

,  userQuestionCategoryId=

"1"

}]

Here is my Php code:

function getquest()
        {
             $id=$this->input->post('qid');
             $data=$this->adminsetting->getquestion($id);
             if(count($data)>0)
             //echo $data[0]->question; 
             echo json_encode($data);
             else
             echo "No Question In database";
        }

Thanks in advance.

7
  • I guess it depends on the data you parse. Have a look to stackoverflow.com/questions/8524933/…. You don't need jQuery as well, to use JSON.parse Commented Nov 5, 2012 at 11:54
  • Do you have an example of the json you're trying to parse? Commented Nov 5, 2012 at 11:54
  • consoe.log(msg) and see the result , and please add your php code Commented Nov 5, 2012 at 11:56
  • 1
    FYI: jQuery uses the internal JSON parser if available (source) so you can just use $.parseJSON() Commented Nov 5, 2012 at 11:58
  • @Andreas ,so am i doing wrong in my php code??i am using json_encode($data).is there any other way to do it?? Commented Nov 5, 2012 at 12:03

2 Answers 2

1

This:

{ question=

"What is your religious affiliation?"

,  userQuestionCategoryId=

"1"

}

Must be like this:

{"question":"What is your religious affiliation?",  "userQuestionCategoryId":"1"}
Sign up to request clarification or add additional context in comments.

Comments

1

Actually the json i s becomes alredy parsed so i have to just used the index,i am missing to use the index msg[0]. Thats why I am getting problem.

success: function(msg){



        document.getElementById('question').value=msg[0].question;

        document.getElementById('id').value=msg[0].userQuestionCategoryId;
        //alert(msg);
        } }); 

Comments

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.