1

I'm able to send JSON Data to server through Ajax as i can see it in params of My Browser Developer Tool => Network but i get No Response Even if try to Print $_REQUEST, $_POST I get just the Cookie Value but not data which I have send

I'm Following From MDN https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

Here what I've tried, I'm trying to send data to server without jQuery Ajax method

After I do this on Server side

echo json_encode($_REQUEST['msgData']);

I get


Notice: Undefined index: msgData in /path/to/url/ABC/controller/msgNotify.php on line 24
null

jQuery(document).ready(function(){
    jQuery('#msgNotify').on('click',function(){
        alert("He");
        var data={};
        data['info']='msgNotify';
        data['username']=username;

        var msgData={'msgData':data};
        makeRequest(msgData,'../controller/msgNotify.php');
    });
});

  function makeRequest(data,url) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      var httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {}
      }
    }

    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }

    httpRequest.open('POST', url);
    httpRequest.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    httpRequest.onload = alertContents;
    httpRequest.send(JSON.stringify(data));
  }

  function alertContents() {
    try{
      if (httpRequest.status === 200) {
        alert(httpRequest.responseText);
      } else {
        alert('There was a problem with the request.');
      }
    }catch(e){
          alert('Caught Exception: ' + e.description);
    }
  }

SERVER SIDE "../controller/msgNotify.php"

echo json_encode($_REQUEST['msgData']);
exit;
hlh3406
  • 1,382
  • 5
  • 29
  • 46
user123
  • 205
  • 1
  • 2
  • 10
  • Try a var_dump($_REQUEST); on the server side and see what you are getting. – Sudhir Aug 05 '15 at 08:21
  • @Sudhir i tried var_dump($_REQUEST) and i get the output as array(1) { ["PHPSESSID"]=> string(26) "rt2kct8hv62rt2ugmvbnh7pfj2" } – user123 Aug 05 '15 at 08:28

2 Answers2

1

Without changing the way you are doing your POST (the JSON is in the body of the http request), you should read as follows

// extract from my Servlet class :

$content = file_get_contents('php://input');
$ary = json_decode($content , true); // prefer decoding to associative array

if ($content && !$ary) {
    self::logResponseStatus('Received malformed JSON', api_request_status::MALFORMED_REQUEST);
     return false;
 }

 $command = $ary['command'];
 $apiKey = $ary['apiKey'];

 // ... etc
YvesLeBorg
  • 9,070
  • 8
  • 35
  • 48
  • 1
    Thanks For help your code i working but can you please explain me what is this self::logResponseStatus('Received malformed JSON', api_request_status::MALFORMED_REQUEST); return false; – user123 Aug 05 '15 at 08:57
  • part of my codebase, just a copy-paste thingie : basically it logs the failed inbound connection (server side, i use log4php), and crafts the response body with useful information for the API caller. – YvesLeBorg Aug 05 '15 at 08:59
-1

You are sending your data as JSON string without key for getting this parametar in your request.

You could try with this:

httpRequest.send("msgData=" + JSON.stringify(data));

Your msgData will be key to getting your object {'msgData':data}. Since it's already a JSON string you don't need to use json_encode in php. If you want only to display "data" from received json you can use

$data = json_decode( $_REQUEST['msgData'] ) echo json_encode($data["msgData"]);

user2432612
  • 188
  • 1
  • 7
  • That won't work. The content-type says it is JSON not form encoded data. If you were to change the content type too, then it would be unsafe because you aren't escaping the JSON to fit into the form encoded data format. Even if you did that, then using JSON would be pointless as it serves more or less the same job as form encoding the data. Doing both is bloated. – Quentin Aug 05 '15 at 08:41
  • Uh yes you are right. I did't catch header for JSON. – user2432612 Aug 05 '15 at 09:11