简体   繁体   中英

Wordpress Jquery MySQL Plugin

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); } }); }); } 

删除console.log然后将无法获取数据

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM