Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 428
Steven Marks Avatar asked Oct 03 '13 09:10

Steven Marks


People also ask

How do I get AJAX response in JSON?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

How do I display JSON data in HTML table using jQuery AJAX?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.

What does the JSON parse () method do when we initiate an AJAX request?

Description: Takes a well-formed JSON string and returns the resulting JavaScript value.

How can make AJAX call in jQuery?

The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.


1 Answers

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

like image 91
Sorter Avatar answered Oct 14 '22 07:10

Sorter