delight-im / PHP-Foundation

Writing modern PHP applications efficiently
MIT License
29 stars 7 forks source link

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data #8

Closed daebak74 closed 5 years ago

daebak74 commented 5 years ago

I just a simple test with Ajax request I try to login.

js:

$.ajax({        
type: "POST",
url: "/admin/login",
dataType: 'json',
data: { 
action : "login",
username : username,
password : password
}
}) ....

index

$app->post('/admin/login', ['\App\Controllers\Core\Login', 'postLogin']);

controller

$result['result_msg'] = 'test';
$app->setContentType('json');
echo json_encode($result);

in console

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Where I am in wrong ? :(

if the Request isXMLHttpRequest() $app->view .... template.ajax.twig else template.html.twig ?

Thanks.

daebak74 commented 5 years ago

Never in mind my mistake work perfect!

ocram commented 5 years ago

You probably had some other output before the JSON output.

By the way, you can certainly use Twig for any output format, not just for HTML. The extensions are just conventions, and could even be left out entirely, but .json.twig would make sense, for example. They also help with syntax highlighting in editors and IDEs. Often, however, you build non-HTML output dynamically in some data structure and just convert it to the output format directly.

When using Twig for something other than HTML, you have to disable (automatic) output escaping perhaps.