jQuery AJAX Call to PHP Script with JSON Return

184,326

Solution 1

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

Solution 2

I recommend you use:

var returnedData = JSON.parse(data);

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

Solution 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);

Solution 4

Your datatype is wrong, change datatype for dataType.

Solution 5

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

header('Content-Type: application/json');
Share:
184,326
Steven Marks
Author by

Steven Marks

Updated on September 10, 2020

Comments

  • Steven Marks
    Steven Marks over 3 years

    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.