Wordpress Ajax not working? - javascript

I am developing plugin in wordpress, i used select tag element, i need the value to be stored in the database on change the option values , but it seems ajax is not working .below is my code ,
this is script code
function ajaxFunction(str,id) {
var payment_selected = str;
var id=id;
var queryString = "&id_took=" + id + "&sel=" + payment_selected;
jQuery.ajax({
var data = { 'action' : 'my_action',
'queryString':queryString
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
}
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
/*below one i have written in my plugin code */
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['id_took'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
if($whatever2=="Payment completed")
{
$result_pay = $wpdb->query("UPDATE $table_name_payment SET
payment_status = $id_selected
WHERE id = $id ");
echo "success";
}
}
?>

Your use of jQuery.ajax seems wrong. Try without wrapping the code with jQuery.ajax like this:
Javascript
function ajaxFunction(str,id) {
var data = {
'action' : 'my_action',
'id_took': id,
'sel' : str
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
HTML
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
PHP
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id = $_POST['id_took'];
$str = $_POST['sel'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
if($whatever2=="Payment completed")
{
$result_pay = $wpdb->query("UPDATE $table_name_payment SET
payment_status = $sel
WHERE id = $id ");
echo "success";
}
}
?>

Related

Ajax Success Returning Commented Html Tag

I am trying to set up a select box that would show up the cities depending on the prior selection of the state.
Basically, I am using ajax to run my php.file to populate my <option>. In the php file I successfully passed the pre-selected state to query the database. However, now, to populate the <option> I am using ajax success to call the php file, however, whenever I try to pass the variable containing the php code it shows up commented with !-- and --.
// hmtl
<select id="select-city" required >
<option disabled selected>Selecione sua Cidade</option>
</select>
// js code
function fillSelectCity () {
var getState = document.getElementById('selectState');
var stateID = getState.options[getState.selectedIndex].value;
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (){
var phpfile = "'fillcity.php'"
var tag = "<?php include_once " + phpfile + " ?>";
$('#select-city').html(tag);
/// here the output is "<!-- ?php include_once 'fillcity.php' ? -->"
}
})
}
//php file
<?php
$conn = mysqli_connect("host", "user", "pass", "db");
if(isset($_POST['stateID']))
{
$stateID = $_POST['stateID'];
}
$query = "SELECT * FROM states WHERE stateID = '$stateID'";
$result_one = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result_one); //my table has a specific ID for each state, so I am fetching the acronoym of the state according to the id;
$stateUf = $row['uf']; // passing the acronym to the $stateUf
mysqli_free_result($result_one);
$queryCity = "SELECT * FROM city WHERE Uf = '$stateUf'"; //query all cities with the acronym
if ($result = mysqli_query($conn, $queryCity)){
while ($row = mysqli_fetch_assoc($result)){
$id = $row['cityID'];
$name = $row['cityName'];
$name = utf8_encode($name);
echo <<< EOT
"<option value="$id">$name</option>"
EOT;
}
mysqli_free_result($result);}
else {echo "<option>Error</option>";}
?>
I expect to populate my select options by looping through the table city in the php file. The tag <?php include_once 'fillcity.php' ?> was used to populate the state select. Probably, there may be a more direct way to populate accordingly, but as I am new to programming, I am trying to figure things out on my own. But please, feel free to recommend other methods as I am not sure if what I am planning to do will gonna work. Thanks!
You can try this one. You can modify it later for improvement.
read.php
<?php
//include header
header('Content-Type: application/json');
$conn= mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$type = $_GET["type"];
if($type == "GetState"){
//SAMPLE QUERY
$sql = "SELECT StateID,StateName from State";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
if($type == "GetCity"){
$StateID= $_POST["StateID"];
//SAMPLE QUERY
//LET'S ASSUME THAT YOU HAVE FOREIGN KEY
$sql = "SELECT CityID,CityName from City where StateID = '".$StateID."'";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
?>
index.html
<select id="state"></select>
<select id="city"></select>
<!--PLEASE INCLUDE JQUERY RIGHT HERE E.G. <script src='jquery.min.js'></script>-->
<!--DOWNLOAD JQUERY HERE https://jquery.com/-->
<script>
LoadState();
function LoadState(){
$.ajax({
url:"read.php?type=GetState",
type:"GET",
success:function(data){
var options = "<option selected disabled value="">Select
State</option>";
for(var i in data){
options += "<option value='"+data[i].StateID+"'>" + data[i].StateName+ "</option>";
}
$("#state").html(options);
}
});
}
function LoadCity(StateID){
$.ajax({
url:"read.php?type=GetCity",
type:"POST",
data:{
StateID: StateID
},
success:function(data){
var options = "<option selected disabled value="">Select City</option>";
for(var i in data){
options += "<option value='"+data[i].CityID+"'>" + data[i].CityName+ "</option>";
}
$("#city").html(options);
}
});
}
$("#city").change(function(){
LoadCity(this.value);
});
You don't need to include 'fillcity.php. The AJAX call runs that script, and the response is the output. It will be in the parameter of the success function.
function fillSelectCity () {
var getState = $("#selectState").val();
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (tag){
$('#select-city').html(tag);
}
});
}

how to do update using ajax jquery in wordpress?

i am developing plugin where i have to update the single record onchanging the select option element , i tried using wordpres codex way ,but i am struck can please anyone help me out here, below is my code
function ajaxFunction(str,id) {
var payment_selected = str;
var id=id;
var queryString = '&id_took='+id+'&sel='+payment_selected;
var data = {
'action' : 'my_action',
'payment_selected': payment_selected,
'id' : id
};
jQuery.post(admin_url("admin-ajax.php"), data, function(response) {
jQuery("#status").html(response);
});
}
/* this is a php file , i used in the plugin where below html form appears */
<?php
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['payment_selected'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
$result_pay = $wpdb->query($wpdb->prepare("UPDATE $table_name_payment SET payment_status = $id_selected WHERE id=$id"));
echo "success";
?>
/* this is the html file */
foreach ($rows as $row) { ?>
<table>
<td><?php echo $row->payment_status; ?></td>
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
<?php } ?>
<table>
<div id="status"></div>
function ajaxFunction(str,id) {
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
'action' : 'my_action',
'payment_selected': payment_selected,
'id' : id
},
success: function (response) {
if(response=='success'){
jQuery("#status").html(response);
}
}
});
}
PHP Code,
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['payment_selected'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
$result_pay = $wpdb->query($wpdb->prepare("UPDATE $table_name_payment SET payment_status = $id_selected WHERE id=$id"));
echo "success";
}
?>
HTML code,
<?php foreach ($rows as $row) { ?>
<table>
<tr><td><?php echo $row->payment_status; ?></td>
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
<?php } ?>
</td></tr>
<table>
<div id="status"></div>
Hope this will helps you.
well i tried in my own way its working fine for me, below is my answer
function ajaxFunction(str,id) {
var payment_selected = str;
var id=id;
var queryString = '&id_took='+id+'&sel='+payment_selected;
var data = {
'action' : 'my_action',
'payment_selected': payment_selected,
'id' : id
};
jQuery.post(ajaxurl, data, function(response) {
jQuery("#status").html(response);
});
}
/* write this php function outside of all the function*/
<?php
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['payment_selected'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
// $result_pay = $wpdb->query($wpdb->prepare("UPDATE $table_name_payment SET payment_status = $id_selected WHERE id = $id"));
$result_pay = $wpdb->update(
$table_name_payment, //table
array( 'payment_status' => $id_selected), //data
array('id' => $id) //data format
);
}
?>
foreach ($rows as $row) { ?>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<td>
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
</td>
<div id="status"></div>
<?php } ?>

the event of onchange at select control at php, trigger issue

I used this select which show counteries
<section class="shipping-calculator-form-shortcode" >
<p class="form-row form-row-wide" id="calc_shipping_country_field">
<label >Shipping options to</label>
<select onchange="myFunctionShipping(this)" name="calc_shipping_country" id="calc_shipping_country" class="ss-woo-shipping-calculator" rel="ss-woo-shipping-calculator">
<option value="1"><?php _e( 'Select a country…', 'woocommerce' ); ?></option>
<?php
foreach ( WC()->countries->get_shipping_countries() as $key => $value )
echo '<option value="' . esc_attr( $key ) . '"' . selected( WC()->customer->get_shipping_country(), esc_attr( $key ), false ) . '>' . esc_html( $value ) . '</option>';
?>
</select>
</p>
<span id="ss-woo-shipping-calculator-loading" style="display:none"><img src='<?php echo plugins_url( '/default.gif', __FILE__ ) ?>' /></span>
</p>
<?php wp_nonce_field( 'woocommerce-cart' ); ?>
<div id="ss-woo-shipping-result">
</div>
</section>
then by javascript code to retrieve the shipping options for it
<script type="text/javascript">
var $s = jQuery.noConflict();
function myFunctionShipping(item) {
$s(document).ready(function($) {
$("select").change(function(){
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var country = item.value;
$("#ss-woo-shipping-calculator-loading").show();
var data = {'action': 'ss_woo_shipping_calculator','country': country};
$.post("<?php echo get_home_url(); ?>", data, function(response) {
$("#ss-woo-shipping-calculator-loading").hide();
response = JSON.parse(response);
if(response.result == 1){
$("#ss-woo-shipping-result").html(response.message);
}else{
$("#ss-woo-shipping-result").html("");
}
return false;
});
return false;});
});
}
the problem that:- it trigger if also any other select control changed
also it is only trigger after changing the selection twice (after page loading)
It "says" that action apply to any select $("select").change(). You can change to limit action only to select with chosen id like
$("#calc_shipping_country").change(function()
or you can choose to use select class name.
EDIT.
My mistake, I didnt figure out that the action is called by function and not select action. Try to remove completely the $("select").change(function() wrap and make look something like this
<script type="text/javascript">
var $s = jQuery.noConflict();
function myFunctionShipping(item) {
$s(document).ready(function($) {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var country = item.value;
$("#ss-woo-shipping-calculator-loading").show();
var data = {'action': 'ss_woo_shipping_calculator','country': country};
$.post("<?php echo get_home_url(); ?>", data, function(response) {
$("#ss-woo-shipping-calculator-loading").hide();
response = JSON.parse(response);
if(response.result == 1){
$("#ss-woo-shipping-result").html(response.message);
}else{
$("#ss-woo-shipping-result").html("");
}
return false;
});
return false;
});
}
</script>

Receive post data ajax with php

I'm trying to receive post data with php from ajax in same page but seems like i have some issues that i have no idea to solve them
here is my html/php code :
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php
while ($row = $result->fetch_assoc())
{
echo "<option value=".$row['N_omran'].">".$row['N_omran']."</option>";
}
?>
</select><br>
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row) {
echo " <h4>Nom : {$row['nom']}</h4>
<h4>Prénom : {$row['prenom']}</h4>
<h4>Téléphone : {$row['tel']} </h4>
<h4>Maticule d'assurance : {$row['matricule_assu']}</h4>
<h4>Adresse : {$row['adress']}</h4>";
}
} ?>
And here is my Ajax post request :
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function () {
alert("Post request successfully done")
}
});
}
});
the code below can replace all your data with the new ones with clean writing :)
// get data from Database
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
} ?>
// show rows to be selected
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?= $row['N_omran'] ?>"> <?= $row['N_omran'] ?></option>
<?php } ?>
</select><br>
// show recieved data
<?php if ($row) { ?>
<div id="informations">
<h4>Nom : <span id="nom"><?= $row['nom'] ?></span></h4>
<h4>Prénom : <span id="prenom"><?= $row['prenom'] ?></span></h4>
<h4>Téléphone : <span id="tel"><?= $row['tel'] ?> </span></h4>
<h4>Maticule d'assurance : <span id="matricule_assu"><?= $row['matricule_assu'] ?></span></h4>
<h4>Adresse : <span id="adress"><?= $row['adress'] ?></span></h4>
</div>
<?php } ?>
// script for making ajax call
<script>
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function (response) {
$("#nom").text(response.nom);
$("#prenom").text(response.prenom);
$("#tel").text(response.tel);
$("#matricule_assu").text(response.matricule_assu);
$("#adress").text(response.adress);
}
});
}
});
</script>
$json_data=file_get_contents('php://input');
$json=json_decode($json_data,true);
if(array_key_exists("selectName",$json)){
$selectOption =$json["selectName"];
}

Why isn't my ajax code updating my second dropdown?

I have no idea why my code isn't working. I basically have two dropdowns, the first is populated from an mssql database and I want the second dropdown to update dependant on the selection in the first.
Below is my code which populates a dropdown box:
<?php
session_start();
$serverName = "REDACTED";
$connectionInfo = array( "Database"=>"REDACTED", "UID"=>"REDACTED", "PWD"=>"REDACTED");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if (!isset($_SESSION['nID']))
{
header("Location: Login.php");
die();
}
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['region']."</option>";
}
return $output;
}
?>
I then use this to populate the first dropdown:
<p>Select a Region
<select name ="region" id ="region">
<option value ="">Select Region</option>
<?php echo loadRegion(); ?>
</select></p>
For the second dropdown box I have the following:
<p>Select a Territory
<select name="territory" id="territory">
<option value="">Select Territory</option>
</select></p>
I call my ajax via:
<script>
$(document).ready(function(){
alert("ready");
$('#region').change(function(){
var region_id = $(this).val();
$.ajax({
url:"getter.php",
method:"POST",
data:{regionId:region_id},
dataType:"text",
success:function(data){
$('#territory').html(data);
}
});
});
});
</script>
My getter page reads as follows:
<?php
session_start();
include 'config.php';
$output = '';
$sql = "SELECT distinct id,territory,rid FROM territoriesHaiss where RID = '".$_POST["regionId"]."' order by id";
$result = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$output = '<option value ="">Select Territory</option>';
while($row = sqlsrv_fetch_array($result))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['territory']."</option>";
}
echo $output;
?>
As pointed out by the 2 comments above (thanks again for the help!) the error was in the code that populates the first dropdown. It should have been a lowercase 'ID', like follows:
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['id'])."\">".$row['region']."</option>";
}
return $output;
}
?>

Categories