Codeigniter with rest api
-
Hi , I need to insert posts using WP REST API from a codeigniter website , here is my controller:
public function tst() { require_once( 'c:/xampp/htdocs/2/wordpress/wp-load.php' ); $this->load->view('tst'); }
And this is the tst.php view content:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?><!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <?php // Register the script wp_register_script( 'wp-api', 'c:/xampp/htdocs/2/wordpress/wp-includes/js/wp-api.js' ); wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) ); // Enqueued script with localized data. wp_enqueue_script( 'wp-api' ); print_r( array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) ); ?> <button type="button" onclick="myFunction()">Retrieve</button> <script> function myFunction() { $.ajax( { url: wpApiSettings.root + 'wp/v2/posts/1', method: 'POST', beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, data:{ 'title' : 'Hello Moon' } } ).done( function ( response ) { alert( response ); } ); } </script> </body> </html>
This is the output for
print_r( array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
Array ( [root] => https://localhost/2/wordpress/wp-json/ [nonce] => 04864b371a )
The error I get is ReferenceError: wpApiSettings is not defined, for this line of code:
url: wpApiSettings.root + ‘wp/v2/posts/1’,
If wpApiSettings gets a value in the php section code , why isn’t it defined in the javascript section ?
The page I need help with: [log in to see the link]
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘Codeigniter with rest api’ is closed to new replies.