• I am not clear if this is possible or not… just testing things out at this point, plan to clean up and move to a plugin.

    I have a simple php function that return results from a query

    add_action( 'wp_ajax_ajax_get_geo', 'ajax_get_geo' );
    add_action( 'wp_ajax_nopriv_ajax_get_geo', 'ajax_get_geo' ); // This lines it's because we are using AJAX on the FrontEnd.
    
    function ajax_get_geo(){
        global $wpdb;
    
        $table_name = $wpdb->prefix . "wbmexp_geo";
     
        $sql = "SELECT * FROM $table_name";
    
        $results = $wpdb->get_results(  $sql );
    
        echo json_encode($results);
        die();
    } 

    and than I have a script to call this via ajax

    function getGeo() {
        jQuery.ajax({ 
    		url : '/wp-admin/admin-ajax.php', 
    		type : 'POST',
    		dataType: "json",
    		data : {
    			action : 'ajax_get_geo'
    		},
    		success: function(obj) {
    			geoData = obj;
    			console.log(geoData);
    		}
    
    	});
    	return geoData;
    }

    Now if I call this from another page /script block I can see the console.log of the json, but what I would like to do is get the return json on this page and use it throughout the page/script – is this possible? I am getting ‘undefined’.

    • This topic was modified 5 years, 3 months ago by ebud.
    • This topic was modified 5 years, 3 months ago by ebud.
Viewing 5 replies - 1 through 5 (of 5 total)
  • I’m not sure I follow what issue you’re having or what you’re asking. Could you clarify?

    – – –

    If you want to just get the geo data in PHP just call the same PHP code that your action hooks call. If you want to display what’s returned from AJAX then you can simply use JS to put that data in HTML.

    – – –

    If you’re referring to using the same info during the whole user session you may be able to store this data in a cookie. Just beware of GDPR.

    https://www.w3schools.com/js/js_cookies.asp

    Moderator bcworkz

    (@bcworkz)

    PHP isn’t picking up your action: parameter. Sending arbitrary JS objects in .ajax()’s data: isn’t compatible with PHP for some reason. Form data works fine. Try
    data : serialize({ action : 'ajax_get_geo'}),

    or use .post() which apparently serializes passed data for us.

    Thread Starter ebud

    (@ebud)

    Thanks for the feedback.
    data : serialize({ action : ‘ajax_get_geo’}),errors with > serialize is not defined.

    @howdy_mcgee – the big picture is pulling data for a table and then using ajax to pull it into the Google Map API. Hitting this /wp-admin/admin-ajax.php?action=ajax_get_geo return the data as expected. I would like to use ajax to return that data to page with the mapping script.

    This is working now

    function getGeo() {
         jQuery.ajax({ // We use jQuery instead $ sign, because WordPress convention.
    		url : '/wp-admin/admin-ajax.php', // This addres will redirect the query to the functions.php file, where we coded the function that we need.
    		type : 'POST',
    		dataType: "json",
    		async: false,
    		data : {
    			action : 'ajax_get_geo',
    		},
    		success: function(obj) {
    			jsondata = obj;
    			//console.log(geoData);
    		}
    	});
    	return jsondata;
    }

    and then on the mapping page I use:

      var geoData = getGeo();
      console.log(geoData[0]);

    This seems to be the key
    async: false,

    I am also curious about id I should be using .done vs success?

    async: false is deprecated and not good practice for AJAX (AJAX should Asynchronize)
    So I’ll try to share my experience…

    ‘geoData’ at last line result is undefined because it returns ‘geoData’ immediately while jQuery.ajax still in progress, It needs more a little time to request and get the result before announcing var geoData in the success callback

    So, if you need to create some AJAX function for better reuse or something like this. I suggest trying this instead.

    Create variable of AJAX function

    var getGeo = function() {
      return jQuery.ajax({ 
        url: '/wp-admin/admin-ajax.php',
        type: 'POST',
        data: {
          action : 'ajax_get_geo'
        },
      });
    }

    and when you want to request data then use jQuery.when()

    jQuery.when( getGeo ).done( function( obj ) {
      // do some magic with response in here
      console.log( obj );
    } );

    but if you want to create AJAX function in main.js or else just one place and want to reuse in every page at you want, try to announce AJAX function var to global like this

    if ( window.getGeo == undefined ) {
      window.getGeo = getGeo;
    }

    and now you can reuse its everywhere with jQuery.when()

    jQuery.when( window.getGeo ).done( function( obj ) {
      // do some magic with response in here
      console.log( obj );
    } );

    and last about .done VS success
    In my opinion if the code is complicated so use .done but use success callback for a few lines of callback

    var aLotOfData = jQuery.when( window.getGeo )
    
    aLotOfData.done(function(obj) {
      console.log( obj );
    });

    I hope this helps

    • This reply was modified 5 years, 3 months ago by Boat.
    • This reply was modified 5 years, 3 months ago by James Huff.
    Thread Starter ebud

    (@ebud)

    A follow up on this… I have the guts of this working, but have issues with the data returned from the ajax call.

    My php in the end send this off to which is 1 column of data named geometry(type ‘json’).

    
    echo json_encode($results);
    die();
    

    script

    var featurecollection =[] ;
    	var jsonData = $.ajax({ 
    		  url : '/wp-admin/admin-ajax.php', 
    		  type : 'POST',
    		  dataType: "json",
    		  data : {
    			  action : 'ajax_get_geo',
    		  },
    		  success: function(obj) {
    		   console.log('Got Data');
      	   },
    	   error: function(xhr) {
    			 alert(xhr.statusText)
    	   }
    	});
    	
    	$.when(jsonData).done(function(dd) {
    	  $.each(dd, function(index, item) {
    			featurecollection.push(
    				JSON.parse(dd[index].geometry)
    			);
    		  });
    		  console.log(featurecollection);
    	});

    and on the ajax side I can load and console.log the result in the browser and expand the object, but when I attempt to use the results from this column which contains geometry for various polygons it doesn’t allow me to use the dot syntax to access specific parts (eg. geometry.coordinates ).

    It seems like the data from the returned column is not json?

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘using ajax to return json’ is closed to new replies.