javascript, ajax to PHP - javascript

I have this in my code and it doesnt work, please help me guys, I want to try passing the value when i pull from the dropdown, it process the data by onChange and showing the value in the tag
<label for="headmark" class="lbl-ui select">
<select id="headmark" name="headmark" onChange="getVal(this)">
<?php while (oci_fetch($headmark_parse)){?>
<option value="<?php echo $head_mark ?>" id="headmark">
<?php echo "$head_mark"; ?></option>
<?php } ?>
</select>
</label>
<script type="text/javascript">
function getVal(val){
$.ajax( {
type: 'POST',
url: update_fab_progress.php,
data: "&val=" + val,
success: function(data) {
alert("data");
}
} );
}
</script>
<?php
echo $_POST['val'];
?>

Use chrome developer tool to help you debug. I think your parameter 'val' in javascript is a little strange. May be, you send a request with empty parameter.

Related

I have a problem while fetching date in "class in C:\xampp\htdocs\ERP\std.php on line 4" from ajax code

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>

Ajax call Not Working in Custom plugin

I am creating a plugin to display all post types in a drop down and another select box to display the corresponding categories (taxonomies) of each post type. When the post type is changed the corresponding categories are selected via an ajax call.
This is my code:
add_action('admin_menu', 'taxonomy_menu');
function taxonomy_menu(){
add_menu_page( 'Taxonomy Plugin', 'Custom Taxonomy Plugin', 'manage_options', 'custom-taxonomy-plugin', 'tax_settings' );
}
function tax_settings(){
$url = plugin_dir_url().'cust-taxonomy/ajax_tax.php';
$taxo = get_taxonomies();
var_dump($url);
?>
<form method="POST" action="">
Post Type<select class="taxonomy">
<?php
foreach ( get_post_types() as $post_type ) {
?>
<option value="<?php echo $post_type;?>"><?php echo $post_type;?></option>
<?php } ?>
</select><br>
Categories<select>
<option value="">Select</option>
</select><br>
No: of posts<input type="text" name="num_posts"><br><span></span>
<input type="submit" name="submit" value="submit">
</form>
<?php
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".taxonomy").change(function(){
var post_type = this.value;
alert(post_type);
jQuery.ajax({
type:'POST',
url:"<?php echo plugin_dir_url().'cust-taxonomy/ajax_tax.php';?>",
data: post:post_type,
success:function(result){
alert(result);
}
});
});
});
</script>
Here no AJAX call is going to the corresponding URL. Why is that?
I could see that there is a syntax error in the call to jQuery.ajax(). The argument that you are passing is not a proper java script object. You need to enclose post: post_type with curly braces as shown below.
jQuery.ajax({
type:'POST',
url:"<?php echo plugin_dir_url().'cust-taxonomy/ajax_tax.php';?>",
data: {post:post_type},
success:function(result){
alert(result);
}
});
You can't use plugin_dir_url without argument.
Use this format instead;
plugin_dir_url(__FILE__).'cust-taxonomy/ajax_tax.php';

How to put Onchange on Ajax returned html select

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

PHP and AJAX Loading Data

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.

Ajax call after changing the value of a 'option' tag

I am facing a little problem using ajax.
I need when I change the value of 'select' tag's 'option' then it will call ajax and the value which I get from the ajax call will show in 'input' tag named 't_name'. But its not working. What the problem in my code?How can I solve it? thank you.
Below is my code :
<select id="teacher_select" class="teacher_select" name="teacher_select" value="Select Teacher">
<option value="">Select Teacher</option>
<?php
while($row=mysql_fetch_assoc($teacher) ):
?>
<option value="<?php echo $row['t_id'];?>"><?php echo $row['t_name'];?></option>
<?php
endwhile;
?>
</select>
<input type="text" name="t_credit" id="t_credit"/>
Ajax :
$('#teacher_select').click(function(){
$.ajax({
type:'post',
url:'get_taken_credit.php',
data: 't_id='+ $('#teacher_select').val(),
success: function(reply_data){
$('#t_credit').html(reply_data);
}
});
});
get_taken_credit.php :
include('db_connection.php');
$t_id = $_POST['t_id'];
$result = mysql_query("SELECT t_credit FROM teacher WHERE t_id = '$t_id'");
echo $result;
exit();
It seems that the id is wrong, you call #teacher_select instead of #dept_select, and try to use
$('#dept_select').change(function () {
instead of
$('#teacher_select').click(function () {

Categories

Resources