Check if Ajax Response is JSON Using Prototype JS

ajaxprototype-js

It is a simple question to all of our dear magento developer.

How can i check ajax response type is json or else using prototype js whenever request header is not defined as application/json

requestHeaders: {Accept: 'application/json'}

My prototype ajax request is:

new Ajax.Request(url,{
    method:'POST',
   parameters:params,
    onSuccess:function(transport){

    }.bind(this)
    });

Now i am trying to send different type of header response basic on my logic.

Condition:
if condition is match with rule then send json response using below code:

  public function testAction() {
      if(ConditionMATCh) {
                      $data = array('user_id' => 1, 'name'=> 'Amit' );
              $result=Mage::helper('marketplace/assignfollowup')->addonFollowerList($data);
              return $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
          }

Else render a layout below code:

 public function testAction() {
      if(ConditionMATCh) {
                      $data = array('user_id' => 1, 'name'=> 'Amit' );
              $result=Mage::helper('marketplace/assignfollowup')->addonFollowerList($data);
              return $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
          } else {
                                $this->loadLayout();
                                $this->renderLayout();
                                return;
      }
  }

My JavaScript ajax request cod is below

new Ajax.Request(url,{
    method:'POST',
    parameters:params,
    onSuccess:function(transport){
          if(responseISJson){

      // do someting
  }else{
      // do other
  }

    }.bind(this)
    });

Now try to do some logic basic of response type(Json/other) on above prototye ajax request example.

Question: How can i track that response Json or else

Best Answer

Find a function which is fulfill my requirement.

Function name: isJSON().

just add below two line code and get result

     var response = transport.responseText;
            if (response.isJSON()) {...

code is :

   new Ajax.Request(url,{
    method:'POST',
    parameters:params,
    onSuccess:function(transport){
    var response = transport.responseText;
    if (response.isJSON()) {
      //It is json reponse
      // do someting
  }else{
      // do other
  }

    }.bind(this)
    });