Error : “Updating failed: The response is not a valid JSON response” with custom shortcode

I am building a theme into which I have integrated data recovered by an external API.

I chose to create a plugin in which I put all my data processing, it allows me to generate a shortcode with which the user can interact, for example, to change how many items are displayed on the home page.

On that side, everything works, but my problem is with the Gutenberg editor ; when I add my shortcode to the page, and I want to save it, the following error message appears :

Updating failed: The response is not a valid JSON response.

However, the changes are saved correctly.

This message is worrying for users because :

  • At the moment of leaving, the web browser displays a JavaScript alert
    which says that the modifications will be lost (but this is false)
  • And each time we come back on the page edit, it ask us to recover the old versions of the page

About PHP functions of my plugin, there are some whose purpose is to return HTML and display it.
I first thought the problem was coming from here, because we are on the admin side, no need to execute anything, so I tried to put my function calls in a condition that verifies that we are not on an admin page :

if(!is_admin()) {
        myFunctionDisplayHTML();
    }

But I still get this error message.
Do you have any idea how to fix this problem ? Thank you in advance for your help !

My WordPress version is 5.6.2, PHP version 7.4.1 and my website runs in local environment.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Problem solved, I replaced all function calls that return HTML with :

ob_start();
myFunctionDisplayHTML();  
return ob_get_clean();

And the JSON response is valid.

Thanks @phatskat, you got me on the right way 🙂
Solution find here


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x