get closest input from select and place it in $.post - javascript

Okay. please see bottom screenshot for illustration on frontend. What i'm trying to do here is when the user makes a selection in the select form ie: selects Received, I want to get the value of the inputbox directly on the bottom of the select form and send it via $.post to another script in order for me to process it.
I can't seem to get the data pass over via $.post to read the value in the inputbox. Main focus should be at the $.post area. I tried using $('.order_item_id').val(); in my $.post data but i only get the value under the first inputbox regardless of whichever selectbox i make the selection from.
Here is the section of my javascript and php.
.js
$('.order_stat_sel').change(function(){
var closest_div=$(this).closest('div.order_receipt');
var closest_selectbox=$(this).closest('.order_stat_sel');
if($('.select_received:selected').length>0){
if(confirm('Confirm Receipt of this item?')){
$.post("/seller/buyer_cfm_receive.php",{order_item_id: $(this).closest('.order_item_id').val()}, function(data) {
alert("Congrats, Order Item Completed" + data);
closest_div.append('<p>Completed</p>');
closest_selectbox.remove().fadeOut("slow");
});
}else{
$('.order_stat_sel').val('p');
}
}
});
php
if($this->orderstatuses[$item->order_status]!='received'){
echo '<select class="order_stat_sel" name="order_status">';
echo '<option class="select_pending" value="'.$pendingitem_state[2].'">'.$pendingitem_state[3].'</option>';
echo '<option class="select_received" value="'.$enditem_state[2].'">'.$enditem_state[3].'</option>';
echo '</select>';
}?>
<form class="send_order_cfm_input">
<input class="order_item_id" name="order_item_id" value="<?php echo $item->virtuemart_order_item_id;?>" type="text" readonly="readonly">
</form>
Any help appreciated

.closest() finds the closest ancestor of the element, but you are actually searching for a descendant of a neighbour:
$.post("/seller/buyer_cfm_receive.php",
{
order_item_id:$(this)
.next(".send_order_cfm_input")
.find('.order_item_id').val()
},
function() {
/*...*/
}
);

Related

PHP/Javascript - Change 2nd Select element based on selection in first Select element and retain selections through POST & page reload

First SELECT:
<?php
function select_size($itemSizes){
echo "<select id=\"size\" name=\"size\">";
$sizes = array("0" => "All Sizes","1" => "Large","2" => "Medium","3" => "Small");
foreach($sizes as $s => $si){
if($itemSizes == $s){$selected = "selected";}
echo "<option value=\"" . $s . "\" $selected>" . $si . "</option>\n";
$selected = "";
}
echo "</select>\n";
}
?>
Second SELECT:
$(document).ready(function() {
$("#eventCategory").change(function() {
var val = $(this).val();
$("#eventType").html(options[val]);
});
var options = ["
<option value='all_items'>ALL Items</option>
<option value='red'>red</option>
<option value='blue'>blue</option>
<option value='green'>green</option>
];
});
First select retains value due to PHP. onChange is working properly as once a value in Select #1 is chosen, Select #2 populates with it's appropriate list. The problem I'm having is Select #2 is not retaining it's value through a POST and page reload. I've worked out a bit of JS that does this but it fouls up the onChange function. I'm trying to achieve both at the same time and have failed thus far. Yes, I'm an amateur with JS. Pretty good with many other languages. The syntax is causing me troubles. Any assistance is greatly appreciated.
You can send an ajax when first select triggers onChange event.
Then, on the success of this Ajax, you can get values from php and changing the second one. As you are using ajax, the first option will not be modified.
As you asked for "reloading page" you will need to print a script in the view that browsers can render, this can look like:
if you can know the ID of each option (if any):
echo "<script> $('#selector1 option#'.$idOption.').attr('selected', 'selected'); </script>";
if you can't know the ID of each or there are any id to catch, you'll get the value for sure, the script will look like:
$('#selector1 option[value="'.$value.'"]').attr("selected", "selected");
where in the first case $idOption is the id of the option selected on first selector and retrieved from php. $value in the second script is.. well, the value.
don't really know if there solves your entire problem as i can only see a part of your code, i'll edit it if you provide feedback.
Maybe you would var_dump / console.log values for getting a backtrace of your data and see where it's lost to ensure you pass the needed data around your functionallity.

Unexpected results form jquery

I have an ajax call under a function called refreshClick that is meant to fill a div with a select box that is generated by php.
Javascript:
function refreshClick() {
$.ajax({
url: "modules/elements/customersList.php",
success: function(data){
$('#refreshdiv').html(data);
}
});
}
HTML:
<div id="refreshdiv">test</div>
PHP:
while($row = $result->fetch_assoc()){
$returnString .= '<option value="'.$row['customerid'].'" data-tokens="'.$row['Phone'].$row['customerid'].$row['Email'].$row['ID'].$row['alt1Name'].$row['alt1Info'].$row['alt2Name'].$row['alt2Info'].'">'.$row['Name'].'</option>';
}
echo '<select data-live-search="true" class="selectpicker form-control" data-selected-text-format="count > 1" style="width:100%" name="customer">';
echo $returnString;
echo '</select>';
So as you can see this code is pretty simple. I cannot for the life of my figure out whats going wrong. I have a button just above the refreshdiv div that calls the refreshClick() function, but when I click it the word test disappears. It LOOKS like it just clears out the div, but if I Inspect Element, I can see that the div was filled the way it was suppose to be, with the correct data aswell, but nothing is visable. Could someone help me figure out where I am going wrong?
Side note: The reason I want to use it this way is so I can call this function any time to refresh the contents of the select box, so that way if whoever is using the software updates the customer list they can refresh the select box without refreshing the page. If there is an easier way to do this, please enlighten me.
--Test data screenshot
This is console.log(typeof data) and console.log(data)
--Inspect element screenshot
(Ignore the hideous refresh button, it's temporary.) I would also like to include, in the page before I click the refresh button the word "Test" shows in the refreshdiv div. It DOES show.
Oh, you are using bootstrap. That's the problem. Bootstrap needs to init every select. It does on startup, but every time it changes you need to run:
$(select).selectpicker('refresh');
To re-init the new ones.

dynamically add a dropdpwn based on value inserted in autocomplete textbox

Please someone help, I am really stuck on this for 2 days :|
I have a PHP form and I would like to enable user select movies by title, or by actors.
So, I was thinking about a dropdown menu by these values (moviebyTitle, moviebyActor). For selecting movies by title, I used jQuery auto-complete which get movie titles from my DB and it works fine.
This is my code:
<select id="selectType" name="source">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
</select>
<input type="textbox" name= "tag" id="tags">
<div id="byActor" class="style-sub-1" style="display: none;" name="stylesub1" onchange="ChangeDropdowns(this.value)">
<select name="films[]" multiple="multiple" width="200px" size="10px">
<?php
include('moviedropdown.php');
?>
</select>
and here is the javascript:
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2
});
$("#selectType").change(function () {
if ($(this).val() == "byTitle")
$("#tags").autocomplete("option", "source", "filmsauto.php");
else
if ($(this).val() == "byActor")
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#movieImdbId").html(response);
});
}
});
}
});
});
</script>
EDIT:
and this is the actions.php: (please kindly see also javascript part above)
<?php
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
// Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];
//$sql = fetchResults($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.
//I added this part to fetch data from DB
include('imdbConnection.php');
$sql = $conn->prepare('SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q');
$sql->execute(array(':q' => $q));
$html = "";
while($row = $sql->fetchAll(PDO::FETCH_OBJ)){
$option = '<option value="' . $row->movieImdbId . '">' . $row->movieImdbId . '</option>';
$html = $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
My question:
I just wonder how can I add a drop down list based on the value user has typed in the textbox. For example, if user wrote "Tom Cruise" in the auto-complete textbox, a dropdown will be added that shows movies in which "Tom Cruise" has played. (I make a COMMENT in the JavaScript code where I had problem)
I really searched a lot, but all samples where to dynamically populate some dropdown (like this one, or adding a textbox based on value selected in dropdown...
Please help, I really don't mean someone write the code for me, I just want to find any sample or some way that I can learn how to do it.
Thanks,
You should have something like the following.
What you actually need is when you type into the auto complete box and select something, you need to get a hold of that value for later use. After that, you need to call the server (a php script) with an ajax call and send that value from the autocomplete box along with the value from the drop down (only if you need to). That php script will need to generate a pile of something like the following in loop and save the whole html in a variable.
<option value='v1'>Value1</option>
<option value='v2'>Value2</option>
After that, send that back to the calling ajax script and then you need to put this as the content inside that drop down that you're trying to populate.
Here's some sample code on how to accomplish the javascript part.
<select id="filmsdd" name="films[]" multiple="multiple" width="200px" size="10px">
</select>
<script>
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#filmsdd").html(response);
});
}
});
});
<script>
EDIT:
path/to/somefile.php would be any file which is stored in your directory along with other website files. let's call it actions.php (I have updated the $.post ajax call)
When $.post runs, it will send a request to actions.php along with two variables q and q2. These variable names can be anything.
q contains the selected value from the auto complete box.
q2 contains the selected type from the drop down.
in actions.php, you end up with something like this.
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
// Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];
$sql = fetchResuls($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.
// Initialize a variable that you will send back to your ajax call, its still waiting for this script to be completed.
$html = "";
// Assuming your function returned a list of objects. Loop through the records.
while($row = mysql_fetch_object($sql)){
$option = '<option value="' . $row->property_id . '">' . $row->property_name . '</option>';
$html .= $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
I hope this helps.
The real question is, what's the point of the second drop down box. Why dont you just display all of the movies in a "table" once they've selected the actor.
I'd suggest a unified "Search" box, and on the PHP side, querying both your movies and actors, displaying all results that way?
If they choose a autoComplete value that is of type actor, display all the actor's movies. If they select an autoComplete value that is of type "movie" - display all the movies.
Effectivly - you're eliminating the By Actor or By Movie radio in favor of a better search bar.

How to call ajax by jquery on multiple checkboxes?

I have multiple (number may go as high as 500) checkboxes, as follows
<?php
$duplicate_checked='';
if ($repeat==1)
{
$duplicate_checked=' checked';
} else {
$duplicate_checked='';
}
?>
<input type="checkbox" name="isrepeat-<?php echo $id_no; ?>" id="isrepeat-<?php echo $id_no; ?>" class ="class_isrepeat" value="<?php echo $id_no;?>" <?php echo $duplicate_checked;?> onclick="updateRepeat(this.checked,<?php echo $id_no;?>);"/><label for="isrepeat-<?php echo $id_no; ?>">Is a duplicate Question?</label>
I want to update the value of Repeat column of the particular question number ($id_no, in this e.g.) in mysql database (e.g. named Qbank) on change of checked value of that checkbox.
I am able to successfully get checked value in javascript function updateRepeat(value, ques_no); But I couldn't get a way to call ajax by javascript.
In jquery this can be done something like -
$('#isrepeat-{question no}').change(function() {
$.post('update_repeat.php', {ques_no: question_number, repeated: checkbox_value_integer},
function(data){
$("#result").html(data);
});
});
Edit - 1. #isrepeat-{question no} represents id tag of the checkbox depending on question number eg, #isrepeat-1, #isrepeat-2, #isrepeat-3 etc.
But, This would require definite question number in "#isrepeat-{question-no}". I dont know how to construct this jquery in a way that it automatically picks question no and checked property for any particular checkbox clicked.
If I use class, instead of id for checkboxes then, how can i get question number and checkbox checked value for any checkbox in a single function?
Also, although I have a basic Idea what should be in update_repeat.php for ajax call, it would be nice if you could give any way by which this update can be easily done in ajax.
thanks.
regards,
Firstly, you are correct by utilizing class as selection to trigger the function. You can then continue by calling $(this) within the trigger callback to utilize the document object for each particular checkbox user clicked on.
Then just use .attr to get an input attribute that stores some information.
Which makes the code into
$('.class_isrepeat').change(function() {
question_number = $(this).val();
checkbox_value_integer = $(this).prop('checked');
$.post('update_repeat.php', {ques_no: question_number, repeated: checkbox_value_integer}, function(data){
$("#result").html(data);
});
});

Can't get form's select element value using jQuery

I am able to get input element's value using
var flt=$("#flt"+rowID).val();
but cannot get select elements value
here is my php code
<?php
$AC= & getAC();
while ($rowAC=mysql_fetch_array($AC)){
$i++;
if ($rowAC['acode']==$row['TPE']){
echo "<option value='{$rowAC['acode']}' selected='selected'>{$rowAC['name_ru']}</option>";
}else{
echo "<option value='{$rowAC['acode']}'>{$rowAC['name_ru']}</option>";
}
}
?>
I am generating list using this php code but
cannot even getting it's text value coding in such a way
var tpe=$("#tpe option[value='2']").text();
window.alert(tpe);
I am concerned only to get it's option value!!!
How to get it???
After some quick testing, it appears that value() only works on the select element itself. To get the value of the different option elements, you can use attr('value') on the option elements themselves.
Very quick demo: http://jsfiddle.net/y9Dqg/2/

Categories