Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery.post callback data is null

I am having an issue with ZEND, JQuery, PHP, and Javascript. I am very new to these languages, and I am just trying to work my way around them.

I have had jquery.post work in other cases, but I cannot get it to do 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");
}

A /admin/newusercallback.phtml file exists.

  <?php ?>

When run, the console has the following messages printed to it:

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 have 2 popup boxes appearing, which say Call Successful! and Null

The issue is that the second popup box should say "Test" instead of Null.

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

"Test"

(quotation marks inclusive)

My question is, why is the callback data for testJquery Null, when browing directly to the page is displaying the data "Test" correctly? Further to that, how can I fix it!

like image 950
Logan Bissonnette Avatar asked Nov 05 '12 23:11

Logan Bissonnette


3 Answers

Thats becouse your jQuery function asking for "json" format, and text "Test" is not json.

Solutions: 1. Remove "json" dataType on your testJquery() function:

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

2. Edit your AdminController.php file to encode array object

    public function newusercallbackAction(){
        echo json_encode(array("Test"));
    }
like image 179
Syuaa SE Avatar answered Nov 12 '22 20:11

Syuaa SE


It looks like your controller is only responding to HTML/TEXT. I don't know how to do it, but your controller should return JSON

like image 21
Rodrigo Dias Avatar answered Nov 12 '22 18:11

Rodrigo Dias


It will only work when response header "Content-Type" is valid json mime, which is application/json. and it also happens to shorthand version .getJSON

put this in your php before you output anything else

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

like image 26
W.T. Avatar answered Nov 12 '22 20:11

W.T.