{"id":154,"date":"2018-01-25T20:04:34","date_gmt":"2018-01-25T20:04:34","guid":{"rendered":"https:\/\/jmrowe.com\/blog\/?p=154"},"modified":"2019-02-15T15:18:17","modified_gmt":"2019-02-15T15:18:17","slug":"notes-for-using-ajax-in-wordpress","status":"publish","type":"post","link":"https:\/\/jmrowe.com\/blog\/notes-for-using-ajax-in-wordpress\/","title":{"rendered":"Notes for using Ajax in WordPress"},"content":{"rendered":"<p>While in WordPress admin area..\u00a0 the variable named ajaxurl is available for javascript scripts to use for the url for ajax. Every call must at the very least have an &#8220;action&#8221; data property passed to WordPress in order for it to know which function will be used on the back-end to complete the ajax request.<\/p>\n<pre class=\"lang:js decode:true\" title=\"Brief example of WordPress ajax js\">\/\/ when in the WordPress admin area. the variable \"ajaxurl\" is available that\r\n\/\/ points to \/wp-admin\/admin-ajax.php which handles all ajax requests.\r\n\r\n\/\/ if the user is not logged in then the ajaxurl is not automatically passed.\r\n\/\/ also wp_ajax_nopriv action must also have the php ajax function tied to it \r\n\/\/ in case the user that is visiting is not logged in.\r\n\r\nvar datasent={\r\n'action':'method_that_handles_the_ajax_request',\r\n'address':'555 street'\r\n};\r\n\r\n\/\/ in this example we manually set a ajaxurl in case the user isn't logged in.\r\n\r\nvar ajaxurltowp=site_vars.ajaxurl; \/\/ passed in from localize wp script \r\n\r\n$.post(ajaxurltowp, datasent,function(response){\r\n\/\/ response is what is sent back from the server for the ajax request.\r\n\r\n});<\/pre>\n<p>The associated php that would be needed to process above :<\/p>\n<pre class=\"lang:php decode:true\">&lt;?php\r\n\r\nfunction handle_request(){\r\n$address=$_POST[\"address\"]; \/\/ grab field sent via ajax\r\n\/\/do something here\r\n\/\/ all functions that handle ajax must die() at the end of the function.\r\ndie();\r\n\r\n}\r\n\r\n\/\/adding action assuming not in a namespace.\r\nadd_action('wp_ajax_method_that_handles_the_ajax_request','handle_request');\r\n\r\n\/\/ adding action for visitors who are no logged in\r\nadd_action('wp_ajax_nopriv_method_that_handles_the_ajax_request','handle_request');\r\n<\/pre>\n<p>Any ajax request must be handles by a function which has to be added via add_action<\/p>\n<p>Note that any action you specify in the &#8216;action&#8217; field for the data sent to the server will have &#8216;wp_ajax_&#8217; prepended to the actions name.<\/p>\n<p>Also need to bind to the action prefix &#8216;wp_ajax_nopriv&#8217; so that the ajax will still work for visitors who are not logged in.<\/p>\n<p>So the action &#8216;method_that_handles_the_ajax_request&#8217; will have to be added in php as &#8216;wp_ajax_method_that_handles_the_ajax_request&#8217; as seen in the php snippet.<\/p>\n<p>If the action can not be found by admin-ajax.php the response returned from the ajax request will be an integer of zero ( 0 ).<\/p>\n<p>If you created an ajax action method properly and you keep receiving a 0 response&#8230;confirm that your ajax action method was added.<\/p>\n<pre class=\"lang:php decode:true\">\/\/if were in a namespace would have to do the following:\r\nadd_action('wp_ajax_method_that_handles_the_ajax_request',__NAMESPACE__.'\\\\handle_request');\r\n\r\n\/\/if were in a class would have to do the following:\r\nadd_action('wp_ajax_method_that_handles_the_ajax_request',array($this,'handle_request'));<\/pre>\n<p>Any function in php that handles a ajax request MUST end with die();<\/p>\n<p>Within the php function, any post variable that is passed via the ajax data field, in our case the &#8216;address&#8217; or &#8216;action&#8217; field, is available via $_POST[&#8220;address&#8221;] or $_POST[&#8220;action&#8221;]<\/p>\n<hr \/>\n<p><a href=\"https:\/\/codex.wordpress.org\/Function_Reference\/wp_localize_script\" target=\"_blank\" rel=\"noopener\">wp_localize_script<\/a><\/p>\n<p>Used to add data to javascript that is normally only available on server side. Has to be used after an enqueue of a script and use the same &#8220;handle&#8221;. It will make the variables passed via localize_script available to the rest of the javascript that was enqueued.<\/p>\n<p>Typically, this is used for nuances<\/p>\n<p>Example of adding the nuances<\/p>\n<pre class=\"lang:php decode:true \">&lt;?php\r\n\r\n\/\/ Register the script\r\nwp_register_script( 'the_handle', 'path\/to\/myscript.js' );\r\n\r\n\/\/ Localize the script with new data\r\n\/\/ ajaxurl is passed in manually in case the visitor\r\n\/\/ is not logged in - wordpress does not automatically\r\n\/\/ populate ajaxurl if the user is not logged in\r\n\r\n$sites_variables = array(\r\n\t'site_nonce' =&gt; wp_create_nonce('site_nonce'),\r\n         'ajaxurl'=&gt; admin_url( 'admin-ajax.php' ) \r\n\t);\r\n\r\nwp_localize_script( 'the_handle', 'site_vars', $sites_variables );\r\n\r\n\/\/ Enqueued script with localized (nonce ) data.\r\nwp_enqueue_script( 'the_handle' );<\/pre>\n<p>Another way to add it when there are times where an additional script isn&#8217;t needed could be done in the following way.<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"lang:js decode:true \">function add_nonce_variable_in_javascript_to_admin_head_area(){ ?&gt;\r\n    &lt;script type=\"text\/javascript\"&gt;\r\n        var site_variables = {\r\n        'site_nonce':&lt;?php echo json_encode(wp_create_nonce(\"site_nonce\")); ?&gt;\r\n        };\r\n    &lt;\/script&gt;&lt;?php\r\n}\r\nadd_action( 'admin_head', __NAMESPACE__ . '\\\\add_nonce_variable_in_javascript_to_admin_head_area' );<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>Now we can update the javascript to use the nonce to pass back to WordPress to check for nonce validity.<\/p>\n<pre class=\"lang:js decode:true \">\/\/ \"site_nonce\" is populated from the sites_vars variable passed from wp_localize_script\r\n\r\nvar datasent={\r\n\"action\":\"method_that_handles_the_ajax_request\",\r\n\"address\":\"555 street\",\r\n\"site_nonce\":sites_vars.site_nonce;\r\n};\r\n\r\n$.post(ajaxurl, data_sent,function(response){\r\n\/\/ response is what is sent back from the server for the ajax request.\r\n\r\n});<\/pre>\n<p>Now that the nonce is created and is being passed from javascript to WordPress.. we setup below in php in the action that the ajax requests\u00a0 to process it&#8217;s integrity.<\/p>\n<pre class=\"lang:php decode:true \">if( !isset($_POST['site_nonce']) || !wp_verify_nonce($_POST['site_nonce'], 'site_nonce')){\r\n\/\/ nonce is missing or is bad. Cancel request\r\n\r\ndie('Permission check failed');\r\n}\r\n\r\n\/\/$_POST['site_nonce'] has to be passed in first parameter as it is POST name we gave it below:\r\n\r\n\r\n\/\/ site_nonce has to be passed since it was \r\n\/\/ the handle we used when creating the nonce\r\n\/\/ i.e. wp_create_nonce('site_nonce');<\/pre>\n<p>&nbsp;<\/p>\n<p>Good notes for ajax usage: <a href=\"https:\/\/developer.wordpress.org\/plugins\/javascript\/enqueuing\/\">https:\/\/developer.wordpress.org\/plugins\/javascript\/enqueuing\/<\/a><\/p>\n<p><code class=\"php spaces\">\u00a0<\/code><code class=\"php plain\">check_ajax_referer( <\/code><code class=\"php string\">'nonce'<\/code> <code class=\"php plain\">);<\/code> \u00a0This function will check nonce and if it fails will automatically kill the action it was ran within<\/p>\n<p><code class=\"php spaces\">\u00a0<\/code><code class=\"php plain\">wp_send_json() <\/code> will send back appropriate header and json back to javascript as well as wp_die() for the action it was called in.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>While in WordPress admin area..\u00a0 the variable named ajaxurl is available for javascript scripts to use for the url for ajax. Every call must at the very least have an &#8220;action&#8221; data property passed to WordPress in order for it to know which function will be used on the back-end to complete the ajax request. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-154","post","type-post","status-publish","format-standard","hentry","category-wordpress"],"_links":{"self":[{"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/posts\/154","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/comments?post=154"}],"version-history":[{"count":25,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/posts\/154\/revisions"}],"predecessor-version":[{"id":322,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/posts\/154\/revisions\/322"}],"wp:attachment":[{"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/media?parent=154"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/categories?post=154"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/tags?post=154"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}