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

Ошибка обновления. Ответ не является допустимым ответом 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, так я заработаю много денег и больше не буду писать статьи).

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

  • Добрый день.
    Столкнулась с той же проблемой, что и некоторое кол-во пользователей пару месяцев назад, однако среди имеющихся в поиске постов ответа не нашла.

    Проблема:
    Open Server 5.2.2; WordPress 5.3.2.
    Чистая установка в новую папку + новая бд.
    Голый WordPress, тема стандартная TwentyTwenty.
    Предустановленные плагины не активировались и сразу удалены.
    Лишние темы удалены.
    Ничего в системе не менялось и не настраивалось, кроме одного: «Настройки -> Постоянные ссылки» переключены со стандартных на «Название записи».
    При попытке изменить или добавить пост или страницу появляется сообщение об ошибке:
    «Ошибка обновления. Сообщение об ошибке: Ответ не является допустимым ответом JSON.»

    «Здоровье сайта» пишет 2 проблемы — отсутствие https и «REST API выдал неожиданный результат».
    Rest APi не подключала и не отключала, напомню: сайт голый. Создан полчаса назад.

    В чем может быть проблема?

    UPD: переключение «Постоянных ссылок» обратно к стандартному варианту чинит проблему.
    Но такое решение, к сожалению, совсем не вариант.
    Т.е. проблему нужно искать в файлах самого WordPress’a… Но где?
    И почему она вообще возникает, ведь вид ссылок — это стандартная системная функция..?

    • Тема изменена 3 года, 3 месяца назад пользователем Avriel.
  • Today I got an issue in WordPress. When I try to create a new page and uploading a new image in the WordPress admin section, I try to find out the solution, but I didn’t get it… So after sanding an hour I got a solution…

    Error

    «Publishing failed. Error message: The response is not a valid JSON response.»

    Community's user avatar

    asked Nov 23, 2019 at 16:36

    Rawan-25's user avatar

    1

    Go to settings>permalinks. Select «Post name» and save.

    Try updating your posts/pages. If it doesnot work, try selecting another option in the settings>permalinks.

    answered Dec 23, 2019 at 5:37

    Tashi's user avatar

    TashiTashi

    4394 silver badges12 bronze badges

    1

    Right now, you can use the Classic Editor plugin for fixing this issue.

    The answer for the error is the editor I didn’t know, but there is a new editor issue. If you are getting the same issue, then please use the below plugin. For fixing these issues, I’m doing R&D on this issue. If I get an exit solution, then will I make an update soon…

    Peter Mortensen's user avatar

    answered Nov 23, 2019 at 16:36

    Rawan-25's user avatar

    Rawan-25Rawan-25

    1,7331 gold badge17 silver badges25 bronze badges

    2

    I had the same problem on a local dev environment and found the issue was due to rewrite permissions. Make sure your .htaccess file has the proper permission.

    sudo chmod 755 .htaccess
    

    After permissions are set, save your permalink settings. If the problem still exists, make sure mod_rewrite is enabled. The following will work for apache2 on Ubuntu.

    sudo a2enmod rewrite
    sudo systemctl apache2 restart
    

    If still not working, your apache config is probably too strict. The following should do the trick for apache2 on Ubuntu. Edit /etc/apache2/apache2.conf and look for the root directory block. It’s normally the one with /var/www like below. You will probably see AllowOverride None. Just change it to All like below for your local, but you probably want to do some research and be more secure on a production server.

    <Directory /var/www/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
    </Directory>

    After the change is made do another restart on apache and all should be good.

    sudo systemctl apache2 restart
    

    answered Feb 2, 2020 at 3:02

    sgaith's user avatar

    sgaithsgaith

    1111 silver badge2 bronze badges

    0

    Changing the permalink settings as mentioned previously fixed the problem for me. If you keep «Post name» as the permalink setting, then the .htaccess file needs to be writable by wordpress.

    Alternatively the below can be pasted at the bottom of .htaccess file. Mod_rewrite changes are executed from the bottom of the file first.

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index.php$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.php [L]
    </IfModule>
    

    answered Feb 6, 2020 at 2:11

    CdeoEm's user avatar

    CdeoEmCdeoEm

    1011 silver badge3 bronze badges

    Maybe you have a security issue with mixed content (HTTP and https URLs).
    Step-1
    1. 1. Check your WordPress URL. Go to Settings -> permalink then click plain and save a page. then remove error

    Step-2

    1. Check your WordPress URL. Go to Settings -> General
    2. Change WordPress Adress and Site Adress to https://

    This solved the problem for me

    Priyanka Saini's user avatar

    answered Jan 20, 2020 at 11:17

    NFpeter's user avatar

    NFpeterNFpeter

    5734 silver badges8 bronze badges

    1

    Go to /etc/nginx/sites-available/
    open default file —> sudo vi default or sudo nano default

    Add Below line to the location:

    Add the comment :
    #try_files $uri $uri/ =404;

    Add this line : try_files $uri $uri/ /index.php?$args;

    See the screenshot below described with red line :

    enter image description here

    answered Jul 28, 2020 at 17:52

    Vasu's user avatar

    VasuVasu

    5175 silver badges7 bronze badges

    Navigate to Settings > Permalinks. Select the permalink structure to Post name and save. Now try saving your post/page.

    Here I have shared the screen-shot for your reference.

    enter image description here

    The problem should have been resolved.

    Once your issue is resolved then you can select an old option in Permalinks if you want.

    Note: If you have already selected Post Name then you need to select other option for reset permalink.

    answered Aug 19, 2020 at 14:02

    Jagir bahesh's user avatar

    I just installed classic editor plugin and it sorted out the “The response is not a valid JSON response” problem.

    answered Jan 9, 2020 at 10:20

    Archie Kariuki's user avatar

    I had the same «not a valid JSON response» error when trying to publish my content. WordPress seems to do a JSON post when publishing a new post/page so I checked the network tab in my Developer Tools. If you check the «response» tab for this JSON call you might see some more details about this invalid JSON response.

    In my case (yours might be different) some deprecated debug message was outputted before the actual JSON data and messed up the response. After fixing the deprecated message publishing worked again.

    <br />
    <b>Deprecated</b>:  Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in <b>Unknown</b> on line <b>0</b><br />
    <br />
    <b>Warning</b>:  Cannot modify header information - headers already sent in <b>Unknown</b> on line <b>0</b><br />
    {__NORMAL_JSON_DATA_HERE__}

    answered Jan 17, 2020 at 1:31

    tookwebdev's user avatar

    tookwebdevtookwebdev

    512 silver badges2 bronze badges

    Now, here there are two server blocks, first one is running on port 80.
    for second server block there is a port 443 where you should implement the below code.

    server{
    #ssl configuration
    location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    # try_files $uri $uri/ =404; // comment this block
    try_files $uri $uri/ /index.php$is_args$args;
    }
    }
    Now exit and restart nginx server.

    enter image description here

    ~$ sudo service nginx restart

    you are done. enjoy.

    answered Nov 3, 2020 at 17:22

    Vasu's user avatar

    VasuVasu

    5175 silver badges7 bronze badges

    In My case, it was a Firewall issue. A ModSecurity firewall rule was triggered for the website. I contacted the hosting provider (NameCheap), they identified the issue and then whitelisted the triggered rule on the server. Then the problem was resolved.

    answered Sep 3, 2021 at 23:59

    Rifat Hossain's user avatar

    Looks like this still has not been fixed.

    A workaround that worked for me (posting in case it works for someone else too) — in my case I was using an HTML block which was causing the issue. What I did was to add a Paragraph block > Edit as HTML. It resolved the issue for now. It’s a shame that WP didn’t look into it yet, seems like it’s been happening for a while.

    answered Feb 27, 2020 at 8:33

    jade newport's user avatar

    I had this same error and the cause in my case was a shortcode used in the page and the function that defined the shortcode was using ‘echo’ to output the data rather than using ‘return’

    answered Mar 23, 2020 at 8:53

    Nat's user avatar

    NatNat

    6211 gold badge6 silver badges17 bronze badges

    I’d been getting the same error message when adding and/or updating pages, in addition to various other random errors. I was getting the errors on both my local development server and my webhost. When changing to one of the default themes (e.g. twenty nineteen), the errors would go away. For me, the problem turned out to be in my page template files. I’d noticed that when choosing a template for a newly created page, I’d have multiple choices with the same name.

    I have several page template files (e.g. about-page.php, contact-page.php, services-page.php, etc.). When creating these files, since most of these pages were similar, I would just copy/paste from an existing file to make a new xxxx-page.php file. However, in some of those copied files (not all), I’d forgotten to modify the ‘Template Name’ (at the top of the file).

    After I’d gone through and made sure all of my template files had unique names, the JSON error went away. All of my other errors disappeared as well. I’m using WordPress 5.4.

    answered Apr 19, 2020 at 19:25

    rebrink's user avatar

    My issue was .htaccess related. I got the hint from LucasBr’s comment about a «.htaccess configuration problem». Since I had copied the site to my local dev environment. I needed to update the custom mod_rewrite settings to match my setup.

    The important lines were:

    RewriteBase /
    

    and

    RewriteRule . /index.php [L]
    

    They had previously been set to access a sub-directory site.

    answered May 13, 2020 at 14:19

    KalenGi's user avatar

    KalenGiKalenGi

    1,7564 gold badges25 silver badges40 bronze badges

    I have some echo in some of my custom plugins, so this was also causing this issue.

    answered Jan 17, 2021 at 9:15

    Amit Dave's user avatar

    Amit DaveAmit Dave

    5565 silver badges12 bronze badges

    I had the persisting issues. Before I could find the solution, I replaced PHP 8, as this was custom PHP Installation.

    But nothing worked.

    The solution was found during Drupal Installation.

    1. Enable Opcache(only for Drupal though)
    2. Allow Mod rewrite, Allow all(in my httpd.ini file there were three occurrences of Mod Rewrite,

    And they were changed to None to All again none all this was small letter, and final one None to All

    Restart httpd with httpd -k restart (CMD as Administrator)

    This resolved.

    answered Feb 19, 2021 at 6:46

    Susobhan Das's user avatar

    I encountered the same kind of problem for a different reason with one of my client and never saw it as a potential solution.

    If you enabled a W.A.F (like cloudflare or similar), one of the side effects can be this error, so be sure to disable to disable you waf if none of the other solutions are working.

    answered Apr 22, 2021 at 12:41

    Gnusam's user avatar

    GnusamGnusam

    381 silver badge6 bronze badges

    If you use mod security 3 with WordPress, you might get this message:

    Publishing failed. The response is not a valid JSON response.

    To remove it, you would need to add this rule to your exclusions file called

    REQUEST-900-EXCLUSION-RULES-BEFORE-CRS
    

    as follows:

    # Remove Publishing failed. The response is not a valid JSON response.
    SecRule REQUEST_HEADERS:Host "example.com" 
         "id:1025,
         phase:2,
         pass,
         nolog,
         chain"
         SecRule REQUEST_URI "@beginsWith /wp-json/wp/v2" 
             " ctl:ruleRemoveById=933210,ctl:ruleRemoveById=949110"
    

    You might need to change the rule id and change example.com to your domain name. After that, do this:

    sudo nginx -t
    

    if no problems were detected, restart nginx:

    sudo service nginx restart
    sudo systemctl restart nginx
    

    answered Nov 28, 2021 at 4:16

    Abe's user avatar

    AbeAbe

    3912 silver badges17 bronze badges

    I had the same problem, also in my case, I couldn’t download and uninstall plugins. and in the page source there were:
    <head> </head> tag before <!DOCTYPE html> in your case it could be just whitespace. the problem was in the function.php file, at the end of the file I had php closing tag ?>. after removing it everything works fine.

    answered Mar 11 at 13:04

    Lasha Lomidze's user avatar

    This is a permalinks error.

    Do these steps to fix it (depending upon the cause in your scenario) as explained here: https://wordpress786.com/updating-failed-error-message-the-response-is-not-a-valid-json-response/ :

    1. go to settings > permalinks and save them once again
    2. if you’re on nginx, go to site nginx conf file and make sure that it contains the rules for wordpress permalinks (usual nginx configurationn for wordpress, ask me if confused)
    3. restart nginx if you make any edits to conf file

    answered Feb 9, 2020 at 11:46

    Nabeel Khan's user avatar

    Nabeel KhanNabeel Khan

    3,6852 gold badges24 silver badges36 bronze badges

    If you face issue on image upload follow this: https://navinrao.com/the-response-is-not-a-valid-json-response/

    I was getting this issue while updating normal text too.
    The issue I face was due to having javascript:void(0) keyword inside my link () .

    Please be sure if your content has keyword containing javascript
    before updating.

    <a href="javascript:void(0)" target="_blank" title="Linkedin" class="social-color-3"><i class="fa fa-linkedin" aria-hidden="true"></i></a>
    

    After I remove javascript:void(0) ; it works fine.
    Have a nice time :)

    answered Mar 16, 2020 at 2:15

    silwalprabin's user avatar

    Try removing any redirects to the WordPress site including subdomains.

    answered Mar 23, 2020 at 1:45

    Manzini Lionel .T's user avatar

    Вы пытаетесь исправить недопустимую ошибку JSON в WordPress?

    Эта ошибка появляется при редактировании сообщений или страниц WordPress на вашем веб-сайте. Вы увидите сообщение о том, что «Ответ не является допустимым ответом JSON», и обновление этой страницы завершится ошибкой.

    В этой статье мы покажем вам, как легко исправить недопустимую ошибку JSON в WordPress. Мы также поговорим о том, почему возникает эта ошибка и как ее избежать в будущем.

    Что вызывает ошибку » Недопустимый ответ JSON’ в WordPress?

    Неспособность получить ожидаемый ответ от сервера приводит к ошибке «Недопустимый ответ JSON» в WordPress.

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

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

    Эта ошибка может возникнуть по ряду причин. Однако наиболее вероятной причиной этого являются неправильные настройки URL-адресов в WordPress или неработающие постоянные ссылки.

    Тем не менее, давайте посмотрим, как легко исправить недопустимую ошибку JSON в WordPress.

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

    1. Проверьте URL-адреса WordPress в настройках

    Во-первых, вам нужно убедиться, что ваш адрес WordPress и настройки адреса сайта верны.

    Просто перейдите на страницу » Общие настройки». Отсюда вам нужно просмотреть поля Адрес WordPress (URL) и Адрес сайта (URL).

    Для большинства веб-сайтов этот параметр должен иметь один и тот же URL-адрес в обоих полях.

    Однако в редких случаях некоторые пользователи могли предоставить WordPress свой собственный каталог и обслуживать веб-сайт по другому адресу. В этом случае у них могут быть разные URL-адреса здесь.

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

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

    Если вы все еще видите ошибку, продолжайте чтение.

    2. Исправьте Структуру Постоянных Ссылок WordPress

    WordPress поставляется с удобной для SEO структурой URL-адресов, которая позволяет вам использовать удобочитаемые URL-адреса для ваших постов и страниц.

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

    Чтобы исправить это, вам нужно просто посетить страницу » Настройки » постоянных ссылок. Отсюда вам необходимо внимательно изучить параметры постоянной ссылки.

    Если вы не уверены, используете ли вы правильные настройки, просто выберите один из доступных форматов по умолчанию.

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

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

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

    Файл .htaccess в WordPress используется в качестве файла конфигурации для управления URL-адресами, удобными для SEO (постоянные ссылки).

    Обычно WordPress может автоматически восстанавливать и обновлять его. Вы также можете запустить это обновление, просто нажав на кнопку » Сохранить изменения «в нижней части страницы «Постоянные ссылки«.

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

    Чтобы исправить это, вам необходимо подключиться к своему веб-сайту с помощью FTP-клиента или приложения файлового менеджера на панели управления учетной записью хостинга WordPress.

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

    Совет: Не удается найти файл .htaccess? Смотрите эту краткую статью о том, как найти файл .htaccess.

    После этого вам необходимо отредактировать файл .htaccess с помощью FTP-клиента или приложения файлового менеджера.

    Как только файл откроется, вам нужно удалить весь код внутри него и заменить его следующим кодом:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    # BEGIN WordPress

    RewriteEngine On

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteBase /

    RewriteRule ^index.php$ - [L]

    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule . /index.php [L]

    # END WordPress

    Не забудьте сохранить изменения и загрузить файл обратно на свой веб-сайт.

    Теперь вы можете посетить свой веб-сайт, отредактировать и опубликовать или опубликовать страницу, чтобы узнать, сможете ли вы воспроизвести недопустимую ошибку ответа JSON.

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

    4. Просмотрите Журнал Отладки Rest API

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

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

    Вы можете увидеть подробную информацию об этой ошибке в инструменте работоспособности сайта WordPress. Посетите страницу работоспособности сайта » Инструменты».

    Отсюда вы можете увидеть проблему с надписью «API REST обнаружил неожиданный результат».

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

    Если это не даст никакой подсказки, то вы можете перейти к следующему шагу.

    5. Деактивируйте Все Плагины WordPress

    Иногда плагины WordPress могут конфликтовать друг с другом или ядром WordPress. Это может привести к неожиданному поведению и может быть потенциальной причиной недопустимой ошибки JSON.

    Просто перейдите на страницу плагинов » Установленные плагины«. Отсюда выберите все ваши плагины WordPress, а затем выберите «Деактивировать’ в раскрывающемся меню «Массовые действия». Теперь нажмите кнопку Применить, чтобы продолжить.

    WordPress теперь деактивирует все установленные вами плагины.

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

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

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

    6. Временно переключитесь на Классический редактор

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

    Эта более старая версия редактора WordPress использует более простой текстовый редактор и не сильно полагается на REST API для получения ответа JSON.

    Чтобы использовать его, вам необходимо установить и активировать плагин Classic Editor. Для получения более подробной информации ознакомьтесь с нашим пошаговым руководством по установке плагина WordPress.

    Плагин работает из коробки, и он отключит редактор Гутенберга при активации.

    Теперь вы можете продолжить работу над своим сайтом и вернуться к устранению неполадок позже.

    7. Дальнейшее Устранение Неполадок

    Ряд вещей может заблокировать API REST WordPress или заставить его вернуть недопустимый ответ JSON. Выше мы рассмотрели наиболее вероятных виновников, но если это не помогло вам, то вот еще несколько шагов, которые вы можете предпринять.

    Переход на тему WordPress по умолчанию

    Иногда конфликт между вашей темой WordPress и плагином или ядром WordPress может привести к неожиданному поведению.

    Вы можете проверить это, просто переключившись на тему WordPress по умолчанию, такую как TwentyTwentyOne или Twenty-Twenty.

    Временно отключите Брандмауэр веб-приложений

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

    Самый простой способ выяснить это-временно отключить плагин или службу брандмауэра WordPress.

    Некоторые брандмауэры WordPress на уровне приложений можно отключить, просто отключив плагин. Для брандмауэров уровня DNS, таких как Sucuri и Cloudflare, вы можете отключить их на панели мониторинга своей учетной записи.

    Включите отладку в WordPress

    WordPress поставляется со встроенной функцией, которая позволяет вам вести журнал ошибок. Однако по умолчанию он не включен.

    Чтобы включить его, вам нужно добавить следующий код в свой wp-config.php файл:

    1

    2

    define( 'WP_DEBUG', true );

    define( 'WP_DEBUG_LOG', true );

    После этого WordPress будет вести журнал всех ошибок при отладке.файл журнала, расположенный в папке /wp-содержимое/. Вы можете получить доступ к этому файлу с помощью FTP-клиента.

    Журнал ошибок может дать вам представление о том, что может быть причиной недопустимой ошибки JSON на вашем веб-сайте. Для получения более подробной информации см. наше руководство по настройке журналов ошибок WordPress и их использованию для отладки ошибок.

    Обратитесь За Помощью К Эксперту

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

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

    Мы надеемся, что эта статья помогла вам узнать, как исправить недопустимую ошибку JSON в WordPress. 

    You are creating content in the WordPress editor but the document fails to update. In fact, you see an error message that says “Updating failed. Error message: The response is not a valid JSON response.” Before you panic, let me assure you that this error can be resolved easily so you don’t lose your hard work.

    This error is one of the common WordPress errors that users encounter on their sites.

    Why does “the response is not a valid JSON response” error occur?

    There could be multiple reasons why this error occurs. This post delves into each reason and offers multiple solutions to solve the problem.

    1. Reset the permalinks

    Before you try anything else, you should try resetting your permalinks to resolve the invalid JSON response error. Navigate to Settings > Permalinks in your WordPress dashboard. Then ensure that the correct permalink setting is selected and click the Save Changes button.

    Now try updating a page. The error should be fixed but if it still occurs, try out the solutions below.

    2. Disable the Block editor and switch back to Classic editor

    WordPress classic editor
    Old is still Gold in WordPress

    The error “Updating failed. Error message: The response is not a valid JSON response.” is overwhelmingly seen in the new Block editor called Gutenberg.

    The easiest way to resolve the updating error is by disabling Gutenberg and switching back to the Classic editor. As they say, old is Gold.

    You can install the Classic Editor plugin for this. Once you have activated the plugin, try to save your posts. You should not see any error message now.

    But what if you still want to use the block editor?

    Nice question. It could be that reverting to the classic editor is not an option for you. In that case, you should follow what we are doing on PassionWP. With the classic editor plugin installed and activated, navigate to Settings>Writing.

    Now select the Classic Editor as the “default editor for all users” option, save your changes, and clear your website cache. Right after this, select the Block Editor as the default editor and again save the changes.

    Now try editing an existing post or create a new post with the block editor. You should not encounter the JSON response error. However, it could be that the editor fails to automatically save your changes.

    In this event, press Ctrl + S (Cmd + S for Mac) to manually save your changes. This solution works for us and we are using the block editor without encountering the JSON response error.

    WordPress Error Fixing Service

    3. Mixed content error due to the use of SSL certificate

    Another common reason for this error is the use of a secure socket layer (SSL) certificate (HTTPS) on your WordPress site. Using an SSL certificate can result in some content being delivered non-securely on HTTP protocol even while the rest of the content is delivered in a secure manner over HTTPS protocol.

    This results in a mixed content error in which both https and https content is transmitted at the same time to the web browser, usually Google Chrome.

    How to solve the Mixed Content Error in WordPress?

    We investigated the mixed content error and noticed that it is linked to the use of the Really Simple SSL plugin that is used by over 3 million WordPress users to configure HTTPS on their websites.

    To resolve the “the response is not a valid JSON response” or mixed content error, navigate to Settings > SSL. This will open the plugin’s settings. Now click on the Settings tab.

    You should do the following two things here:

    1. Ensure that the “Mixed content fixer” option is turned on. This prevents mixed content problems on your website that we discussed above.
    2. Next, you should turn on the “Use an alternative method to fix the mixed content” option. This will ensure that “the response is not a valid JSON response” error does not erupt abruptly while editing.
    How to fix the response is not a valid JSON response error in WordPress
    Really Simple SSL settings

    After saving the changes, go back to the post you were working on and try saving your post or page. You should no longer experience the response is not a valid JSON response error.

    ad

    4. Plugin conflict

    The more plugins you use on your WordPress site, the higher the chances of conflict between plugins. Some of these conflicts can result in invalid JSON response errors as well.

    I have witnessed this issue on websites running a high number of plugins, say more than 40. But it’s not just the number of plugins that matter. Rather, some plugin files might be causing the JSON bug on your website.

    For instance, on a client’s site, the Yoast SEO plugin was causing the JSON response error.

    So, in order to rule out any plugin conflict, you should deactivate all the plugins on your website. If required, use the Health Check and Troubleshooting plugin to deactivate the plugins in the backend while the front end remains the same for your visitors.

    If the JSON response error disappears when you deactivate all the plugins means that one of the plugins was causing the error. Now, you should activate the plugins one by one. If the error recurs on activating a particular plugin implies that this plugin was the culprit.

    5. WordPress REST API conflict

    The WordPress admin backend uses the REST API to communicate with the server. If there is any conflict with this API, WordPress won’t be able to connect with the server and will instead display the JSON response error.

    In order to identify if the REST API problem is indeed causing the problem, try editing one of your posts and saving it. Once the invalid JSON error is displayed, right-click the mouse button and then click Inspect to open Chrome’s dev tools.

    Now under the Console tab, check whether any REST API error is displayed. If it is, then the REST API conflict is indeed the cause.

    The best solution to this is to contact your web host since REST API errors are mostly caused at the server level. If you’re using a cache plugin like LiteSpeed Cache, you should disable the setting to cache the REST API and try saving the post again.

    Finding this solution required considerable effort and time. Consider rewarding me with a coffee!

    6. Alternative solutions to the response is not a valid JSON response error

    Deactivate all the plugins on your site and edit the content normally. If you’re using the Really Simple SSL plugin then deactivate this plugin first. Subsequently, try saving the document. If you are able to save it without facing any errors, re-activate the plugins one by one to check which plugin was causing the error.

    There is another solution you can try to fix the response is not a valid JSON response error in WordPress.

    Navigate to Settings > Permalinks. Change the permalink structure from post-name or the current structure to Plain i.e. https://yoursite.com/?p=123. Now try saving your post/page. The problem should have been resolved.

    Fix the response is not a valid json response error by changing the permalink
    WordPress permalinks settings

    But try this solution if all other methods fail as changing the permalinks will result in huge SEO issues on a live website and you will also need to add multiple redirects.

    We discussed 6 possible solutions to the response is not a valid JSON response error in WordPress. I hope one of these methods worked for you. If it did, let me know in the comments below. If it didn’t, post your specific problem so others can suggest different solutions.

    You can also check out our WordPress Error Fixing Service to fix the invalid JSON response error for you.

    Download the WordPress SEO eBook

    Go from WordPress SEO Zero to Hero in no time. Also receive 2 Bonus PDFs with this free eBook.

    Give it a try. You will thank yourself later.

    Понравилась статья? Поделить с друзьями:
  • Ошибка обновления нвидиа
  • Ошибка обновления модуля защищенного документооборота ошибка
  • Ошибка обновления ми бэнд 4
  • Ошибка обновления лаунчера майнкрафт
  • Ошибка обновления компонентов klava