[javascript] jQuery AJAX Call to PHP Script with JSON Return

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 question is related to javascript php jquery ajax json

The answer is


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

I recommend you use:

var returnedData = JSON.parse(data);

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


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

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

Your datatype is wrong, change datatype for dataType.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?