Wednesday, March 24, 2021

How to get AJAX ”get” to work on wp(WordPress) in vanilla js(javascript ) when there is namespace, when press button –jQuery (NO jQuery)

 Huh! This take a lot a time, to figure out so many moving parts.

1. No "data" needed at all, but "action"

First I try figure out what jQuery does, but that was lot of scramble I got nothing. Finally then I figure to look inside admin-ajax.php itself if there is hint's how it works. And there I found what I been looking for.

 


So right url is on form:

...wp-admin/admin-ajax.php?action=testfirst

Where "testfirst" is that what $_GET add in $action from the url.

2.This kind of button and two div's for the AJAX on somewhere in WP Templates

 <div id="demo"></div>
 <div id="demo2"></div>
 <button id="spesial_button" onclick="P_lifg()">I am spesial</button>
 
"P_lifg()" is function that has the ajax get.

3.Next js script file

I name it OWnajaxjs.js

You know like in https://www.w3schools.com/js/js_ajax_intro.asp But few changes.
Pic from w3schools

And that admin-ajax.php page it's "empty" that must fill by specials actions on functions.php
But here now it OWnajaxjs.js file:


var urlToajax=jsajaxe_S.ajaxurl;


 function P_lifg(){ 
 
	 var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.responseText;
    document.getElementById("demo2").innerHTML = urlToajax+ "?action=testfirst";
    }
  };
	
	
	xmlhttp.open("GET", urlToajax+ "?action=testfirst", true); 	
	xmlhttp.send(0);
	
 }


//file end
That jsajaxe_S.ajaxurl is the actual location of admin-ajax.php this js file get it from php in wp_localize_script at the functions.php.

"demo" div will get AJAX dump and "demo2" get url to location where dump is so one can go there to check it out.


4.functions.php 1. Register, Localize and Enqueue script that is OWnajaxjs.js


So add this in functions.php

5.functions.php 2. wp_ajax_ wp_ajax_nopriv_

add_action( 'wp_ajax_testfirst', __NAMESPACE__ .'\\FunctionTF' );
add_action( 'wp_ajax_nopriv_testfirst', __NAMESPACE__ .'\\FunctionTF');
 Next the pic that explains it all:

6.functions.php 3.action function here FunctionTF

  function FunctionTF(){

  exit( "Hola hola" );

		
	} 
Yes see, it "hola hola" is inside exit(), this take long time to figure out, there was conflicting information in web where to lay code here, but then I figure to again return to a admin-ajax.php file, and from there I get notice, that there are certain inbuild core ajax actions so I figure to go and check how one of them handle AJAXhandle I choose wp_ajax_rest_nonce() function and behold on 


7. If you get everything right



3D BLog has return

Go  to Check    https://thereal3dblog.com/