Custom Ajax & Rest API
About the feature
Example of Rest API usage
JavaScript code
async function makeRequest(postId, value) {
// 1. todo use '/wp-json/advanced_views/v1/layout/' for Layout,
// and put your Layout ID at the end
// 2. todo use '/wp-json/advanced_views/v1/card/' for Cards,
// and put your Post Selection ID at the end
await fetch('/wp-json/advanced_views/v1/{layout|post-selection}/{6630e2da1953e}', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// todo your arguments here
'postId': postId,
'value': 'value,
}),
}).then(response => response.json())
.then((response) => {
// todo process response, the variable already contains the parsed object
console.log('Request complete', response);
})
.catch(error => () => {
console.error('Request error:', error)
});
}PHP Controller code
Request Authentication
1. Create and pass nonce to the template (in controller.php)
2. Define nonce as a JS window variable (in Twig or Blade template)
3. Use nonce in the request headers (script.js)
Example of Ajax usage
script.js
Layout's controller.php
Post Selection's controller.php
Request Authentication
Last updated