Php ajax call for same php script response null
ajax, jquery, php
Solution
It's look like your response content is empty. You forgot an `echo`.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$jsonResponse=array('rstatus'=>1,'id'=>$_POST['id']);
header("Content-type: application/json");
echo json_encode($jsonResponse);
die();
}
If you want to response a json, you must put it in the response content. In Php, you just have to use `echo` to put something in the response content.
Problem
I am developing a single page script i.e. category.php for category management. - This script have an input button to invoke AJAX call. ``` <input type="button" id="btn" /> ``` Jquery code to bind click event and call ajax. I want json response. ``` $(document).ready(function(e) { $('#btn').click(function(e) { id=1; jQuery.ajax({ type: 'post', url: 'category.php', success: function(data) { if(data.rstatus==1){ alert(data.text); }else alert(data); }, data:{'id':id} }); }); }); ``` A php code to entertain AJAX call. ``` if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $jsonResponse=array('rstatus'=>1,'id'=>$_POST['id']); header("Content-type: application/json"); json_encode($jsonResponse); die(); } ``` Problem: This ajax call is unable to produce correct response in call back function, and cause error in firebug console. TypeError: data is null In FIREBUG Headers are as follow: `Response Headers` ``` > Cache-Control no-cache, must-revalidate Connection Keep-Alive > Content-Length 0 Content-Type application/json Date Tue, 26 Mar 2013 > 12:45:52 GMT Expires Mon, 26 Jul 1997 05:00:00 GMT > Keep-Alive timeout=5, max=98 Last-Modified Tue, 26 Mar 2013 > 12:45:52GMT Pragma no-cache Server Apache/2.4.3 (Win32) OpenSSL/1.0.1c > PHP/5.4.7 X-Powered-By PHP/5.4.7 ``` `Request Headers` ``` > > Accept */* Accept-Encoding gzip, deflate > > Accept-Language en-US,en;q=0.5 Content-Length 4 > > Content-Type application/x-www-form-urlencoded; charset=UTF-8 > > Cookie __gads=ID=39701a3d85dce702:T=1350383638:S=ALNI_MY_rHGVQ-qNxH4UGmbY_G-IuVcDkA; > > __utma=141011373.593047819.1350426838.1364292528.1364295112.314;PHPSESSID=1s73cho6ildjt80jtudt8nq0f5 Host abc.com Referer http://www.abc.com/category.php > > User-Agent Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 > > Firefox/19.0 X-Requested-With XMLHttpRequest ```