Pass a JavaScript Variable to PHP for POST - javascript

I have 2 dropdown menus. I want to dynamically populate second dropdown based on the first one. When changing the value in first dropdown, it has to pass the selected value to an invisible php array to update it. So here is the problem: passing the js variable(strUser) to php {{ the php var }} (used {{}} only to make it more simple to see).
<form class="formatted-form" action="" method="POST">
<div class="message">
<?php ThemexInterface::renderMessages(isset($_POST['success'])?$_POST['success']:false); ?>
</div>
<table class="profile-fields">
<tbody>
<?php if(!ThemexCore::checkOption('user_location')) { ?>
<tr style="display: none">
<th><?php _e('Hidden Country', 'lovestory'); ?></th>
<td>
<div class="select-field">
<span></span>
<?php
echo ThemexInterface::renderOption(array(
'id' => 'country',
'type' => 'select',
'options' => array_merge(array('-' => '–'), ThemexCore::$components['countries']),
'value' => !empty(ThemexUser::$data['user']['profile']['country'])?{{ThemexUser::$data['user']['profile']['country']}}-this should be replaced with the strUser variable we get in js :null,
'wrap' => false,
));
?>
</div>
</td>
</tr>
<tr>
<th><?php _e('Visible_Country', 'lovestory'); ?></th>
<td>
<span>
<?php
$post_ids2 = $wpdb->get_col( "SELECT DISTINCT country FROM countries" );
echo "<SELECT id=tara_1 onChange='reload()' >";
foreach ($post_ids2 as $value){
echo "<option value=$value </option>";
echo $value;
}echo "</select>";
?>
</span>
</div>
</td>
</tr>
<script>
function reload(){
var e = document.getElementById("tara_1");
var strUser = e.options[e.selectedIndex].text;
}</script>
<tr>
<th><?php _e('City', 'lovestory'); ?></th>
<td>
<span>
<?php
global $wpdb;
$post_ids = $wpdb->get_col( "SELECT city FROM countries WHERE tara='".ThemexUser::$data['user']['profile']['country']."'" );
echo "<SELECT id=tara_1 name=cities>";
foreach ($post_ids as $value){
echo "<option value=$value </option>";
echo $value;
}echo "</select>";
?>
</span>
</div>
</td>
</tr>
<?php } ?>
<?php
ThemexForm::renderData('profile', array(
'edit' => true,
'before_title' => '<tr><th>',
'after_title' => '</th>',
'before_content' => '<td>',
'after_content' => '</td></tr>',
), ThemexUser::$data['user']['profile']);
?>
</tbody>
</table>
<?php _e('Save Changes', 'lovestory'); ?>
<input type="hidden" name="update" value="1" />
<input type="hidden" name="user_action" value="update_profile" />
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(THEMEX_PREFIX.'nonce'); ?>" />
</form>
I know php is server-side and js works on client-side, that's why i am confused on how could i dynamically refresh the second dropdown AND pass the value selected by user to PHP POST. I am new to PHP and JS so please be kind, i would appreciate any hint on how I should approch the problem. In the end i want it to behave like this:
Dropdown1 selected>Italy, Dropdown2 > {gets populated with italian cities from database}
Dropdown1 selected>France, Dropdown2 > {gets populated with frech cities from database}
Well, the real problem is passing JS to PHP- which i think is the wrong approach.
Thanks in advance.

Related

How to use PHP loop variable in javascript?

I have run an SQL statement to get all the records I need to show in a HTML table.
I have then run a while loop to display the records from the database. (The code for this is below.)
<table class="projects-table">
<tr>
<th>Complete?</th>
<th>Paid?</th>
<th>Project Name</th>
<th>£ / hr</th>
<th>End Date</th>
<th>Hours Logged</th>
<th><i class="fa fa-trash"></i></th>
</tr>
<?php
$select_id_jobs = mysqli_query($mysqli, "SELECT id FROM users WHERE username='$login_user'");
while($row = mysqli_fetch_array($select_id_jobs)) {
$id_jobs = $row['id'];
}
$select_jobs_with_usrid = mysqli_query($mysqli, "SELECT * FROM jobs WHERE username_id = '$id_jobs';");
while($row = mysqli_fetch_array($select_jobs_with_usrid)) {
?>
<tr id="<?php echo $rowId; ?>">
<td>
<!-- Complete Checkbox -->
<input type="checkbox" id="<?php echo $completeCheck;?>" onclick="compTask();">
</td>
<td>
<!-- Paid checkbox -->
<input type="checkbox" onclick="paidTask()">
</td>
<td>
<?php echo $row['project_title']; ?>
</td>
<td>
<?php echo $row['cost_hour']; ?>
</td>
<td>
<?php echo $row['completion_date']; ?>
</td>
<td>
<?php echo $row['time_spent']; ?>
</td>
<td>
<div class="delete-btn"><a onclick="deleteTask()">DELETE</a></div>
</td>
</tr>
<?php } ?>
</table>
As you can see from the checkbox for completing a task. What I want to do is use javascript so that when the checkbox is checked the text from the other records turns green.
I have included the javascript I am trying to use below. I don't know why but I can't access the inputs ID in order to change the css.
<script>
function compTask() {
if (document.getElementById("<?php echo 'complete-' . $row['id'] ?>").checked == true) {
document.getElementById("<?php echo 'tr' . $row['id']; ?>").style.color = "green";
alert("hello");
} else {
document.getElementById("<?php echo 'tr' . $row['id']; ?>").style.color = "black";
}
}
Okay easy way to do that is to print id as parameter in js function
something like that:
<input type="checkbox" id="<?php echo $completeCheck;?>"
onclick="compTask( '<?php echo $row['id'];?>' );">
and in js function deal with id from parameter:
function compTask(id) {
if (document.getElementById('complete-' + id).checked == true) {
document.getElementById('tr' + id).style.color = "green";
alert("hello");
}
}
Hy,
You need to add id in onclick="deleteTask('<?php echo $row['id']; ?>')">
Now in you function have id:
function deleteTask(id) { console.log(id) }

How to add a new element to a specific cell inside a table?

<?php session_start() ;
include 'databaseConnection.php' ;
$sqlCommand3 = "SELECT * FROM posts ;" ;
$result3 = mysqli_query($conn , $sqlCommand3);
$resultCheck = mysqli_num_rows($result3);
while ($row = mysqli_fetch_array($result3)) { ?>
<tr>
<td style="padding-left: 10px;">
<?php echo $row['poster']; ?>
</td>
<td style="padding-left: 45px;">
<?php echo $row['post_destination']; ?>
</td>
<td style="padding-left: 30px;">
<?php echo $row['post_readyTime']; ?>
</td>
<td style="padding-left: 45px;">
<?php echo $row['post_numberOfPassenger'];?>
</td>
<td style="padding-left: 32px;">
<?php echo $row['post_submitTime']; ?>
</td>
<td>
<form action="riderJoin.php" method="post">
<input type ="hidden" name ="id" value="<?php echo $row['post_id']; ?>" >
<input type =submit class="edit_btn" name = submit value = "Join">
</form>
</td>
<!--<td>
Delete
</td>-->
</tr>
<?php } ?>
</table>
</div>
</div>
<script type="text/javascript">
$("td:nth-child(4):contains('5')").addClass('redWord');
var x = document.getElementsByClassName('edit_btn');
<?php if (isset($_POST['submit'])) { ?>
var i = <?php echo $_SESSION['postId'] ; ?> - 1 ;
$(x[i]).val('Delete').css('background-color','red').css('color','white');
<?php }?>
</script>
How to add a new input (type = "submit" value="delete") with a new action (before the "join" button) whenever the $_POST['submit'] is set? I don't want to add a new input before each "join" button. Instead, I just want to add after a specific "join" button inside a cell when that specific "join" button is clicked. Also, if I click another 'join' button in other cell, a similar effect would happen too. So in the end, after clicking two "join" button, there should be only two delete button each added before the specific clicked "join" buttons. How to solve it ?
Thanks a lot :)

selected option fetch data from database in php

I want to fetch data from a database related to a selected option when it is clicked.
When I select another option then fetch the data for that selection.
When I fetch the new data option the old data is replaced.
I want to display each set of data in a new row so I do not want the new data to replace the old data.
<form action="" method="post">
<div class="form-group">
<label for="sel1">Select list:</label>
<select multiple name="names" class="form-control" id="sel1">
<?php
$result = "SELECT Name FROM coder";
$sql = $conn->query($result);
if ($sql->num_rows > 0)
while($row = $sql->fetch_assoc()) {?>
<option value='<?php echo $row['Name'] ?>'><?php echo $row['Name'] ?></option>
<?php }
?>
</select>
</div>
<input type="submit" name="submit" class="btn btn-info">
</form>
<table>
<thead>
</thead>
<tbody>
<?php
$result = "SELECT * FROM coder WHERE Name='$name'";
$sql = $conn->query($result);
if ($sql->num_rows > 0)
while($row = $sql->fetch_assoc()) {{?>
<tr>
<td><?php echo $row['Name']?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
I suggest to use jquery for binding the div once the result is placed inside it.
Also Instead of using direcy Query, you also can use onChange event of jQuery for fetching the data according to your need. It will accelerate the speed of fetching of data.
Divide the div into samall child divs and store the data into them.
Your problem will be resolved in this way for sure

php & js - add emails to input text

I am trying to send each member email generate from the php if condition to an input text. The selection works well however, the problem I have is to find a way if multiple checkboxes are selected the emails sums spacing them with a coma.
Right now what I have is that if I check multiple checkboxes the last email selected replaces the old one.
Any Idea how Could I do this? Also if just one email is selected no coma have to be added and if the checkbox is unchecked the email is removed.
<?php if ( bp_has_members( "search_terms={$_POST['category']}")) : ?>
<?php while ( bp_members() ) : bp_the_member(); ?>
<table border="1" >
<tr>
<td style="width:30px;">
<input class="select_email" type="checkbox" name="get_email" value="<?php bp_member_user_email('type=user_email') ?>"/>
</td>
<td>
<?php bp_member_user_email('type=user_email') ?>
</td>
</tr>
</table>
<?php endwhile; ?>
<?php endif; ?>
Jquery
$(document).ready(function(){
$(".select_email").click(function(){
var select_check = $(this);
var select_email = $(this).parent().find(".select_email").val();
//var sum_email = select_email + ", " + select_email;
if ( select_check.is(':checked') ) {
// Do stuff
alert(select_email + " added");
$("#my_email_to_id").val(sum_email);
}else {
alert(select_email + " removed");
}
});
});
<?php if ( bp_has_members( "search_terms={$_POST['category']}")) : ?>
<?php while ( bp_members() ) : bp_the_member(); ?>
<table border="1" >
<tr>
<td style="width:30px;">
<input class="select_email" type="checkbox" name="get_email[]" value="<?php bp_member_user_email('type=user_email') ?>"/>
</td>
<td>
<?php bp_member_user_email('type=user_email') ?>
</td>
</tr>
</table>
<?php endwhile; ?>
<?php endif; ?>
Jquery
$(document).ready(function(){
$(".select_email").click(function(){
var val = $(':checkbox:checked').map(function(){ return this.value; }).toArray().join(', ');
alert(val);
$("#my_email_to_id").val(sum_email);
});
});

Cart is updated only once using Jquery and Codeigniter

I am working on Updating Codeigntier Cart with Jquery using Ajax call to update. Here is my jquery function
$(function() {
$('.cart_form select').on('change', function(ev) {
var rowid = $(this).attr('class');
var qty = $(this).val();
var postData_updatecart = {
'rowid' : rowid,
'qty' : qty
};
//posting data to update cart
$.ajax({
url : base_url + 'bookings/update_booking_cart',
type : 'post',
data : postData_updatecart,
beforeSend : function() {
$('#cart_content').html('Updating...');
},
success : function(html) {
//window.location.href = "postproperty.php?type="+suffix+'&page=page1';
$('#cart_content').html(html);
}
});
});
});
I have cart view file as
<div class="cart_form">
<?php echo form_open(base_url().'index.php/bookings/customerdetails', array('class' => 'bookings_form_customer', 'id' => 'bookings_form_customer')); ?>
<table cellpadding="6" cellspacing="1" style="width:100%" border="0">
<tr>
<th style="text-align:left">Item Description</th>
<th style="text-align:left">QTY</th>
<th style="text-align:right">Item Price</th>
<th style="text-align:right">Sub-Total</th>
</tr>
<?php $i = 1; ?>
<?php foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>
<tr>
<td>
<?php echo $items['name']; ?>
<?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>
<p>
<?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />
<?php endforeach; ?>
</p>
<?php endif; ?>
</td>
<td>
<select name="<?php echo $i.'[qty]'; ?>" class="<?php echo $items['rowid']; ?>">
<?php
for($tt=0; $tt<=10; $tt++)
{
?>
<option value="<?php echo $tt; ?>" <?php if($tt==$items['qty']) echo 'selected="selected"'; ?>><?php echo $tt; ?></option>
<?php
}
?>
</select>
</td>
<td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td>
<td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="2"> </td>
<td class="right"><strong>Total</strong></td>
<td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
</tr>
</table>
<p><?php echo form_submit('update_cart', 'Update your Cart'); ?></p>
</form>
</div>
Things are working Nice. But, lets say if I have 2 products, if i select one item's qty from 1 to 2, cart is updated and updated cart is shown using AJAX. But, if I immediately change another item's qty then it doesnt work.
The cart view file is inside class 'cart_form'.
Helping hands are appreciated.
I got an answer. You can refer below link
Ajax Request works only once
OR
Directly follow this
REPLACE jquery code part by
$(function() {
$(document).on( "change", "#bookings_form_customer select", function(ev) {
// your code goes here
});
});

Categories