Почему скрипт возвращает ошибку unexpected token in json at position 0?
Отправляю форму на php-обработчик через ajax таким образом:
function send(elem) {
$('.err').remove();
$.ajax({
url: '/index.php?route=common/home/send',
type: 'post',
data: $('.' + elem + ' input').serialize(),
dataType: 'json',
success: function (json) {
if (json['telephone']) {
$('#' + elem +' .btnsend').before('<div class="err">' + json['telephone'] + '</div>');
}
if (json['success']) {
$('#' + elem + ' .modal-body').html('<p>'+json['success'] +'</p>');
setTimeout(function () {
$('#' + elem + ' .close').trigger('click');
}, 2000);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
код на php:
public function send() {
$json = array();
if (isset($this->request->post['telephone']) && ((utf8_strlen($this->request->post['telephone']) > 17) || (utf8_strlen($this->request->post['telephone']) < 15))) {
$json['telephone'] = 'Укажите корректный телефон!';
}
if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$json) {
$subject = $this->request->post['type'].' '.$this->config->get('config_name');
$message = $this->request->post['type'] . "\n\n";
if(isset($this->request->post['telephone']) && $this->request->post['telephone']) {
$message .= 'Телефон: ' . $this->request->post['telephone'] . "\n\n";
}
if(isset($this->request->post['name']) && $this->request->post['name']) {
$message .= 'Имя: ' . $this->request->post['name'] . "\n\n";
}
$message .= $this->config->get('config_name');
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->hostname = $this->config->get('config_smtp_host');
$mail->username = $this->config->get('config_smtp_username');
$mail->password = $this->config->get('config_smtp_password');
$mail->port = $this->config->get('config_smtp_port');
$mail->timeout = $this->config->get('config_smtp_timeout');
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($this->config->get('config_email'));
$mail->setSender($this->config->get('config_name'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
$mail->send();
$emails = explode(',', $this->config->get('config_mail_alert'));
foreach ($emails as $email) {
if ($email && preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $email)) {
$mail->setTo(trim($email));
$mail->send();
}
}
$json['success'] = 'Ваша заявка успешно отправлена!';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
CMS использую opencart. Почему он выдает ошибку unexpected token in json at position 0 ? На php же делаю json_encode