Ошибка обновления ответ не является допустимым ответом json wordpress

Возникла ошибка "Ответ не является допустимым ответом JSON" при обновлении или публикации записи в WordPress? Предлагаем 6 способов ее решения!

Ошибка обновления. Ответ не является допустимым ответом JSON

Обновление не удалось. Ответ не является допустимым ответом JSON. Как оказалось, с такой ошибкой сталкиваются многие вебмастеры при обновлении или публикации записей в WordPress.

С ней же столкнулся и я при переносе сайта своего клиента с хостинга Beget на Namecheap. Кстати, консоль у меня была на английском языке, и эта ошибка звучала так: Updating failed. The response is not a valid JSON response.

В этом материале я расскажу о всех возможных способах решить эту проблему, и какой помог лично мне.

Навигация по статье

Почему возникает эта ошибка?

Причин возникновения этой ошибки множество, но самая распространенная — отключение событий REST API. Но мы не будем останавливаться только на ней и рассмотрим все возможные способы решения этой проблемы.

Кстати, так выглядит сама ошибка обновления, возникающая при публикации или обновлении записи в WordPress.

Ошибка обновления WordPress

Как я решил эту проблему? Изначально я создавал сайт на хостинге Beget, после завершения работы требовалось выгрузить сайт на хостинг Namecheap. И сразу после публикации сайта я обнаружил, что больше могу обновлять или создавать новые записи/страницы. Особо никаких действий предпринимать мне не хотелось, поэтому я просто написал в техподдержку, и там решили мою проблему.

Если же техподдержка вашего хостинга не очень отзывчивая, то я рекомендую перейти на Beget и обязательно указать мой код партнера 1486766 при регистрации! 😀

А если серьезно, то попробуйте каждый из описанных ниже методов, и один из них вам наверняка поможет!

Способ 1. Обновите постоянные ссылки

Перейдите в консоль вашего сайта, затем в Настройки и найдите там пункт Постоянные ссылки.

Обновление постоянных ссылок

Здесь вам требуется просто нажать на кнопку Обновить. После этого можно проверить изменения.

Способ 2. Установка классического редактора WordPress

Далеко не самый идеальный способ решения проблемы, потому что вам придется отказаться от удобного современного блочного редактора и начать пользоваться его давно устаревшей версией.

Плагин Classic Editor WordPress

Скачайте плагин Классический редактор с официального репозитория WordPress. Затем перейдите в НастройкиНаписание. Здесь вам нужно найти параметр Классический редактор для всех пользователей и выбрать значение Для всех.

Можно проверить изменения. Если не помогло, переходим к следующему способу!

Способ 3. Отсутствие SSL сертификата или его некорректная настройка

Зачастую многие регистраторы и хостинг-провайдеры предлагают слишком дорогие SSL-сертификаты, цена на которые порой превышает 5 000 рублей за год. Далеко не все готовы платить столько денег и ищут возможность подключить бесплатный SSL-сертификат.

Зачастую эти попытки заканчиваются неудачами, некорректными настройками сайта, что приводит к ряду ошибок.

Если вы новичок, то крайне рекомендую использовать хостинг Beget в своей работе. Он не только предоставляет бесплатный пробный период на 30 дней для любого тарифа, но и выдает бесплатные рабочие SSL-сертификаты. Я уже как-то писал обзор на хостинг Beget, рекомендую к прочтению!

Способ 4. Устранение ошибки смешанного содержимого

Данное решение поможет, если ошибка возникла после подключения SSL-сертификата. Для начала перейдите в раздел настроек вашего сайта и проверьте, чтобы URL WordPress Address (Адрес WordPress) и URL Site Address (Адрес сайта) начинались с протокола безопасного соединения https.

Адрес WordPress и адрес сайта

Затем перейдите в раздел плагинов, скачайте и установите Really Simple SSL. После активации плагина появится уведомление Almost Ready to migrate SSL. Нажмите на синюю кнопку Activate SSL.

Плагин Really Simple SSL WordPress

Затем идем в Настройки, находим раздел SSL. Проконтролируйте, чтобы первые три пункта (Mixed content fixer, Enable WordPress 301 Redirection to SSL, Enable 301 .htaccess redirect) были активны. По окончанию настройки проверяем изменения.

Способ 5. Проверка тем и плагинов

Если ошибка «Обновление не удалось. Ответ не является допустимым ответом JSON» появилась после установки какой-то темы или плагина, то не сложно догадаться, в чем может быть причина ее возникновения.

Попробуйте переключиться на другую тему и проверить изменения. Затем отключите все плагины и снова проверьте изменения. Если же проблема решена, то остается только выяснить, какой из плагинов вызывает эту ошибку. Включайте их по очереди и проверяйте, появилась ли снова эта проблема.

Способ 6. Удостоверьтесь, что вы не отключили Rest API и wp-json

В самом начале этого материала я сказал, что это одна из самых частых причин возникновения ошибки обновления записей и страниц.

Перейдите в редактор вашей темы и найдите файл functions.php. А теперь внимательно изучите его содержимое. Если проблема кроется в отключении REST API и wp-json вы найдете примерно следующее:

// Отключаем сам REST API
add_filter('rest_enabled', '__return_false');

// Отключаем фильтры REST API
remove_action( 'xmlrpc_rsd_apis',            'rest_output_rsd' );
remove_action( 'wp_head',                    'rest_output_link_wp_head', 10, 0 );
remove_action( 'template_redirect',          'rest_output_link_header', 11, 0 );
remove_action( 'auth_cookie_malformed',      'rest_cookie_collect_status' );
remove_action( 'auth_cookie_expired',        'rest_cookie_collect_status' );
remove_action( 'auth_cookie_bad_username',   'rest_cookie_collect_status' );
remove_action( 'auth_cookie_bad_hash',       'rest_cookie_collect_status' );
remove_action( 'auth_cookie_valid',          'rest_cookie_collect_status' );
remove_filter( 'rest_authentication_errors', 'rest_cookie_check_errors', 100 );

// Отключаем события REST API
remove_action( 'init',          'rest_api_init' );
remove_action( 'rest_api_init', 'rest_api_default_filters', 10, 1 );
remove_action( 'parse_request', 'rest_api_loaded' );

// Отключаем Embeds связанные с REST API
remove_action( 'rest_api_init',          'wp_oembed_register_route'              );
remove_filter( 'rest_pre_serve_request', '_oembed_rest_pre_serve_request', 10, 4 );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
// Отключаем wp-json
add_filter('rest_enabled', '__return_false');
remove_action( 'xmlrpc_rsd_apis', 'rest_output_rsd' );
remove_action( 'wp_head', 'rest_output_link_wp_head', 10, 0 );
remove_action( 'template_redirect', 'rest_output_link_header', 11, 0 );
remove_action( 'auth_cookie_malformed', 'rest_cookie_collect_status' );
remove_action( 'auth_cookie_expired', 'rest_cookie_collect_status' );
remove_action( 'auth_cookie_bad_username', 'rest_cookie_collect_status' );
remove_action( 'auth_cookie_bad_hash', 'rest_cookie_collect_status' );
remove_action( 'auth_cookie_valid', 'rest_cookie_collect_status' );
remove_filter( 'rest_authentication_errors', 'rest_cookie_check_errors', 100 );
remove_action( 'init', 'rest_api_init' );
remove_action( 'rest_api_init', 'rest_api_default_filters', 10, 1 );
remove_action( 'parse_request', 'rest_api_loaded' );
remove_action( 'rest_api_init', 'wp_oembed_register_route' );
remove_filter( 'rest_pre_serve_request', '_oembed_rest_pre_serve_request', 10, 4 );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
remove_action( 'wp_head', 'wp_oembed_add_host_js' );

Если у вас есть похожий код, то удаляем его. Затем переходим в Настройки, находим раздел «Постоянные ссылки» и нажимаем «обновить».

Способ 7. Узнать ответ у техподдержки вашего хостинга

Иногда проблема может возникнуть не из-за вашего сайта, а некорректных настроек сервера. Попробуйте обратиться в техподдержку вашего хостинга с просьбой решить вашу проблему.

Кстати, а вам рассказать, у какого хостинга самая лучшая техподдержка? 😀 Конечно же у Beget! А вы думали, я какой-то другой хостинг здесь посоветую? (Не забывайте при регистрации указывать мой партнерский код 1486766, так я заработаю много денег и больше не буду писать статьи).

Вам понравился материал? Интересует разработка сайтов? Тогда обязательно подпишитесь на нашу группу ВКонтакте! Так вы всегда будете в курсе событий и никогда не пропустите новые материалы. А еще у нас есть беседа с активными участниками, где мы бесплатно помогаем новичкам с решением любых вопросов! 🙂

Приветствую вас на сайте Impuls-web!

Если ваш сайт работает на WordPress, то данная статья будет для вас очень полезна, так как в последних версиях данной CMS есть один небольшой недостаток, и если оставить его без внимания, то в дальнейшем это может привести к тому, что ваш сайт будет постепенно терять позиции в поисковой выдаче.

Данный недостаток связан с новым интерфейсом REST API, и заключается он в том, что на вашем сайте создается новая папка WP-JSON, в которой размещаются страницы с кодом.

На первый взгляд ничего страшного. Однако все эти страницы попадают в поисковую выдачу, и представляют собой вспомогательный код, не содержащий какого-то уникального контента. Как известно, поисковые системы как Яндекс, так и Google очень негативно относятся к подобным мусорным страницам. Причем, со временем этих страниц становится все больше и в конечном итоге, это может привести к тому, что поисковые системы начнут понижать ваш сайт в поисковой выдаче.

К счастью данная проблема решается довольно просто. Однако перед тем как перейти к ее решению, давайте сначала проверим, есть ли она на вашем сайте.

Для того, что бы понять, есть ли данная папка с ненужными страницами на вашем сайте или нет, достаточно к адресу вашего сайт через слэш приписать wp-json.

Например, так:

impuls-web.ru/wp-json

Если вы попадаете на страницу с непонятным кодом – это говорить о том, что на вашем сайте данная проблема есть. Именно вот такие вот страницы засоряют вашу поисковую выдачу.

страница wp-json

Помимо этого данный компонент так же может создавать дубли страниц на вашем сайте, которые тоже очень негативно воспринимаются поисковыми системами.

Актуальное решение

  1. 1. Открываем файл Robots.txt, который должен находится в папке с файлами вашего сайта на хостинге. Найти и открыть его можно при помощи FTP клиента или програмы Notepad++ или аналогов, а так же через файловый менеджер на Вашем хостинге.
  2. 2. Убедитесь в том, что у вас в этом файле есть такая строка

    Выглядеть это должно так:

    Закрываем wp-json в robots.txt

  3. 3. Если такой строки нет, ножно её добавитьт. С её помощью мы задаем поисковым системам запрет на индексировнаия всех файлов, расположенных по пути: домен сайта/wp-…
    Сюда будут входить файлы /wp-json/, /wp-includes, /wp-content/plugins
  4. 4. Если вы редактировали файл прямо на хостинге, то нужно его просто сохранить. Если вы загружали этот файл с хостинга, то нужно его сохранить, а потом выгрузить обратно на хостинг с заменой существующего файла.

Устаревшее решение

Обращаю ваше внимание на то, что данная статья и видео записывались почти 5 лет назад! За это время многое обновилось и изменилось. На сегодняшний день я не рекомендую вам использовать устаревшее решение, так как оно может привести к проблемам в работе некоторых плагинов! Используйте первый вариант решения через файл Robots.txt.

Тем не менее, я все же оставлю описание устаревшего метода, так как вы можете найти его на других сайтах и должны знать что это решение в современных реалиях не подходит!
Итак, для решения данной проблемы можно воспользоваться таким алгоритмом:

  1. 1.Вставить небольшой фрагмент кода в файл функций вашей темы functions.php. Открыть данный файл вы можете при помощи стандартного редактора WordPress, который находится в разделе «Внешний вид» => «Редактор».
  2. 2.Находим здесь файл functions.php он же «Функции темы».
  3. 3.Далее, мы переходим в самый конец данного файла. А дальше внимание, в идеале файл functions.php должен заканчиваться вот такими символами: ? >

    Если в вашем файле такие символы есть, то предложенный фрагмент кода вы будете вставлять перед этим вот символом:

    редактор кода WordPress

    Если же в вашем файле функций этих символов нет, то вы просто вставляете в самом конце файла functions.php. Специально дописывать эти символы здесь не нужно!

    Перед внесением любых правок в файл функций или любой другой файл темы, не забудьте сделать его резервную копию. То есть, просто, скопируйте данный фрагмент кода куда-нибудь себе в текстовый документ, что бы он у вас сохранился в качестве резервной копии.

  4. 4.Так же можно подключиться к сайту при помощи FTP-клиента, далее зайти в папку с доменом. Далее перейти в папку wp-content/themes/папка_с _названием_вашей_темы/ и здесь найти файл functions.php, а затем, точно так же спуститься в самый конец файла, и либо в самом конце, либо же перед символами ? > вставить данный фрагмент кода.

    Код будет выглядеть следующим образом:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    // Отключаем сам REST API

    add_filter(‘rest_enabled’, ‘__return_false’);

    // Отключаем фильтры REST API

    remove_action( ‘xmlrpc_rsd_apis’, ‘rest_output_rsd’ );

    remove_action( ‘wp_head’, ‘rest_output_link_wp_head’, 10, 0 );

    remove_action( ‘template_redirect’, ‘rest_output_link_header’, 11, 0 );

    remove_action( ‘auth_cookie_malformed’, ‘rest_cookie_collect_status’ );

    remove_action( ‘auth_cookie_expired’, ‘rest_cookie_collect_status’ );

    remove_action( ‘auth_cookie_bad_username’, ‘rest_cookie_collect_status’ );

    remove_action( ‘auth_cookie_bad_hash’, ‘rest_cookie_collect_status’ );

    remove_action( ‘auth_cookie_valid’, ‘rest_cookie_collect_status’ );

    remove_filter( ‘rest_authentication_errors’, ‘rest_cookie_check_errors’, 100 );

    // Отключаем события REST API

    remove_action( ‘init’, ‘rest_api_init’ );

    remove_action( ‘rest_api_init’, ‘rest_api_default_filters’, 10, 1 );

    remove_action( ‘parse_request’, ‘rest_api_loaded’ );

    // Отключаем Embeds связанные с REST API

    remove_action( ‘rest_api_init’, ‘wp_oembed_register_route’);

    remove_filter( ‘rest_pre_serve_request’, ‘_oembed_rest_pre_serve_request’, 10, 4 );

    remove_action( ‘wp_head’, ‘wp_oembed_add_discovery_links’ );

    В данном фрагменте кола мы отключаем компоненты REST API, которые приводят к данной прблеме.

    Вставляя код так же, обращайте внимание на то, что бы в конце данного файла у вас не стояли лишние пробелы и Enter-ы.

  5. 5.После вставки кода нажимаем на кнопку «Обновить файл».
  6. 6.Переходим на страницу сайта, обновляем ее, и теперь пробуем осуществить туже проверку, которую мы делали в самом начале. Ставим в адресной строке, после адреса сайта /wp-json.

Если вы всё сделали правильно, то вас должно перенаправить на страницу с ошибкой 404 «страница не найдена» или на главную страницу сайта. Здесь всё зависит от темы оформления.

Видеоинструкция

Как видите, это решение очень простое, но на самом деле, оно позволит уберечь ваш сайт от очень серьезных проблем в будущем. Потому, как уже есть много примеров, и среди моих знакомых в том числе, у которых сайты начали терять свои позиции именно из-за того, что у них в выдаче появлялось очень много мусорных страниц и дублей, связанных с элементом WP-JSON.

Если данная статья была для вас полезна – не забудьте написать комментарий и поделиться статьей в социальных сетях. А на этом у меня все, подписывайтесь на мою рассылку и мой канал на YouTube. До встречи в следующих статьях и видео!

С уважением Юлия Гусарь

Ошибка, об устранении которой мы расскажем в этой статье, заключается в следующем. При попытке создать и / или сохранить изменения в записи или странице в WordPress появляется сообщения: “Ошибка обновления. Сообщение об ошибке: Ответ не является допустимым ответом JSON”. Рассмотрим, как это устранить и как продолжить пользоваться сайтом и полноценно наполнять его контентом.

Ошибка обновления Вордпресс

Оглавление

  • 1 Перенастройка постоянных ссылок
  • 2 Восстановление файла .htaccess
  • 3 Выполнение обновления
  • 4 Установка классического редактора
  • 5 Деактивация всех плагинов и замена темы
  • 6 Восстановление из резервной копии

Перенастройка постоянных ссылок

Самое просто, что нужно сделать при появлении ошибки обновления WordPress – это перенастроить постоянные ссылки. Сделайте следующее:

  • Перейдите в раздел “Настройки”, подраздел “Постоянные ссылки”.
  • Запомните, как у вас сейчас настроены постоянные ссылки. Если сомневаетесь, что сможете запомнить, то сделайте скриншот этой страницы и сохраните.
  • Перенастройте постоянные ссылки, например, выбрав вариант “Простые”.
  • Сохраните изменения.
  • Перенастройте постоянные ссылки снова, сделав настройки как было до этого (как вы запомнили или заскриншотили).
  • Сохраните изменения.

После этого попробуйте создать или сохранить изменения в записи и проверить, пропала ли ошибка.

Восстановление файла .htaccess

.htaccess – это небольшой системный файл с несколькими строками кода, который управляет настройками сервера. Если в этом файле будут какие-то некорректные изменения, то это может привести к ошибкам на сайте или полной его неработоспособности. В WordPress ошибка обновления может возникать именно из-за некорректных записей в файле .htaccess.

На официальном сайте WordPress в разделе “Basic WP” находится оригинальный файл .htaccess, который в WordPress является по умолчанию. Скопируйте его содержимое и вставьте в .htaccess своего сайта. На своём сайте этот файл вы найдёте в корневой папке. Его можно открыть в редакторе файлового менеджера на хостинге.

После восстановления .htaccess на оригинальный, проверьте настройку постоянных ссылок в разделе “Настройки”, подразделе “Постоянные ссылки”. Они после этого могут сбиться и прийти к состоянию по умолчанию.

Возможно, у вас в корневой папке сайта файла .htaccess не будет. Например, если вы его случайно удалили. Тогда создайте его. Файл должен иметь строгое имя .htaccess (на самом деле это файл без имени, а после точки написано его расширение). И наполните файл кодом, который даётся на странице WordPress.

Выполнение обновления

Некоторые видят в WordPress ошибку обновления, когда сама CMS, плагины или тема не обновлены. Поэтому проверьте в разделе “Консоль”, подразделе “Оглавление”, выполнены ли все обновления. Если какие-то продукты требуют обновления, то сделайте их.

Установка классического редактора

В одном из обновлений WordPress разработчики сильно изменили редактор. Вместо привычного редактора с панелью управления в верхней части страницы, появился блочный редактор Guttenberg, которые представляет собой конструктор, позволяющий создать страницы любого вида. Guttenberg до сих пор обновляется и улучшается, наделяется новыми функциями.

Некоторые пользователи сразу отказались от редактора Guttenberg и решили остаться на классическом. Другие решили начать осваивать новое и пользуются новым редактором Guttenberg.

Иногда новый редактор Guttenberg вызывает проблемы и ошибки. В основном это связанно с несовместимостью с некоторыми плагинами и темами. Ошибка обновления WordPress с недопустимым ответом JSON также иногда связанна с этим. Поэтому рекомендуется установить классический редактор вместо Guttenberg. Для этого разработчики WordPress создали специальный плагин, который так и называется Classic Editor. Достаточно установить и активировать плагин и он сразу начинает работать. Редактор после активации плагина становится классическим. И теперь проверьте, пропала ли ошибка обновления WordPress.

Деактивация всех плагинов и замена темы

Это универсальный способ, который помогает диагностировать любую проблему на сайте, в том числе он поможет и при ошибке обновления в WordPress при создании или изменении записи / страницы. Сделайте следующее:

  1. Сначала деактивируйте все плагины в разделе “Плагины”. Проверьте, есть ли ошибка обновления. Если нет, то делайте шаг 2. Если ошибка осталась, то делайте шаг 4.
  2. Активируйте плагины по одному. После каждой активации плагина проверяйте наличие ошибки обновления.
  3. Тот плагин, после активации которого ошибка обновления возобновится, и есть виновный. Удалите его, замените на другой или измените его настройки.
  4. Если деактивация всех плагинов ошибку не устранила, то активируйте их снова.
  5. В разделе “Внешний вид” активируйте любую тему.
  6. Проверьте наличие ошибки обновления. Если она пропала, значит проблема была в теме. Замените тему на другую или измените её настройки. Если ошибка осталась, значит проблема в чём-то другом.

Восстановление из резервной копии

Подойдёт в тех случаях, когда в WordPress ошибка обновления появилась недавно. Тогда легче всего восстановить сайт из резервной копии, воспользовавшись бекапами на хостинге. Восстановите сайт на ту дату, когда проблемы ещё не было. При этом вы потеряете то, что было сделано с даты бекапа до настоящего времени – пропадёт не только причина ошибки обновления, но и полезные действия. Их придётся делать заново.

Fix the annoying WordPress error Publishing failed. The response is not a valid JSON response., Updating failed. The response is not a valid JSON response., or The response is not a valid JSON response.

You may have seen these errors when trying to publish or update your WordPress posts or pages. You may even have see this error when trying to upload an image in your WordPress website.

If you don’t deal with this error right away, you may lose all the changes that you have made for the past few hours (yes, we humans still go by hours without saving our work). This article is about rescuing you from that.

There are many reasons for why these errors can occur to your WordPress site. It can be related to your web server, .htaccess file, SSL certificate, a plugin, a theme, or for another reason. So depending on your specific scenario, a different solution may work for you.

Here, I have outlined all the methods that will help you solve this error. Be it Publishing failed. Error message: The response is not a valid JSON response., Updating failed. Error message: The response is not a valid JSON response., or just The response is not a valid JSON response.

Try using the following methods one by one and you should find the one that works for you. But in order not to lose your work progress, open your WordPress dashboard in a new window and try the solutions there.

Update Permalink

Warning: Updating permalink structure may change the URL of all your website pages and posts so the previous URLs to access your pages and posts won’t work. Your website’s SEO will also be affected by this. Therefore, if keeping your original URL is important, you may either not want to try this one or revert back to the original permalink structure as soon as the test is completed. But if your website is brand new, you don’t have to worry about it.

Change Permalink WordPress

The most common solution for publishing or updating failed the response is not a valid JSON response error is to update your permalink structure.

From your WordPress dashboard, go to Settings and then Permalinks. Then you can click on the Save Changes button to re-save or update the current permalink structure. Then check to see if the error is fixed.

If it doesn’t fix the error then you can go back to the permalink page and then select Plain from under the Custom Settings heading to change the permalink structure. Then click on Save Changes. Now check again to see if the error has been solved.

If the error hasn’t resolved, then you can try changing to all the other permalink structures and check if the error gets solved for any of them.

If this solution doesn’t work for you try the next one.

Use Classic Editor

In December 2018 WordPress updated their Classic Editor with the new Gutenberg/Block Editor. And since then many have faced this “Publishing failed. The response is not a valid JSON response.” and “Updating failed. The response is not a valid JSON response.” error.

Install Classic Editor Plugin WordPress

So, by going back to the Classic Editor many have been able to solve the error. In order to use Classic Editor, you will need to install and activate the Classic Editor plugin on your WordPress website.

However, if you use Classic Editor, this will replace the new Block Editor of WordPress with its old Classic Editor. This will change how you are used to editing your pages and posts. This may also affect the formatting and layout of your existing pages and posts that have been previously edited using the Block editor. So, you should safeguard your site first by changing a setting in the Classic Editor before you start using it.

Change Classic Editor Plugin Settings WordPress

So, to safeguard from affecting your existing pages, after you activate the Classic Editor plugin, go to Settings and then Writing from the WordPress dashboard. This will show you the settings for the Classic Editor plugin. From here, select “Yes” for the option “Allow users to switch editors”. Then click on Save Changes. This will let you use the Gutenberg/Block editor for your existing pages and posts so you won’t have to be concerned about losing existing work in case you want to edit any existing pages or posts on your site. This will also give you the option to edit any new pages or posts with either Block editor or the Classic editor.

Then try creating a new page or post using the Classic Editor and check if the JSON response error has been fixed.

From the plugin’s settings page, you can also select “Block Editor” as the option for “Default editor for all users” if you would like to make the Block Editor your default WordPress editor while using the Classic Editor plugin.

Using the Classic Editor might solve the JSON response error for you while updating or publishing your pages and posts. But if it doesn’t solve the error, then you can just deactivate the plugin and try out the next solution.

Configure SSL

Your website always needs to have TLS/SSL enabled or web browsers will show a warning message whenever someone tries to visit your website. That warning will make your site look dangerous so you will lose lots of your website visitors. That’s why properly setting up SSL certificate for your website is an important thing to do regardless of it solving “The response is not a valid JSON response” error.

In this part, I will tell you how you can properly set up your WordPress website to use SSL certificate which is also a very common solution to the JSON response error.

Use SSL Certificate

You can check if your site is using SSL certificate by looking at the URL of your website. After your website is loaded in a web browser, you can click on your website’s URL to see if the URL starts with HTTPS or HTTP. If it starts with HTTPS and if you see a padlock icon without a cross sign beside the URL, then your site is already configured with SSL certificate. So, you will just need to ensure that your website is using it properly.

with SSL vs without SSL

For instance, if your website is example.com then it will look like https://example.com and it will be marked with a padlock icon after it loads in your web browser if it is properly set up with SSL certificate.

However, having no padlock icon doesn’t always mean that an SSL certificate hasn’t been issued or your website. Instead, the reason might be that your website hasn’t been configured to automatically redirect all HTTP traffic to the HTTPS version of your website. To check if that is the case, change your website URL’s HTTP to HTTPS on the web browser and press enter. If the browser now shows a padlock icon beside the URL, then an SSL certificate has been issued for your site but it isn’t configured properly. So, we will need to configure it properly.

But if changing HTTP to HTTPS doesn’t work, then that it is probably because an SSL certificate hasn’t been issued for your website. And if that is the case, then you will first need to issue an SSL certificate for your website. If you are using cPanel, Plesk, DirectAdmin, CyberPanel or any other web hosting control panel, then you can easily issue an SSL certificate for your website from that web hosting control panel. See their guide on how to do that.

Additionally, the validity of SSL certificates expires after a certain period so you may also check if your SSL certificate is still valid. If it is not valid then you should first renew the SSL certificate to fix the SSL related issues. Once a valid SSL certificate is installed on your WordPress site, you can follow the next steps here to solve Publishing failed. The response is not a valid JSON response. or Updating failed. The response is not a valid JSON response. error.

Force HTTPS Redirect

Using your web hosting control panel like cPanel, Plesk, CyberPanel, etc., you can easily redirect all HTTP traffic to the HTTPS version of your website. The process of doing this will differ based on the hosting control panel you are using but you should easily find an option to do that in the SSL settings or in the domain settings option on the control panel. Look for settings that say something like force HTTPS redirect, redirect HTTP to HTTPS, and so on. See their guide on how to do that.

If you aren’t using a hosting control panel or if this doesn’t work for you then you can use the Really Simple SSL plugin to do that. I have described it further in the next step «Solve Mixed Content Error» which is also very important to solve SSL related issues for your WordPress site. So, even if this step solves the error, you should still follow the next step to solve the mixed content error on your website.

Solve Mixed Content Error

Your webpages will generally require linking multiple files like CSS, JS, images, etc. to display and function properly. And the links for these files may contain HTTP or HTTPS. If your website is configured to use HTTPS but if some of those links are using HTTP instead of HTTPS, there will be a mixed content error.

Install Really Simple SSL Plugin WordPress

To solve this problem you can install the Really Simple SSL plugin on your WordPress site. It will modify all links on your website to use HTTPS and therefore solve the mixed content error.

Really Simple SSL Plugin Configuration WordPress

After you install and activate the Really Simple SSL plugin, you will get a notification to activate SSL. So, click on the “Go ahead, activate SSL!” button on the notification. But if you don’t see the notification then from your WordPress dashboard, go to Settings and select SSL.

Then you will see the same button saying “Go ahead, activate SSL!”. Once you click on the button it will activate SSL and set HTTPS redirect for your website.

Really Simple SSL Plugin 301 Redirect Warning WordPress

Then it will give you will see a warning that says “WordPress 301 redirect enabled. We recommend to enable the 301 .htaccess redirect option on your specific setup”. Beside that warning, you will see a link saying “Enable”. Clicking on the link will take you to the Settings tab on the plugin. You can also go to the same page from your WordPress dashboard by going to Settings then SSL and then by selecting the Settings tab.

Really Simple SSL Plugin Settings WordPress

Here, you will see an option saying “Enable 301 .htaccess redirect”. Turn on the button beside that to activate HTTPS redirect from your .htaccess file. Before enabling the button you can also read the warning on how to regain access to your site in case of a redirect loop issue. Then after enabling the button click on Save.

WordPress Address General Settings

Also, from your WordPress dashboard, you can go to Settings then General. This will show you “WordPress Address (URL)” and “Site Address (URL)”. Make sure that these URLs are using HTTPS and not HTTP.

After doing this, check if the JSON response error has been fixed. If it doesn’t get fixed, you can also go to Settings > SSL > Settings and then turn on the button beside the “Use alternative method to fix mixed content” option and then save the change.

Now, check if the JSON response error has been fixed. If it hasn’t, then turn off the button beside the “Use alternative method to fix mixed content” option and save the change again then follow the next solution.

Check Themes and Plugins

If the previous methods don’t work for you then you can try to find out if it is any theme or plugin that is causing the problem. So, first, go to Appearance and then Themes from your WordPress dashboard. Then activate the default WordPress theme (as of now it is Twenty Twenty) and check if the error is fixed. If not, then revert back to your original theme.

The error may also cause by a plugin and in that case you can deactivate all the plugins on your website and then check again to see if the error occurs. If the error doesn’t occur then it is probably a plugin that is causing the issue. So, to find out which plugin is causing the problem, turn on one plugin at a time and check if the error occurs. And if the error occurs after enabling a certain plugin, then you will know that is the one causing the problem. So, you can just deactivate that plugin and activate the rest of the plugins that you need.

Restart OpenLiteSpeed

If you are using OpenLiteSpeed web server, then there is a very high chance that a restart will solve your problem.

OpenLiteSpeed is the open source or free version of the LiteSpeed Web Server (also known as LIteSpeed Enterprise). One of the major differences between LiteSpeed Enterprise and OpenLiteSpeed is that LiteSpeed Enterprise autodetects changes in .htaccess file and adjusts as necessary in realtime but OpenLiteSpeed can’t do that so it requires restarting for any changes in the .htaccess file to take place. And because WordPress uses the .htaccess file for many operations, those inactive .htaccess changes in the OpenLiteSpeed server may also cause The response is not a valid JSON response error. If you see this error after adding a new website on your OpenLiteSpeed server, this may also be the reason.

So, if you are using OpenLiteSpeed web server, a restart of the OpenLiteSpeed server can solve the error for you.

OpenLiteSpeed Status CyberPanel

If you are using CyberPanel web hosting panel with OpenLiteSpeed, then you can open your CyberPanel dashboard then go to Server Status then LiteSpeed Status. Then you can click on the Reboot LiteSpeed button to restart your OpenLIteSpeed server.

But if you are using a different web hosting panel or if you aren’t using any web hosting panel at all, then you will need to find out how to restart the OpenLIteSpeed server for your specific setup.

Update .htaccess

If none of the previous methods work then you can try configuring your .htaccess file.

In order to ensure that you can revert back to your original .htaccess file in case anything goes wrong, you can keep a backup of it by downloading it in your computer. If you know how to use an FTP client or the file manager of your web hosting control panel like cPanel, CyberPanel, etc., then you can download the .htaccess file from your website’s “public_html” folder.

Install Advanced File Manager Plugin WordPress

If you want an easy solution and want to do everything from WordPress dashboard then install and activate a file manager plugin like Advanced File Manager on your WordPress website.

Advanced File Manager htaccess Settings

Then from your WordPress dashboard, go to File Manager then Settings. From here put a checkmark beside the Display .htaccess? option then click on Save Changes.

Advanced File Manager htaccess WordPress

Now click on File Manager to see all the folders and files for your website. Here, in the “public_html” folder of your website, you will see the “.htaccess” file. Right-click on the file and click Download to keep a backup of it.

So, now you will be able to easily re-upload the original .htaccess file to the same location in case anything goes wrong.

Now, disable all the plugins on your WordPress site. Then delete the .htaccess file so that we can start from the beginning.

Now, go to Settings and then Permalinks from your WordPress dashboard. Then, make sure the permalink option of your choice is selected and then click on Save Changes. This will create a new .htaccess file for your website.

Now you need to check if “The response is not a valid JSON response” error is fixed or not.

If the error has been fixed, then you can turn on one plugin at a time and check if the error occurs again. If the error occurs after enabling a certain plugin then you can just deactivate that one and activate the other plugins as you need.

But if the error isn’t fixed after saving your permalink, then you can select the other permalink structures one after another and check if the JSON response has been fixed. Remember to change your permalink structure to the original one after your testing with different permalink structures is finished if you want to keep your previous URL structure.

But if that doesn’t fix “The response is not a valid JSON response” error, then you will need to follow the previously mentioned steps for Force HTTPS Redirect and Solve Mixed Content Error one more time. Do these steps while all your plugins are still deactivated.

This should solve the error for your website. And if the problem is solved, then activate all your plugins again one by one and check if any of them cause any problem. If the error doesn’t occur again, then the problem has been fixed but if the problem occurs after installing any specific plugin then just deactivate that plugin and activate the other ones.

After you activate the plugins, the .htaccess rules associated with the plugins should automatically be created to your new .htaccess file based on the existing plugin settings. So, you shouldn’t lose any configurations this way. But if something doesn’t work properly, then you can open both the .htaccess files in the editor or in a text document and compare the rules in both the .htaccess files. Then you can update the new .htaccess file with the changes you found. You can even delete the new .htaccess file and then upload the original one to go back to the previous state.

Check Site Health

From your WordPress dashboard, if you go to Tools and then select Site Health, then under the Status tab on that page, WordPress will show you any improvement recommendations that could help your website.

WordPress Site Health

An issue related to Rest API could also cause the JSON response error on your website. Moreover, if you find any issue there, solving the issue might also fix the JSON response error for your website.

Fix Image Upload Error

The Response Is Not A Valid JSON Response Image Upload Error WordPress

If you have tried the previous methods but “The response is not a valid JSON response” error still occurs when you try to upload images on your WordPress website, then you can follow the instructions in this section.

Use Media Library Instead of Direct Upload

If you are trying to upload images in an Image block using the Upload button, then you might get the JSON response error but surprisingly many people have found that if they first select Media Library then go to the Upload Files tab and then upload images from there then the error doesn’t occur.

Image Block WordPress

This might be a temporary workaround but it can be helpful if you are in the middle of writing a post or if any other methods don’t work for you.

Remove Invalid Characters

You may also get “The response is not a valid JSON response” error if you try to upload images with unsupported characters in the image name. So, you can rename your image using only English letters, numbers, and supported symbols like hyphens. Then you can upload that renamed image to see if the error has been fixed.

Use Default to GD plugin

Some people were also able to solve The response is not a valid JSON response error by using the Default to GD plugin. This plugin isn’t available on WordPress so you will need to download it from the Default to GD GitHub link.

Default to GD Plugin Download

To download the plugin click on the «Code” button on the page. Then select Download ZIP. This will download the plugin on your computer.

Default to GD Plugin Install

Then go to your WordPress dashboard then Plugins then Add New. Now click on Upload Plugin button then upload the plugin you just downloaded by clicking on the Choose File button. Then click on Install Now. After the installation is completed, click on Activate Plugin. It doesn’t require any set up so you can now check if the JSON response error occurs while uploading images to your WordPress site. And if the error still occurs, then you can just deactivate and then delete the plugin.

These methods for solving “The response is not a valid JSON response” error works for most people but if it doesn’t work for you then you may have a specific problem in your WordPress settings or in your web server setup. This error can also cause because of an issue related to the REST API, misconfiguration in NGINX server, security plugins like Wordfence or for security rules like WAF or Web Application Firewall. In these cases, you can look for solutions specific to those areas.

I hope one of these methods works for you and if works let me and others know which one worked for you. And if you found any other solution tell us in the comments section so that it can help others.

Понравилась статья? Поделить с друзьями:
  • Ошибка обновления конфигурации базы данных для одного ссылочного кода существует более одной таблицы
  • Ошибка обновления код ошибки 1017
  • Ошибка обновления код 106 ростелеком
  • Ошибка обновления клиента normacs
  • Ошибка обновления касперский что делать