I have created a plugin for user to check delivery option is available in their location or not.
backend code is working fine like, I can add zipcode. data is showing in the admin table.
in the frontend am trying to check data via ajax call where getting response as 0 with if statement even when I enter an existing zip code or wrong.
Please help where am wrong. Thanks.
Here is JavaScript Ajax Code
jQuery(document).ready(function() {
var zipcodeInput = jQuery("#checkzipcode").find("input[name='checkzipcode']");
var zipcodeSubmit = jQuery("#ajax-form");
zipcodeSubmit.submit(function(e) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: my_action_callback.ajaxurl,
dataType: 'html',
data: {
action: 'my_action_callback',
checkzipcode: zipcodeInput.val()
},
success: function (data) {
jQuery('#zipcode-result').html(data);
},
error: function (data) {
console.log('error');
}
});
});
});
Here is THML Code
function check_zipcode_for_delivery_frontend(){ ?>
<div class="woo-zcd-form">
<form method="POST" id="ajax-form">
<label>Enter Zipcode:</label>
<input type="text" name="checkzipcode" id="checkzipcode" required>
<input type="submit" name="submit" value="Check Zipcode" id="submit-zipcode">
</form>
</div>
<div id="zipcode-result"></div>
<?php }
add_shortcode('check_zipcode_delivery', 'check_zipcode_for_delivery_frontend');
Here is PHP Code
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'assets/js/custom.js', array('jquery') );
wp_enqueue_script( 'jquery' );
wp_localize_script( 'my_custom_script', 'my_action_callback', array( 'ajaxurl' => admin_url('admin-ajax.php') ) );
});
add_action('wp_ajax_my_action_callback', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action_callback', 'my_action_callback');
function my_action_callback() {
global $wpdb;
$table_name = $wpdb->prefix . "deliverybyzipcode";
$checkzipcode = $_POST['checkzipcode'];
$sql = "SELECT * FROM ".$table_name." WHERE delivery_zipcode = '$checkzipcode'";
$result = $wpdb->query($sql);
$rows = $result->num_rows;
if($rows == $checkzipcode) {
echo "Yes! Our delivery service is available in your area.";
}
else {
echo 'Sorry! we are currently no delivering in your area.';
}
}
I think this line is causing the trouble.
Change this line $sql = "SELECT * FROM ".$table_name." WHERE delivery_zipcode = '$checkzipcode'";
to this one $sql = "SELECT * FROM ".$table_name." WHERE delivery_zipcode = '".$checkzipcode."'";
It is not clear from your question what is the type of delivery_code in your database so you should pay attention to that as well. And of course, take care of SQL injection.
Related
I'm trying to make some SQL queries using PHP in Wordpress, to auto populate and check values on a gravity form against the existing database.
To do that however, I'm going to need to pass some javascript variables to php, then use that to interact and pull that data back to the form. As someone with minimal web dev background, easier said then done.
My main issue is with an AJAX call that properly carries over a value, but only to the action function. All other calls will show null (I assume due to scoping, but globals don't seem to help).
The main relevant PHP is in a custom plugin as follows:
$address = 0;
function my_enqueue() {
wp_register_script( 'lead-scheduler', null);
wp_enqueue_script( 'lead-scheduler', plugins_url( '/lead_ajax.js', __FILE__ ), array('jquery') );
wp_localize_script( 'lead-scheduler', 'leadajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'jquery' );
wp_register_script( 'lead_ajax', null);
wp_enqueue_script( 'lead_ajax' );
}
add_action( 'init', 'my_enqueue' );
function handle_request(){
//Check post address, then apply to global variable
echo $_POST['address'] . "\n";
global $address;
$address = $_POST['address'];
echo $address . "\n";
wp_die("RIP");
}
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' );
function functionCaller() {
if (is_page ('')) {
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(function(){
var addressField = document.getElementById('input_22_2');
var temp;
//Set up event listener
addressField.onchange = addressCheck;
function addressCheck(){
//Get foreign script
$.getScript("/wp-content/plugins/lead-scheduler/lead_ajax.js", function(){
//Wait until done to execute console.log
$.when(adrCheck()).done(function(){
console.log("Logging: " + "<?php global $address; echo $address ?>");
});
});
}
});
});
</script>
<?php
}
}
add_action('wp_head', 'functionCaller'); ?>
The AJAX call comes from a JS file that I call to:
//AJAX
function adrCheck(){
jQuery(document).ready( function() {
console.log("called")
var addressField = document.getElementById('input_22_2').value;
jQuery.ajax({
type : "post",
url : leadajax.ajax_url,
data : {action: "handle_request", address: addressField},
success: function(response) {
console.log(response)
},error: function(response){
console.log(response);
}
})
})
}
The call seems to work, as the echo in handle_request() works fine. But calling that variable anywhere else returns null. $.when.done doesn't seem to do much, nor does anything synchronous.
I'm sure there's something super elementary that I'm missing, but I can't seem to find it.
My ajax call output is always showing 0 as output don't know why
In functions.php I have this code
function get_data() {
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
And my ajax call is in a javascript
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "GET",
dataType : "json",
url : "/wp-admin/admin-ajax.php",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
I'm making ajax call in wordpress without use of plugin but not getting what I'm passing.Even If I output $abc still it shows 0.
In backend there is global ajaxurl variable defined by WordPress itself.
This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.
Good way to do this is to use wp_localize_script.
Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
After localizing your JS file, you can use my_ajax_object object in your JS file:
jQuery.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: formData,
success: function(msg){
console.log(msg);
}
});
Actually, WordPress comes with a handy function to access admin-ajax.
Requirements
In wp-admin you do not need to do anything, the js library is always loaded
In the front-end you need to enqueue the script wp-util, like this:
add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
function my_enqueue_function() {
// Option 1: Manually enqueue the wp-util library.
wp_enqueue_script( 'wp-util' );
// Option 2: Make wp-util a dependency of your script (usually better).
wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );
}
The JS Library
The wp-util script contains the wp.ajax object that you can use to make ajax requests:
wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )
Your example:
wp.ajax.post( "get_data", {} )
.done(function(response) {
alert("Your vote could not be added");
alert(response);
});
PHP code
Of course, you still need to create the wp_ajax_* hooks in your PHP script.
add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );
function my_ajax_handler() {
wp_send_json_success( 'It works' );
}
Tip:
For Ajax responses WordPress provides two functions:
wp_send_json_success( $my_data ) and wp_send_json_error( $my_data ) - both functions return a JSON object and instantly terminate the request (i.e., they exit;)
I had the same problem. I was new to WordPress. Therefore, I am explaining here so that every new learner can understand how ajax is calling in WordPress.
First, create a function in function.php file that resides under wp-content/theme/selected_theme folder. Here, selected_theme maybe your theme name.
In the above question, a function is created with the name get_data();
function get_data() {
echo "test";
wp_die(); //die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
in the above two lines,
The add_action method is used to implement the hook. Here, I am passing the two parameters, first is wp_ajax_nopriv_get_data. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.
In the second add_action, I am passing the two parameters, first is wp_ajax_get_data. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.
Here, wp_ajax_nopriv call if the user is not logged in and wp_ajax called when the user is logged in.
jQuery.ajax({
type: "post",
dataType: "json",
url: "/wp-admin/admin-ajax.php", //this is wordpress ajax file which is already avaiable in wordpress
data: {
action:'get_data', //this value is first parameter of add_action
id: 4
},
success: function(msg){
console.log(msg);
}
});
Add admin-ajax.php by using admin_url('admin-ajax.php');
<script type="text/javascript">
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "POST",
dataType : "json",
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
</script>
<form type="post" action="" id="newCustomerForm">
<label for="name">Name:</label>
<input name="name" type="text" />
<label for="email">Email:</label>
<input name="email" type="text" />
<label for="phone">Phone:</label>
<input name="phone" type="text" />
<label for="address">Address:</label>
<input name="address" type="text" />
<input type="hidden" name="action" value="addCustomer"/>
<input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>
functions.php
wp_enqueue_script('jquery');
function addCustomer() {
global $wpdb;
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];
if ( $wpdb->insert( 'customers', array(
'name' => $name,
'email' => $email,
'address' => $address,
'phone' => $phone
) ) === false ) {
echo 'Error';
} else {
echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
javascript
<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: newCustomerForm,
success: function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
</script>
If you are getting 0 in the response, it means your ajax call is working correctly.
But, you have not defined $wpdb as a global variable in your function get_data.
Check your error log, you must be seeing error there.
Try:
function get_data() {
global $wpdb;
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}
Step 1: Add ajax 'wp_enqueue_script' file in function file where you have to add other 'wp_enqueue_script' or 'wp_enqueue_style' files
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax- script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
Step 2:Now you need to create function, where you want to get response, using ajax
e.g below
add_action('wp_footer','add_ajaxex_in_footer');
function add_ajaxex_in_footer()
{ ?>
<script type="text/javascript">
jQuery('#sbmtbtn').click(function(){
jQuery.ajax({
type:"POST",
url:my_ajax_object.ajax_url,
data: {action:'my_special_ajax_call_enroll_cours'},
success:function(res){
console.log(res);
}
});
});</script><?php
}
Step 3: Now you have to create function where you have to write query,
add_action('wp_ajax_my_special_ajax_call_enroll_cours', 'enroll_cours');
add_action('wp_ajax_nopriv_my_special_ajax_call_enroll_cours', 'enroll_cours');
function enroll_cours()
{
echo "Here you van write Query or anything";
exit;
}
=> If you want to fire ajax request after onClick button, just pass the button ID
<input type="button" id="sbmtbtn" name="Save">
Here how to make in plain vanilla js the AJAX call in WordPress.
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);
}
See on this blog, what to add functions.php and template html to get this work, also reasonings why there is no data in vanilja js unlike jQuery, but just action
Here add_actions in functions.php:
add_action( 'wp_ajax_testfirst', __NAMESPACE__ .'\\FunctionTF' );
add_action( 'wp_ajax_nopriv_testfirst', __NAMESPACE__ .'\\FunctionTF');
Add this function over that, here now this function:
function FunctionTF(){
exit( "Hola hola" );
}
See explanation why? code in "exit" in my blog
Here add this html on some wp-template
<div id="demo"></div>
<div id="demo2"></div>
<button id="spesial_button" onclick="P_lifg()">I am spesial</button>
See rest in: https://praybook2.blogspot.com/2021/03/AJAX-plain-vanilla-js-wp-and-namespace.html
I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".
I have been trying to make to make a page where i could select a customer and would get the corresponding customer details from a database.
It should look something like this:
<select id="select_customer">
<option value='1'>customer 1</option>
<option value='1'>customer 2</option>
</select>
public function getCustomerDetails($customerId) {
if(isset($customerId)) {
$customer = DB::getInstance()->query("select * from customers");
foreach($customer->results() as $customer) {
$str = "<li>{$customer->name}</li>";
$str .= "<li>{$customer->name_contactperson}</li>";
$str .= "<li>{$customer->email}</li>";
$str .= "<li>{$customer->address} {$customer->house_number}</li>";
$str .= "<li>{$customer->postalcode}</li>";
$str .= "<li>{$customer->city}</li>";
$str .= "<li>{$customer->country}</li>";
}
return $str;
}
return false;
}
What i now would like to do is to get the value from the select_customer post this with ajax to the getCustomerDetails method and get the corresponding details without a page reload.
I tried to make it work with ajax and with xAjax but i coulden't get it to work.
I tried this:
<?php include 'xajaxAIO.inc.php';
$xajax = new xajax();
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->processRequest(); ?>
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />
The other thing i tried was this:
<script>
document.getElementById('select_customer').addEventListener('change', function() {
var $userId = this.value;
$.ajax({
type: "POST",
url: "classes/invoice.php",
data: "getCustomerDetails("+$userId+")"
})
});
</script>
I dont get any error messages in my console but it seems like the requested function doesnt execute.
Anybody who could tell me how it could get this to work?
Thanks in advance!
I would recommend just sending $userId alone then call getCustomerDetails($userId) in the invoice.php page.
$.ajax({
type: "GET",
url: "classes/invoice.php",
data: $userId
})
});
OR
$.ajax({
type: "GET",
url: "classes/invoice.php&function=getCustomerDetails&userId="+$userId
dataType: "json", //Dont need this if youre returning a string
success: function(result) {
alert(result);
}
})
});
Then in the invoice page you could call the function using the $_GET variable like so:
$response = 'error;
if($_GET['function'] == 'getCustomerDetails'){
if(!empty($_GET['userId'])){
$_GET['userId'] = 0;
}
$userID = $_GET['userId'];
$response = getCustomerDetails($userID);
}
die(json_encode($response)); //for array
die($response); //for a string
If you use xajax framework... you need register the new function...
<?php include 'xajaxAIO.inc.php';
$xajax = new xajax();
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->register(XAJAX_FUNCTION, 'getCustomerDetails');
$xajax->processRequest(); ?>
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />
<?php function getCustomerDetails($id){
///////////////////////////////////////////////
///// And use framework xajax to response /////
///////////////////////////////////////////////
}?>
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);
}
});
});
}
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.
Remove console.log
Then the data will not be get