0

Please find below the javascript which loads when main page is loaded.

    $(document).ready(function() {

       $.post('../business logic/NewsLogic.php', null, function(response) {
             var respObj = $.parseJSON(response);
             if (respObj != null) {
                 alert('I am here ');
             }
});

I can't able to parse JSON i got error that object doesn't support property or method parseJSON

/* below is the sample PHP */

  $newsDAO = new NewsDAO();
  $newsInfo = new News();
  $respArr = array();

  $respArr = $newsDAO->showAllNews();
  print json_encode($respArr);

where respArr is an array which contains Elements.

2 Answers2

0

can you post the $.post response?

anyway, i think it will be better to use $.ajax with json as dataType like:

   $(document).ready(function() {

        $.ajax({
type:'post',
        url: '../business logic/NewsLogic.php',
        data: 'somequerystring',
        dataType: 'json',
        success: function(jsonObject) {

        }
        })

    });
sd1sd1
  • 1,028
  • 3
  • 15
  • 28
0

use JSON.parse method

in your code it would fit like

var respObj = JSON.parse(response);

*********edit*********

Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:

var json = '{"result":true,"count":1}',
    obj = JSON.parse(json);

alert(obj.count);

For the browsers that don't you can implement it using json2.js.

As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:

var json = '{"result":true,"count":1}',
    obj = JSON && JSON.parse(json) || $.parseJSON(json);

This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.

source : Parse JSON in JavaScript?

Community
  • 1
  • 1
Pranay Bhardwaj
  • 1,059
  • 8
  • 9
  • Still JSON is undefined on javascript page – user1511414 Aug 29 '13 at 20:34
  • @Neo `JSON && ...` should probably test with `window.JSON` or `typeof JSON !== 'undefined'`. Testing `JSON` alone will throw an error if it hasn't been declared. Member operators and `typeof` can be used to avoid that. – Jonathan Lonowski Aug 29 '13 at 20:42