40

I've been smashing my head against a brick wall with this one, i've tried loads of the solutions on stackoverflow but can't find one that works!

Basically when I POST my AJAX the PHP returns JSON but the AJAX shows Undefined instead of the value:

JS:

  /* attach a submit handler to the form */
  $("#group").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /*clear result div*/
  $("#result").html('');

  /* get some values from elements on the page: */
  var val = $(this).serialize();

  /* Send the data using post and put the results in a div */
  $.ajax({
      url: "inc/group.ajax.php",
      type: "post",
      data: val,
  datatype: 'json',
      success: function(data){
            $('#result').html(data.status +':' + data.message);   
            $("#result").addClass('msg_notice');
            $("#result").fadeIn(1500);           
      },
      error:function(){
          $("#result").html('There was an error updating the settings');
          $("#result").addClass('msg_error');
          $("#result").fadeIn(1500);
      }   
    }); 
});

PHP:

  $db = new DbConnector();
  $db->connect();
  $sql='SELECT grp.group_id, group_name, group_enabled, COUNT('.USER_TBL.'.id) AS users, grp.created, grp.updated '
        .'FROM '.GROUP_TBL.' grp '
        .'LEFT JOIN members USING(group_id) '
        .'WHERE grp.group_id ='.$group_id.' GROUP BY grp.group_id';

    $result = $db->query($sql);     
    $row = mysql_fetch_array($result);
    $users = $row['users'];
    if(!$users == '0'){
        $return["json"] = json_encode($return);
        echo json_encode(array('status' => 'error','message'=> 'There are users in this group'));
    }else{

        $sql2= 'DELETE FROM '.GROUP_TBL.' WHERE group_id='.$group_id.'';
        $result = $db->query($sql2);

        if(!$result){
            echo json_encode(array('status' => 'error','message'=> 'The group has not been removed'));
        }else{
            echo json_encode(array('status' => 'success','message'=> 'The group has been removed'));
        }
    }

JSON Result from firebug:

{"status":"success","message":"success message"}

AJAX Displays the JSON result as Undefined and I dont have a clue why. I have tried displaying adding dataType='json' and datatype='json'. I have also tried changing it to data.status and data['status']: still no joy though.

Any help would be really appreciated.

hooknc
  • 4,253
  • 4
  • 30
  • 53
Steven Marks
  • 658
  • 1
  • 6
  • 18
  • 3
    Set a "application/json" header `header('Content-Type: application/json');` – hank Oct 03 '13 at 09:12
  • 4
    `datatype` should have a capital `T`: `dataType: 'json'`. In theory it should infer the type from the response, so this may not fix the issues. – Rory McCrossan Oct 03 '13 at 09:13
  • Either @hank or @Rory's suggestion should be enough. If the correct mimetype is set, there is no need to specify the `dataType` – Johan Oct 03 '13 at 09:15

5 Answers5

48

Make it dataType instead of datatype.

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

header('Content-Type: application/json');

Correct Content type for JSON and JSONP

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

Community
  • 1
  • 1
Sorter
  • 8,190
  • 5
  • 52
  • 63
  • Hi Thanks for this! most of the posts say that header('Content-Type: application/json'); isnt required! obviously it is! – Steven Marks Oct 03 '13 at 09:41
  • I'm very glad if this helped you. I know how it feels when something like this doesn't work. And yes I've too banged my wall on the head for this in the past :D but with a different server side language. – Sorter Oct 03 '13 at 09:44
  • I do have one script that still doesn't work, I am deleting a row from a table and then returning json however the json seems to have the ID from the deleted row in front of it: `38{"status":"success","message":"The group has been removed"}` – Steven Marks Oct 03 '13 at 09:53
  • You have to print and see what php is sending and fix accordingly. – Sorter Oct 03 '13 at 09:57
  • This was the solution to my problem – AdRock Oct 21 '16 at 13:46
5

I recommend you use:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

Shakti Patel
  • 3,482
  • 4
  • 19
  • 27
  • if you use success callback, you already have resulting string parsed into javascript object and put as a parameter in the success callback function. – Simon Polak May 07 '14 at 19:06
3

Use parseJSON jquery method to covert string into object

var objData = jQuery.parseJSON(data);

Now you can write code

$('#result').html(objData .status +':' + objData .message);
mujaffars
  • 1,327
  • 12
  • 33
2

try to send content type header from server use this just before echoing

header('Content-Type: application/json');
Pankaj Sharma
  • 1,765
  • 1
  • 16
  • 22
2

Your datatype is wrong, change datatype for dataType.

Arleal
  • 96
  • 3