Good Day. I'm trying to develop a plugin for WordPress that manually sends an e-mail (containg the WooCommerce Order details) to a desired supplier's e-mail. I'm having a hard time figuring out on how to load a data when a user select from a drop down list. I would like to load the data using AJAX on multiple fields without leaving the page. Here's some part of the code:
<select id = "dropdown_orders" class = "dropdown_orders" name="dropdown_orders" onchange="myFunction(this.value)">
<option value=""><?php _e( 'Select an Order', 'woocommerce-manual-order-forwarding' ); ?></option>
<?php
foreach($order_details as $details => $value)
{
echo '<option value="' . $value['ID'] . '">' . "Order ID: " .$value['ID'] . '</option>';
}
?>
</select>
That is the code for the drop down list to show all the Orders with "Complete" Status. And here is the AJAX part.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"</script>
<script type="text/javascript">
function myFunction(value)
{
if(value!="")
{
$.ajax(
{
type: "GET",
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { experience: value},
success: function(data) {
alert("You have selected the Order ID of: " + value);
//I want to display a div element that contains all the data from the WordPress database.
}
});
}
else
{
alert("Please Select and Order ID first!");
}
}
</script>
What I want to achieve is that, when the user select from one of the options from the drop down list, the page will display a div element that displays all the details about the order. Is it possible to do that? Any help would be appreciated. I know that it's impossible to call a PHP function after the "success" part of AJAX.
EDIT HERE
On display-orders-admin.php
<div id="forward-field" class="wrap">
<h2><?php _e( 'WooCommerce Order Forwarding System', 'woocommerce-manual-order-forwarding' ); ?></h2>
<p><?php _e( '<strong>Note:</strong> This add-on gives you the capability to forward your WooCommerce orders individually on your desired supplier.', 'woocommerce-manual-order-forwarding');?></p>
</div>
<div class="container-box">
<h2><?php _e( 'Order Details', 'woocommerce-manual-order-forwarding' ); ?></h2>
<p><?php _e( '<strong>Note:</strong> Please select an order from the drop down list below to use the order e-mail forwarding feature.', 'woocommerce-manual-order-forwarding');?></p>
<select id = "dropdown_orders" class = "dropdown_orders" name="dropdown_orders">
<option value=""><?php _e( 'Select an Order', 'woocommerce-manual-order-forwarding' ); ?></option>
<?php
foreach($order_details as $details => $value)
{
echo '<option value="' . $value['ID'] . '">' . "Order ID: " .$value['ID'] . '</option>';
}
?>
</select>
<div class="custom-border"></div>
<!-- TRIGGER AN ACTION HERE WHEN THE USER SELECT FROM ONE OF THE ORDER IDS FROM DROPDOWN -->
<!-- EXECUTE A JQUERY | AJAX REQUEST TO PULL OUT ALL THE DETAILS OF THE ORDER WITH THE GIVEN ID -->
<!-- DISPLAY THE ORDER DETAILS USING DIV ELEMENTS ON THE SAME PAGE -->
</div>
How can I achieve those in comments?
First you are using jQuery, yet you are doing things old-school by using onchange. Let's not do that.
Remove onchange attribute and instead attach an onchange event listener to your dropdown using .change() method.
<select id="dropdown_orders" class="dropdown_orders" name="dropdown_orders">
<option value=""><?php _e( 'Select an Order', 'woocommerce-manual-order-forwarding' ); ?></option>
<?php foreach ($order_details as $details => $value) : ?>
<option value="<?php echo $value['ID'] ?>">Order ID: <?php echo $value['ID'] ?></option>
<?php endif ?>
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"</script>
<script>
$(function () {
$('#dropdown_orders').change(function () {
if (this.value != "") {
// fyi: $.getJSON() method is a shorter syntax
$.ajax({
type: "GET",
url: '<?php echo $_SERVER['PHP_SELF'] ?>',
data: { experience: this.value },
dataType: "json",
success: function (res) {
// ...
}
});
} else {
alert("Please Select and Order ID first!");
}
});
});
</script>
Now, regarding your actual problem, make your PHP return back a JSON string using json_encode(). A starter example of how your PHP script would look like:
// first step: check the request parameter
if (isset($_GET['experience'])) {
// get the order detail e.g. $order based on the request parameter
// let's assume $order is an associative array e.g. $order = ['id' => 123, 'price' => 12.40]
// final step: send back a JSON-encoded response
header('Content-Type: application/json');
echo json_encode($order); // only this should be echo'd
}
Back to the HTML/JS code, all you have to do is process the response res once it is received in the success callback. First, it may be a good idea to create and re-use a hidden block element to store your order detail's information. This will be like a template. You will just need to show it once the order information is ready.
So, first add the following to your HTML:
<div id="order-detail" style="display: none;">
<div class="id"></div>
<div class="price"></div>
</div>
Next, change your JS.
$(function () {
$('#dropdown_orders').change(function () {
if (this.value != "") {
// fyi: $.getJSON() method is a shorter syntax
$.ajax({
type: "GET",
url: "<?php echo $_SERVER['PHP_SELF'] ?>",
data: { experience: this.value },
dataType: "json",
success: function (res) {
// load the information from your response into the DIV
var $div = $('#order-detail');
$div.find('.id').html(res.id);
$div.find('.price').html(res.price);
// show the DIV once everything is ready
$div.show();
}
});
} else {
alert("Please Select and Order ID first!");
}
});
});
Instead of having a template to store your order details, you can also build the DIV with the order information within your success callback; however, this may lead to messy code.
Related
I'm trying to show the parent categories in a drop-down box and based on which parent categories are selected, their Sub Categories should appear in a separate drop-down box via an ajax call.
I've done a lot of research and came across the following article which is 100% what I need to achieve: https://1stwebdesigner.com/implement-ajax-wordpress-themes/
I followed it correctly but for some reason, the sub-category drop-down is always disabled.
My end goal is to have the 2 dropdowns with a submit button and have it act as a search form, display the selected sub-category posts on a separate page, this was my first step to getting there but having no luck.
I've tried changing the javascript $ to jQuery as this was giving an error the first time I used it but currently no errors on the page at all.
<!-- Dropdown select box & javascript -->
<div id="content">
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
<script type="text/javascript">
jQuery(function() {
jQuery('#main_cat').change(function() {
var $mainCat = jQuery('#main_cat').val();
// call ajax
jQuery("#sub_cat").empty();
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
type: 'POST',
data: 'action=my_special_action&main_catid=' + $mainCat,
success: function(results) {
// alert(results);
jQuery("#sub_cat").removeAttr("disabled");
jQuery("#sub_cat").append(results);
}
});
});
});
</script>
</div>
<!-- Ajax call in function.php -->
add_action('wp_ajax_my_special_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');
function implement_ajax() {
if(isset($_POST['main_catid']))
{
$categories= get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
foreach ($categories as $cat) {
$option .= '<option value="'.$cat->term_id.'">';
$option .= $cat->cat_name;
$option .= ' ('.$cat->category_count.')';
$option .= '</option>';
}
echo '<option value="-1" selected="selected">Scegli...</option>'.$option;
die();
} // end if
}
add_action('wp_ajax_my_special_ajax_call', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_ajax_call', 'implement_ajax');//for users that are not logged in.
In jQuery you call the action action=my_special_action and in functions.php the function you hook with your action is my_action_callback but you didn't define that function. Also, the second hook is not even triggering.
Try the below code
<!-- Ajax call in function.php -->
add_action('wp_ajax_my_special_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');
function my_action_callback() {
if(isset($_POST['main_catid'])) {
$categories = get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
foreach ($categories as $cat) {
$option .= '<option value="'.$cat->term_id.'">';
$option .= $cat->cat_name;
$option .= ' ('.$cat->category_count.')';
$option .= '</option>';
}
echo '<option value="-1" selected="selected">Scegli...</option>'.$option;
die();
} // end if
}
Learn more about How to use ajax in WordPress?
I am new in ajax. i have a problem. i'm selecting value from select tag and sending it into ajax code that give me record at realtime but it display nothing in next select tag. if i tried to open second php file. it diplay error like, "Notice: Undefined index: class in C:\xampp\htdocs\ERP\std.php on line 4". i don't know what to do. help me.
Here is my code of ajax
<script>
function myfunction(datavalue) {
$.ajax({
type: 'POST',
url: 'std.php',
data: { class : datavalue},
success: function(response){
$('#stdName').html(response);
}
});
}
</script>
option from where i am getting value
<select name="std-class" onchange="myfunction(this.value)" id="stdClass">
<?php if(isset($_GET['fee_id'])){?>
<option value="<?php echo $row['std_class']; ?>"><?php echo $row['std_class'];?></option>
<?php }else {?>
<option>Select Class</option>
<?php }
$std=mysqli_query($con, "SELECT class_name FROM classes");
while($row1=mysqli_fetch_array($std)){
?>
<option value="<?php echo $row1['class_name'];?>"><?php echo $row1['class_name'];?></option>
<?php }?>
</select>
And this is the php file code
<?php
$con=mysqli_connect("localhost","root","","sms_db");
$class=$_POST['class'];
$result=mysqli_query($con, "SELECT * FROM students WHERE class='$class' ORDER BY id ASC");
while($rows=mysqli_fetch_assoc($result)){ ?>
<option value="<?php echo $rows['username'];?>"><?php echo ucwords($rows['name']);?></option>
<?php }
?>
I also tried this code but it also not working
<script>
function myfun() {
var select = document.getElementById('stdClass').value;
console.log(select);
$.post("std.php", {
class: select
},
function(response) {
$('#stdName').html(response);
});
}
</script>
<script>
function myfunction(datavalue) {
$.ajax({
type: 'POST',
url: 'std.php',
data: { "class" : datavalue},
success: function(response){
$('#stdName').html(response);
}
});
}
</script>
I have html form and ajax use for submission data to php page. There is one select box which values retrieve from database, options are display correctly and same value assigned to 'Value' attribute as well. but when passed to php page it shows only only one part of value. Codes are blow.
<
form id='add-student'>
<select name="txt_class" class="form-control" id="txt_class">
<?php
include ('../svr/class-dropdown.php');
while ($row_1 = mysqli_fetch_array($result_1)) {
echo '<option value=' . $row_1['class_name'] . '>' . $row_1['class_name'] . '</option>';
}
?>
</select>
</form>
Value of $row_1['class_name']==Grade 10,
Ajax submission part
submitHandler: function (form) {
var form_data = $("#add-student").serialize();
$(form).ajaxSubmit({
url: "../svr/add-stu-submit.php",
data: form_data,
dataType: "json",
success: function (data) {
alert("Successfully Added New Student");
window.location = "../htdocs/allocate.php";
}
});
PHP part
if(!isset($_POST['stu_index'])){
echo '<script type="text/javascript">';
echo 'alert("Something Went Wrong.Please Try Again ");';
echo 'window.location = "../htdocs/add-stu.php";';
echo '</script>';
} else {
$cur_class=$_POST['txt_class'];
var_dump($cur_class);
}
My expected output of var_dump is string(5) "Grade 10", but real output is string(5) "Grade", what is issue of my code
I have a problem putting Onchange() on a ajax returned html on my form.
Basically I have clients listed in a select.
<select name="company" id="company">
<?php
$sqlget1 = "SELECT * FROM clients WHERE 1=1 ORDER BY company ASC;";
$resget1 = mysql_query($sqlget1);
while($row1 = mysql_fetch_array($resget1)) {
?>
<option value="<?php echo $row1['id']; ?>"><?php echo $row1['company']; ?></option>
<?php
}
?>
</select>
And when some one selects a client, im using Ajax to fetch projects that are assigned to that client.
$('#company').change(function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
It gets returned back to
<div id="response"></div>
The code for get_projects.php is
<?php
include('inc.php');
if(isset($_POST["projects"])) {
$projects = $_POST["projects"];
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
echo '<select name="project" id="project" class="select2 form-control">';
echo '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2)) {
?>
<option value="<?php echo $row2['id']; ?>" pstatus="<?php echo $row2['pstatus']; ?>" ptype="<?php echo $row2['ptype']; ?>"><?php echo $row2['pname']; ?></option>
<?php
}
echo '</select>';
}
?>
Now when i use on change function on the returned html from ajax it is not working.
I tried to see the source code and found out that it is not there atall. It only shows the <div id="response"></div>
But i can see the result on the form but cant see the source in the source code.
Hence i thought that's why the Onchange() is not working for <select name="project" id="project" class="select2 form-control"> because it is not showing.
I see, the data which is return from Ajax is object
You should parse it to get the raw content an set into DIV
When you are dynamically adding mark up to the page the javascript doesn't know about the controls you have added through php.
Try finding the newly added control like this:
var select = document.getElementById('project');
Then you should be able to fire your on change method
Not tested, but it should work
<?php
include('inc.php');
if(isset($_POST["projects"]))
{
$projects = $_POST["projects"];
$varOut = "";
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
$varOut .= '<select name="project" id="project" class="select2 form-control">';
$varOut.= '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2))
{
$varOut.= "<option value=" . $row2['id'] . " pstatus=". $row2['pstatus']. ">ptype=".$row2['ptype']."><".$row2['pname']."></option>";
}
$varOut.= '</select>';
}
echo $varOut;
?>
I've finally solved the issue.
Basicall i just pasted the Onclick() script for '#projects' inside the get_projects.php file.
So now every time when it comes from ajax it also brings the javascript as well.
When you use ajax, you add a piece of html later to the DOM (browsers view), because you use .change the onchange is only added to the '#company' elements wich already exist in the browser.
You need to bind the onchange after you appended the html. for example:
$('#company').change(function() {
onCompanyChange()
});
function onCompanyChange(){
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
$('#company').change(function() {
onCompanyChange()
});
});
}
OR
You can also use an on change, on change does work with elements added later to to the dom. so this code works with elements wich already exists and new added elements with for example ajax
$("#company").on("change",function(){
console.log("change");
});
Try below code. Hope this works fine.
$(document).ready(function() {
$(document).on('change', '#company', function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
});
I'm building my first Wordpress plugin and i'm having a little bit of trouble achieving the functionality I would like.
Essentially what I'm trying to do is save a dynamic array to options.php
I'll try and explain the functionality in a bit more depth. Basically, the user will select a post_type from a dropdown of all the available post_types including custom post types. Using jQuery, I'm detecting state changes on that dropdown to then post to a function in the plugin which will output all the available field_types associated with the selected post_type as labels and checkboxes.
https://www.dropbox.com/s/zacpvq85c5u9lrq/Screen%20Shot%202015-12-21%20at%2012.01.12.png?dl=0
https://www.dropbox.com/s/txyigfe81k0wd1i/Screen%20Shot%202015-12-21%20at%2012.01.23.png?dl=0
I can determine which checkboxes have been checked and create a javascript array of them, how do I then get this array, to wordpress and then have it saved as a preconfigured setting_field?
What I've got so far.
I output all the current post_types as part of a select input.
<select name="comparison_pt" id="comparison_pt" value="<?php echo get_option('comparison_pt'); ?>" value="<?php echo get_option('comparison_pt'); ?>">
<?php
$types = get_post_types(array());
$fields = get_fields();
foreach($types as $type) { ?>
<option value='<?php echo $type; ?>'><?php echo $type; ?></option>
<?php } ?>
</select>
Based on the selected option from the above dropdown
$('#settings_post_type').change(function() {
var selected_post_type = $('#settings_post_type option:selected').text();
$.ajax({
url: plugin_object.admin_url,
type: 'POST',
data: {
action: 'get_settings_field_values',
type: selected_post_type
},
success: function(response) {
console.log('AJAX POST => SUCCESS');
$('#settings_field_types').text('');
$('#settings_field_types').append(response);
},
error: function(response) {
console.log('AJAX POST => ERROR');
console.log(response);
}
});
});
I use the selected value as a WP_Query post_type parameter, returning only 1 post and using that to determine the available field_types for that post.
This outputs a number of labels and checkboxes as can be seen in the images provided, when they're clicked I have a function to detect which checkboxes are checked and then pushes them into an array e.g. var selected = ['population', 'growth_pa'];
I want to save this array in wordpress as an settings_field which is already predefined.
add_settings_field("comparison_ft", "Comparison Field Types", "display_fields_form_element", "plugin-options", "options_section");