{"id":21044584,"url":"https://github.com/tripflex/vue-wp-admin-ajax","last_synced_at":"2025-06-11T22:33:52.400Z","repository":{"id":41952085,"uuid":"205207173","full_name":"tripflex/vue-wp-admin-ajax","owner":"tripflex","description":"Vue.js plugin wrapper around axios for making AJAX calls to WordPress admin-ajax.php (IN DEVELOPMENT)","archived":false,"fork":false,"pushed_at":"2023-03-03T06:10:21.000Z","size":906,"stargazers_count":4,"open_issues_count":18,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-04-14T18:06:29.332Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tripflex.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-08-29T16:37:03.000Z","updated_at":"2022-07-09T02:18:44.000Z","dependencies_parsed_at":"2023-01-26T15:00:56.142Z","dependency_job_id":null,"html_url":"https://github.com/tripflex/vue-wp-admin-ajax","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tripflex%2Fvue-wp-admin-ajax","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tripflex%2Fvue-wp-admin-ajax/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tripflex%2Fvue-wp-admin-ajax/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tripflex%2Fvue-wp-admin-ajax/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tripflex","download_url":"https://codeload.github.com/tripflex/vue-wp-admin-ajax/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225365878,"owners_count":17462975,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-19T14:17:39.099Z","updated_at":"2024-11-19T14:17:39.852Z","avatar_url":"https://github.com/tripflex.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# vue-wp-admin-ajax\n\n\u003e WordPress admin ajax request plugin for Vue.js built on top of [Axios](https://github.com/axios/axios)\n\n**THIS IS STILL IN DEVELOPMENT AND IS NOT YET AVAILABLE ON NPMJS.ORG**\n\nThis is a Vue.js plugin specifically for handling WordPress Admin Ajax (`admin-ajax.php`) calls, resolving a few compatibility issues when making ajax calls to WordPress.\n\n## Features\n\n- POST requests\n- GET requests\n- Response data parsing\n- Promises and async/await support\n- Automatically sets `action` and `nonce` if not manually defined\n- Automatically sets `ajaxurl` if not manually defined (from `window.ajaxurl` )\n- Optional callback on document ready\n- Uses WordPress' `addLoadEvent` if available, otherwise checks document ready state or uses `DOMContentLoaded` if not ready when loaded\n\n## Installation\n\n```shell\nnpm install vue-wp-admin-ajax\n```\n\n## Setup\n\n#### Standard\n\n```vue\nimport WPAdminAjax from 'vue-wp-admin-ajax'\nVue.use(WPAdminAjax)\n```\n\n#### Custom Options\n\n```vue\nimport WPAdminAjax from 'vue-wp-admin-ajax'\nVue.use(WPAdminAjax, { wpReturnData: true })\n```\n\n#### Options\n\n- (boolean) `wpReturnData` - Default `true` - Whether or not to parse the response, which assumes that on the WordPress PHP side, that you are using `wp_send_json_error`\n  and `wp_send_json_success`, which wraps the response in an object like `{ success: BOOLEAN, data: USERDATA }`\n\n  When `true` (default), this plugin will parse the response from WordPress, converting the value set in `data` to a JSON Object, otherwise it will return the entire response. (\n  this is specifically for the WordPress response)\n\n- (boolean) `axiosReturnData` - Default `true` - By default in axios, the entire response object is returned, by leaving this setting to `true`, only the value found in the\n  response `data` is returned. Set this to `false` to return the entire axios response object (this is specific to Axios)\n\n- (function) `ready` - Use this to specify a custom callback function to be called when the document is in a ready state. Will be passed the instance of this plugin.\n\n- (object) `axios` - Use this to specify any specific axios options to use for all requests. All available options can be found\n  under [Request Config](https://github.com/axios/axios#request-config) in axios documentation. This can also be specified in each request (see below).\n\n- (string) `nonce_key` - You can use this option to define the key in `window` object to use for the nonce (when one is not defined in `data` already). This is useful if you're\n  going to use the same nonce for all ajax calls.  This value can be a string using dot notation to specify where in an object to find the nonce.\n\n- (boolean) `successFalseReject` - Default `true` - When successFalseReject is set to true, this plugin will reject the request promise when the returned response from WordPress\n  has `success` as `false`, ie: `{ success: false, data: XXX }`. This will be the case whenever you send JSON response with wp_send_json_error() function\n\n#### `wpReturnData` vs `axiosReturnData`\n\nThe two options `wpReturnData` and `axiosReturnData` can be a bit confusing ...\n\nTo clarify, `axiosReturnData` is specifically for the axios response. When Axios returns a response, it is wrapped in schema that includes `status`, `data`, and a few other things,\nsee [https://github.com/axios/axios#response-schema](https://github.com/axios/axios#response-schema)\n\n`wpReturnData` is specifically for the WordPress response if you're using `wp_send_json_error` or `wp_send_json_success`. If you are (and you should be), this would technically be\nthe response from axios (if both `wpReturnData` and `axiosReturnData` are set to `false`):\n\n```javascript\n{\n    data: {\n        success: true,\n        data: {\n            some: 'value'\n        }\n    },\n    status: 200,\n    statusText: 'OK',\n    headers: {},\n    config: {},\n    request: {}\n}\n```\n\nAs you can see, this means the response from axios actually has `data` parameter twice. When `wpReturnData` and `axiosReturnData` are both `true` (they are by default), instead of\nreturning the response you see above, this will be returned:\n\n```javascript\n{\n    some: 'value'\n}\n````\n\n## Usage\n\nAfter installing this plugin, you can access it using the Vue instance:\n\n```\nVue.$wpaa\n```\n\nor when inside an actual Vue file:\n\n```\nthis.$wpaa\n```\n\n### Available Methods\n\n#### Parameters\n\nRegardless of whether you are using a `GET` (`this.$wpaa.get`) or `POST` (`this.$wpaa.post`) request, the arguments/parameters are exactly the same:\n\n- `action` (string) **required** - This should be the action as defined in WordPress that you are calling. In the example below, the action is `vuewpaa_demo`\n\n```php\nadd_action( 'wp_ajax_vuewpaa_demo', 'vuewpaa_demo_response' );\n```\n\n- `data` (object) **optional** - This should be an object of data that you want to send to the server (if any). Even if using `GET` it should be an object which will be converted\n  to parameters on the request.\n\n- `options` (object) **optional** - Any custom axios configuration options you want to use for this request, all available options can be found\n  under [Request Config](https://github.com/axios/axios#request-config) in axios documentation.  **These will take priority over any default or global options defined in plugin\n  setup**\n\n#### POST\n\n```\nthis.$wpaa.post( action, data, options )\n```\n\n#### GET\n\n```\nthis.$wpaa.get( action, data, options )\n```\n\n## Vuex\n\nTo access this plugin from within Vuex, you can access it using the `this._vm` which is a reference to the Vue instance, for example:\n\n```\nthis._vm.$wpaa.post( 'some_action', {id: someID })\n```\n\n## Examples\n\n#### PHP\n\nSomewhere on the page you need to output the nonce to be used, for ease of use you should use the same name as the action itself.\n\nThis plugin will automatically attempt to get the nonce value based on the action, if you don't specify one in the `data` parameter.\n\nIt will first look for the value in the `window` object, based on the action name.\n\nYou can use `wp_localize_script` to output an nonce value on the `window` object (after calling `wp_register_script` and before calling `wp_enqueue_script`):\n\n```php\nwp_localize_script( 'YOUR-SCRIPT-HANDLE', 'vuewpaa_demo', array( 'nonce' =\u003e wp_create_nonce( 'vuewpaa_demo' ) ) );\n```\n\nIf a value is not found on the window object, this plugin will check for an actual input HTML element to obtain the value from\n\nTo output an actual input with an nonce value using `wp_nonce_field` (this will create a `hidden` HTML `input` field):\n\n```php\nwp_nonce_field( 'vuewpaa_demo', 'vuewpaa_demo' );\n```\n\nIf you don't use any of the methods above, you MUST specify the nonce in the `data` parameter (using the `nonce` key)\n\nPHP AJAX Handling\n\n```php\nadd_action( 'wp_ajax_vuewpaa_demo', 'vuewpaa_demo_response' );\n\nfunction vuewpaa_demo_response(){\n    \n\t// Plugin will always pass the nonce under the `nonce` parameter/name\n    check_ajax_referer( 'vuewpaa_demo', 'nonce' );\n    \n    $post_id = absint( $_POST['id'] );\n\n    if( empty( $post_id ) ){\n        // We send with a 500 to trigger the promise rejection on call\n        // wp_send_json_error also already handles calling die()\n        wp_send_json_error( __( 'Post ID missing!' ), 500 );\n    }\n    \n    $data = 'some response';\n    // OR\n    $data = array( 'some' =\u003e 'value' );\n    \n    wp_send_json_success( $data );\n}\n```\n\n#### Vue.js\n\nI strongly recommend using `async`/`await`:\n\n```javascript\nasync sendRequest(){\n    try {\n        const result = await this.$wpaa.post( 'vuewpaa_demo', {id: this.id} );\n        console.log( result );\n    } catch( error ){\n        if ( error.response ) {\n            // The request was made and the server responded with a status code\n            // that falls out of the range of 2xx\n            console.log( error.response.data );\n            console.log( error.response.status );\n            console.log( error.response.headers );\n        } else if ( error.request ) {\n            // The request was made but no response was received\n            // `error.request` is an instance of XMLHttpRequest in the browser and an instance of\n            // http.ClientRequest in node.js\n            console.log( error.request );\n        } else {\n            // Something happened in setting up the request that triggered an Error\n            console.log( 'Error', error.message );\n        }\n        console.log( error.config );\n    }\n}\n```\n\nBut you can of course still use standard `.then` and `.catch`:\n\n```javascript\nsendRequest(){\n\n    this.$wpaa.post( 'vuewpaa_demo', {id: this.id} ).then( function( result ){\n    \t\n        console.log( result );\n        \n    }).catch( function( error ){\n    \t\n        if ( error.response ) {\n            // The request was made and the server responded with a status code\n            // that falls out of the range of 2xx\n            console.log( error.response.data );\n            console.log( error.response.status );\n            console.log( error.response.headers );\n            \n        } else if ( error.request ) {\n        \t\n            // The request was made but no response was received\n            // `error.request` is an instance of XMLHttpRequest in the browser and an instance of\n            // http.ClientRequest in node.js\n            console.log( error.request );\n        } else {\n        \t\n            // Something happened in setting up the request that triggered an Error\n            console.log( 'Error', error.message );\n        }\n        console.log( error.config );\n        \n    })\n}\n```\n\n## Dependencies\n\n- [Axios](https://github.com/axios/axios) - Promise based HTTP client for the browser and node.js\n- [QS](https://github.com/ljharb/qs) - Used to stringify data before being sent\n\n## Frontend Setup\n\nIf you plan to use this on the frontend of your site, `window.ajaxurl` is NOT set already, so you MUST localize it to be output or manually define it in the options (when\ninitializing this plugin, or making the call). To add in global options do it like this:\n\n```javascript\nVue.use(WPAdminAjax, { ajaxurl: YOUR_AJAX_URL_VALUE })\n````\n\nThe easier way would be to just localize the variable (after you call `wp_register_script` and before you call `wp_enqueue_script` ) in PHP (this will allow this plugin to\nautomatically detect the ajax url):\n\n```PHP\nwp_localize_script( 'YOUR-SCRIPT-HANDLE', 'ajaxurl', admin_url( 'admin-ajax.php' ) );\n```\n\n* in recent versions of WordPress this will throw a warning about localizing a string (thanks PHP8), so you should most likely due this another way but the method above will still work.\n\n## Demo Setup\n\n``` bash\n# install deps\nnpm install\n\n# serve demo at localhost:8080\nnpm run dev\n\n# build library and demo\nnpm run build\n\n# build library\nnpm run build:library\n\n# build demo\nnpm run build:demo\n```\n\n## Changelog\n\n- **1.0.1** (April 22, 2022)\n  - Add support for nonce in nested object (dot notation in string)\n  - Added `successFalseReject`\n\n- **1.0.0** (August 29, 2019) - Initial Release\n\n## License\n\n[MIT](http://opensource.org/licenses/MIT)\n\nCopyright (c) 2022 Myles McNamara","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftripflex%2Fvue-wp-admin-ajax","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftripflex%2Fvue-wp-admin-ajax","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftripflex%2Fvue-wp-admin-ajax/lists"}