JQuery.post callback data is null

I have a problem with ZEND, jQuery, PHP and Javascript. I am very new to these languages ​​and I am just trying to work with them.

I had jquery.post working in other cases, but I can't get her to make a simple call right now.

Phtml file (/admin/user.phtml)

function testJquery() { var url = "<?php echo $myHome2Url.'/admin/newusercallback/sessionid/'.$_SESSION['mySessionId'].'/lang/'.$_SESSION['language']?>"; console.log(url); $.post(url,{}, function(data) { window.alert("Call successful!"); window.alert(data); },"json"); 

}

PHP File: (AdminController.php)

 public function newusercallbackAction() { echo json_encode("Test"); } 

The file A / admin / newusercallback.phtml exists.

  <?php ?> 

When launched, the following messages are displayed on the console:

 POST https://dev.myurl.ca/admin/newusercallback/sessionid/0c1a5e41-ad0a-470d-9901-305464b48908/lang/ENG https://dev.myurl.ca/admin/newusercallback/sessionid/0c1a5e41-ad0a-470d-9901-305464b48908/lang/ENG GET https://dev.myurl.ca/admin/user/sessionid/0c1a5e41-ad0a-470d-9901-305464b48908/lang/ENG/report_id/0/ 

I got 2 pop-ups that say Call Successful! and null

The problem is that the second pop-up should indicate "Test" instead of Null.

If I look at the URL https://dev.myurl.ca/admin/newusercallback/sessionid/0c1a5e41-ad0a-470d-9901-305464b48908/lang/ENG , my browser displays a window with text

 "Test" 

(quotation marks inclusive)

My question is: why is the callback data for testJquery Null when the cast directly to the page displays the "Test" data correctly? In addition to this, how can I fix it!

+6
source share
3 answers

This means that your jQuery function requests the format "json" and the text "Test" is not json.

Solutions: 1. Remove the "json" dataType in the testJquery () function:

  function testJquery(){ $.post(url,{},function(data){ window.alert("Call successful!"); window.alert(data); }); } 

2. Edit the AdminController.php file to encode an array object

  public function newusercallbackAction(){ echo json_encode(array("Test")); } 
+2
source

It looks like your controller only responds to HTML / TEXT. I do not know how to do this, but your controller should return JSON

+1
source

It will only work when the "Content-Type" response header is valid json mime, which is equal to application/json . and it also has a shortened version of .getJSON

put this in your php before you output anything else

header ("Content-type: application / json; charset = utf-8");

+1
source

All Articles