Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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. This is killing me

share|improve this question
2  
Set a "application/json" header header('Content-Type: application/json'); –  hank Oct 3 '13 at 9:12
2  
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 3 '13 at 9: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 3 '13 at 9:15

5 Answers 5

up vote 10 down vote accepted

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'.

share|improve this answer
    
Hi Thanks for this! most of the posts say that header('Content-Type: application/json'); isnt required! obviously it is! –  Steven Marks Oct 3 '13 at 9: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 3 '13 at 9: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 3 '13 at 9:53
    
You have to print and see what php is sending and fix accordingly. –  Sorter Oct 3 '13 at 9:57

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

header('Content-Type: application/json');
share|improve this answer

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);
share|improve this answer

I recommend you use:

var returnedData = JSON.parse(data);

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

share|improve this answer
    
if you use success callback, you already have resulting string parsed into javascript object and put as a parameter in the success callback function. –  blushrt May 7 at 19:06

Your datatype is wrong, change datatype for dataType.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.