1

So, I'm working on a plugin that leverages jquery and mysql to dynamically update dropdown boxes.

When the page first loads, the dropdown box should be populated with data selected from mysql. But nothing, apart from the empty dropdown box rendering to the page, works. And no error messages are issued.

What am I overlooking here?

plugins/myplugin/myplugin.php

<?php

/**
 * Plugin Name: Test
 * Plugin URI: 
 * Description: This plugin performs dynamic region updates into select boxes in WordPress
 * Version: 1.0.0
 * Author: Me
 * Author Email: 
 * License: GPL2
 */

function getregions_scripts() {
  wp_enqueue_script(
    'getregions-script',
    plugin_dir_url(__FILE__) . "assets/getregions.js",
    array('jquery'),
    '1.0',
    true
  );

  wp_localize_script(
    'getregions-script', // this needs to match the name of our enqueued script
    'gymRegions',      // the name of the object
    array('ajaxurl' => admin_url('admin-ajax.php')) // the property/value
  );
}
add_action( 'wp_enqueue_scripts', 'getregions_scripts' );

add_action( 'wp_ajax_showcountries', 'showcountries_callback' );
add_action( 'wp_ajax_no_priv_showcountries', 'showcountries_callback' );
function showcountries_callback() {

  include_once("pdo_mysql.php");

  pdo_connect("localhost","user","password");
  pdo_select_db("wpdb");


  $action=$_POST["action"];

  if($action=="showcountries"){
     $showcountry = pdo_query("Select country_data from wp_usertable");

     if (!$showcountry) {
         $message  = 'Invalid query: ' . pdo_error() . "\n";
         $message .= 'Whole query: ' . $showcountry;
         die($message);
     }else{
         foreach($showcountry as $row){
            echo '<option value=".$row[country_code].">.$row[country_name].</option>';
         }
     }
  }
  else if($action=="showregions"){
      $country_id= $_POST["country_id"];

      $showregion = pdo_query("Select region_code, region_name from regiontbl
                WHERE country_id=?", pdo_real_escape_string($country_id));

      if (!$showregion) {
          $message  = 'Invalid query: ' . pdo_error() . "\n";
          $message .= 'Whole query: ' . $regionquery;
          die($message);
      }else{
         foreach($showregion as $row){
            echo '<option value=".$row[region_code].">.$row[region_name].</option>';
         }
      }
  }

}

function showcountries_frontend() {
$the_html = '
<form id="MyForm">
        <div style="float: left">
            <select id="CountryList" onchange="getRegion()" size="20"></select>
            <select id="RegionList" size="20" onchange="getMap()"></select>
        </div>
        <div id="cityList" style="float: right"></div>
</form>';
return $the_html;
}
add_shortcode("sc_frontend", "showcountries_frontend");

?>

plugins/myplugin/assets/getregions.js

function initialize($) {
    .......
    feedData($);
}

jQuery(document).ready(function ($) { initialize($); });

function feedData($) {
    jQuery(document).ready(function ($) {
        var serialized = $('#MyForm').serialize();
        $.ajax({
            cache: false,
            type: "POST",
            async: false,
            url: "gymRegions.ajaxurl",
            data:{action=showcountries, serialized},
            success: function (data) {
                $('#CountryList').append(data);
            },
            error: function (data, status, error) {
                console.log(data);
                console.log(status);
                console.log(error);
            }
        });
    });
}
TheoG
  • 1,498
  • 4
  • 30
  • 54
  • 1
    Is your data making it back from your ajax call? Try a `console.log(data)` after `success` and let us know. – jbrya029 May 06 '16 at 15:06
  • @jbrya029 No, nothing is making it back. I placed a console.log(data) within success:, and no output was generated. Any ideas? – TheoG May 06 '16 at 16:28
  • Your problem is probably with your pdo connection, your "action" post variable, or your echo statement throwing an error. Have you tried looking at the XHR request in Chrome's developer tools --> Network tab? If you're throwing a PHP error it should appear here whereas it may not make it back as "data" in the ajax call. – jbrya029 May 06 '16 at 16:57
  • @jbrya029 I've looked at the XHR request in Chrome, and again, nothing is generated there either. I only get an 'Invalid shorthand property initializer' error notification in developer tools --> Sources. – TheoG May 06 '16 at 17:13
  • Try adding an `else` statement to your `$action` if/elseif that echoes an error message. If you're still getting nothing, you may just need to echo every step of the file until you can find the breakpoint and address the issue from there. – jbrya029 May 06 '16 at 17:21
  • @jbrya029 Ok, so the first issue I resolved, is that my action statement should have read {action: "showcountries"}. By doing so, I now receive the following: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. jquery.js?ver=1.12.3:4 POST http://192.168.0.50/index.php/testing-2/gymRegions.ajaxurl 404 (Not Found) So, gymRegions.ajaxurl, or rather ajaxurl, is the issue. Where do I find ajaxurl? – TheoG May 06 '16 at 18:05
  • that needs to be the url of your plugins page to complete the ajax call. In your example, it needs to point to `myplugin.php` and call the showcountries_callback function. – jbrya029 May 06 '16 at 18:12
  • @jbrya029 Sorry for sounding somewhat dim (it's been a long day with this), but what exactly needs to point to myplugin.php? – TheoG May 06 '16 at 18:26
  • Your quotes are off. You can use double quotes and { - `""` – jbrya029 May 06 '16 at 20:43
  • @jbrya029 Ok, so the issue was that url should have been defined as url: gymRegions.ajaxurl. EDIT: It works now, and I've just seen your response below. Many thanks for ALL of your help :) – TheoG May 06 '16 at 20:50

2 Answers2

0

Remove console.log Then the data will not be get

vishal
  • 1
  • Can you expand a little more on what you mean, exactly? I removed the entire error: function section, but this made no difference. – TheoG May 06 '16 at 16:35
0

There's a lot going on here that needs to be addressed.

Your ajax call is looking for a location to make the call to; however, you are passing this value:

url: "gymRegions.ajaxurl",

So, the resulting 404 is based on that string: 192.168.0.50/index.php/testing-2/gymRegions.ajaxurl

Localizing a script

In order to pass the location of your plugin directory to your javascript file, you will need to localize the scrip. This can be done in wordpress using the following:

wp_enqueue_( 'getregions-script', plugin_dir_url(__FILE__) . "assets/getregions.js", array('jquery'), '1.0', true);
wp_localize_script( 'getregions-script', 'gymRegions', array('ajaxurl' => plugin_dir_url(__FILE__) . 'assets/getregions-ajax.php'));

This will allow you to call gymRegions.ajaxurl without quotes in your ajax call.

Make your ajax file

Now that this has been completed, you can create a new php file in your plugin: assets/getregions-ajax.php. This file will house your current showcountries_callback function content (does not need to be a function). Whatever is on this page will be executed.

To include wp, I usually use something like this:

header('Content-Type:application/json');
header("X-Robots-Tag: noindex, nofollow", true);

/* find and load wp to avoid duplicating class */
if (file_exists('../../../../wp-load.php')) :
    require_once('../../../../wp-load.php');
else:
    require_once('../../../../../wp-load.php');
endif;

After this, I will require my class or execute any code.

JSON encode output

Finally, consider JSON encoding your output. Instead of echo-ing everything instantly create an $html variable and at the end of your file:

echo json_encode($html, JSON_PRETTY_PRINT);

Go one step at a time

This may be a little confusing at first but taking it one step at a time will help. Don't try to eat it all in one bite, just focus on getting 'hello world' to return from your ajax call and then build from there.

There may be other issues but this should at least get you started down the right path.

jbrya029
  • 492
  • 3
  • 11
  • @TheoG you will need to parse the json data in the response: http://stackoverflow.com/questions/5289078/parse-json-from-jquery-ajax-success-data – jbrya029 May 06 '16 at 23:23