Echo PHP based on form selection jQuery .post AJAX - php

I'm using jQuery to send an AJAX request after a selection is made on a form, and I want echo back different things into a div depending on what selection is made. Here is my form:
<form name="myform" id="myform" method="post" action="#">
<select name="myselect" id="myselect">
<option>-- Make a selection --</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</form>
Here is the javascript earlier in the page:
$(document).ready(function() {
$('#myselect').change(function() {
$(this).parents("form").submit();
});
$('#myform').submit(function() {
$.post(
'myscript.php',
$(this).serialize(),
function(data){
$("#mydiv").html(data)
}
);
return false;
});
});
And here is myscript.php:
<?php
if ($_POST['myselect'] = "1") {
echo "Div contents 1";
}
if ($_POST['myselect'] = "2") {
echo "Div contents 2";
}
?>
My problem is this: 'Div contents 1Div contents 2' gets echoed into mydiv after I make any selection on the form. I was trying to get it to echo 'Div contents 1' if option 1 is selected and 'Div contents 2' if option 2 is selected.
Thanks and apologies for the long question.

The code :
if ($_POST['myselect'] = "1")
and
if ($_POST['myselect'] = "2") {
Will always evaluate to true, since its assignment.
You need to use :
if ($_POST['myselect'] == "1") {

Its a good oldy,
Change to
<?php
if ($_POST['myselect'] == "1") {
echo "Div contents 1";
}
if ($_POST['myselect'] == "2") {
echo "Div contents 2";
}
?>
Note the ==

Related

Multiple else if in jQuery

I am doing dependent select box using jquery, ajax and php from same table of the database. Testpage
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "name") {
result = 'category';
alert ('test1');
} else if (action == "category") {
result = 'material';
alert ('test2');
} else if (action == "material") {
result = 'source_light';
alert ('test3');
} else if (action == "source_light") {
result = 'color_temperature';
alert ('test4');
} else {
// result = 'color_temperature';
}
$.ajax({
url:"fetch_filter2.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
I don't know why but it only works: test1 and test2. Test3 and 4 are not sent to php.
HTML file
Maybe something is wrong with select box? But these are just a select box with id's.
<select name="name" id="name" class="form-control action">
<option value="">Select name</option>
<?php echo $name; ?>
</select>
<br />
<select name="category" id="category" class="form-control action">
<option value="">Select category</option>
</select>
<br />
<select name="material" id="material" class="form-control">
<option value="">Select material</option>
</select>
<br />
<select name="source_light" id="source_light" class="form-control">
<option value="">Select source_light</option>
</select>
<br />
<select name="color_temperature" id="color_temperature" class="form-control">
<option value="">Select color_temperature</option>
</select>
What about something like this
$(document).ready(function(){
$('.action').change(function()
{
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
switch(action) {
case "name":
result = 'category';
alert ('test1');
break;
case "category":
result = 'material';
alert ('test2');
break;
case "material":
result = 'source_light';
alert ('test3');
break;
case "source_light":
result = 'color_temperature';
alert ('test4');
break;
default:
// result = 'color_temperature';
}
$.ajax({
url:"fetch_filter2.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
Verify your drop down list under "action" class. As per your condition it won't trigger if your selected drop down item doesn't have value if($(this).val() != '').
Also make sure your expected drop down items have the value material for your test3 and source_light for your test4
Another suggestion: To load and trigger dynamic change event for drop down you can use below jQuery API:
$(document).on("change", ".action", function(){
//Your code here
});
If this doesn't solve your problem then please share your HTML or drop down data.
Updated answer: I can see there is no class "action" in your select/drop down items for material, source_light and color_temperature. That is why change actions of these drop down items are not catching in your $('.action').change(function() ... code block.

How do I show or hide a div based on dropdown value populated by PHP query

Can someone help me with this...
I've managed to find code and get it to work using JQuery -collapse function when the user changes value away from "Rejected"
...what I can't get to work is if the dropdown selected value is populated from a query within PHP page and is set to anything other than "Rejected", I need it to hide the DIV else if it's pre-populated value is "Rejected" then show DIV and then if user changes the value on screen to say "No" then hide it. and again if they happen to select "Rejected" again then show it ETC.
<!-- Page Code -->
<div class="NotAcceptedReason">
<label class="font-bold text-danger">Please Enter Reason:</label>
<textarea name="_initReviewCriteria002_Comment" class="form-control">
My Reason Comment Here
</textarea>
</div>
<!-- Selected Value pre-populated by db -->
<select class="form-control" name="_ReviewCriteria" id="ReviewCriteria">
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="NA">NA</option>
<option value="Rejected" selected>Rejected</option>
</select>
<!-- Script Function to handle onChange Event on dropdown selection -->
<script>
$('.AcceptedReason').addClass('collapse');
$('#ReviewCriteria').change(function () {
opt = $(this).val();
if (opt == "Yes") {
$('.NotAcceptedReason').collapse('hide');
} else if (opt == "No") {
$('.NotAcceptedReason').collapse('hide');
} else if (opt == "NA") {
$('.NotAcceptedReason').collapse('hide');
} else {
$('.NotAcceptedReason').collapse('show');
}
});
</script>
ALSO...Some posts say that the use of 'hide'/'show' is depreciated in JQuery ver x? but I'm finding examples of the latest JQuery versions using this, which I find confusing.
You have to trigger the change() for the first time, add the following line :
$(function(){
$('.AcceptedReason').addClass('collapse');
$('#ReviewCriteria').change();
....
})
Also your code could be more organized if you merge the conditions :
if (opt === "Yes" || opt === "No" || opt === "NA") {
$('.NotAcceptedReason').collapse('hide');
} else {
$('.NotAcceptedReason').collapse('show');
}
It will be better if you could use slideUp/slideDown functions, check example below.
Hope this helps.
$(function(){
collapseDiv($('#ReviewCriteria').val());
$('body').on('change', '#ReviewCriteria', function () {
collapseDiv($(this).val());
})
})
function collapseDiv(opt){
if (opt === "Yes" || opt === "No" || opt === "NA") {
$('.NotAcceptedReason').slideUp();
} else {
$('.NotAcceptedReason').slideDown();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<!-- Page Code -->
<div class="NotAcceptedReason">
<label class="font-bold text-danger">Please Enter Reason:</label>
<textarea name="_initReviewCriteria002_Comment" class="form-control">
My Reason Comment Here
</textarea>
</div>
<!-- Selected Value pre-populated by db -->
<select class="form-control" name="_ReviewCriteria" id="ReviewCriteria">
<option value="Yes">Yes</option>
<option value="No" selected>No</option>
<option value="NA">NA</option>
<option value="Rejected">Rejected</option>
</select>
This is because you don't check the initial value of select box. Add the following code after onChange event :-
$(function(){
var init_opt = $('#ReviewCriteria').val();
if (init_opt == "Yes") {
$('.NotAcceptedReason').collapse('hide');
} else if (init_opt == "No") {
$('.NotAcceptedReason').collapse('hide');
} else if (init_opt == "NA") {
$('.NotAcceptedReason').collapse('hide');
} else {
$('.NotAcceptedReason').collapse('show');
}
});

Change select dropdown based on first select dropdown?

I am trying to change the second select dropdown based on whether the first selected option contains an (m) or (ft).
My form HTML search is as follows:
<form id="search" action="/property_search" method="get" class="clearfix">
<select name="sqsize" id="sqsize" class="sqsize">
<option value="">sq.ft/sq.m:</option>
<option value="233.52m">233.52m</option>
<option value="233.52m">233.52m</option>
<option value="467.04m">467.04m</option>
<option value="2,513ft">2,513ft</option>
<option value="2,513ft">2,513ft</option>
<option value="5,026ft">5,026ft</option>
</select>
<select name="sqsizemin" id="sqsizemin" class="sqsizemin">
<option value="">Size Min:</option>
</select>
<input type="submit" class="submit" value="Search">
</form>
My Jquery is as follows:
<script type="text/javascript">
$(function(){
$('#sqsize').change(function () {
var options = '';
if($(this).val() == 'm') {
options = '<option value=""></option>';
}
else if ($(this).val() == 'ft') {
options = '<option value="6">6</option>';
}
$('#sqsizemin').html(options);
});
$('#sqsize').trigger('change');
});
Try something like this(using indexOf):
$(function(){
$("#sqsize").change(function(){
var options = '';
if($(this).val().indexOf('m') > -1) {
options = '<option value="">mm</option>';
}
else if ($(this).val().indexOf('ft') > -1) {
options = '<option value="6">6</option>';
}
$('#sqsizemin').html(options);
});
});
Working fiddle: https://jsfiddle.net/robertrozas/b0w61quf/
Try like this:
https://jsfiddle.net/kc5qqtco/
$(function(){
$('#sqsize').change(function () {
if($(this).val().match(/m/g)) {
$('<option value=""></option>').appendTo('#sqsizemin');
}
else if ($(this).val().match(/ft/g)) {
$('<option value="6">6</option>').appendTo('#sqsizemin');
}
});
});
Using indexOf will get you a working solution.
See the jsfiddle

how to refresh particular element in php with jquery?

I have one select box.on change event of it, I call confirm box. When I clicked on cancel button then remains changed value.
So I want to refresh only select box not whole page.
function statusChanged(obj,id){
$(obj).change(function() {
var answer = confirm ("Are you sure update Status?");
var status;
if(answer){
status=$(this).val();
//alert(status);
ajaxUpdate("service-providers.php", {action:"updatestatus",'status': status,'id':id}, function(data) {
if(data.type=="success") {
$("#notify").notification({caption:"Status Updated Successfully.", type:"information", sticky:false ,onhide:function(){
window.location="service-providers.php";
}
});
}
});
}
else{
// here i want to refresh select box
}
});
}
html code:
<select id="status1" name="status1" style="width:140px;" onChange="statusChanged(this,<?php echo $applicationid; ?>);">
<?php
if($status==3 || $status==4)
echo "<option value='4'>Submitted</option>";
else
echo "<option value='0'>Select</option>";
?>
<option value="2" <?php if($status==2) echo "selected='selected'"; ?> >Approved</option>
<option value="3" <?php if($status==3) echo "selected='selected'"; ?> >Rejected</option>
</select>
after page loads do:
$('select').each(function() {
$(this).attr('original_data', $(this).val());
});
and in your function do
$(this).val(this.attr('original_data'));
Checked. Works perfectly.
use this code under else it will just reset select box.
This will work
$('#SELECTBOX_ID').prop('selectedIndex',0);
see the for http://jsfiddle.net/TmJCE/10/ working demo.
also I implemented this code in my local I mainly made two changes I removed onchange from select and second is I did not use ajax coz you only want to work on click of cancel on confirm box.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
jQuery("#status1").change(function() {
var answer = confirm ("Are you sure update Status?");
var status;
if(answer){
status=$(this).val();
//I have did not call ajax
}
else{
jQuery('#status1').prop('selectedIndex',0);
}
});
});
</script>
<?php
$status = 0; // I temporary added t
?>
<select id="status1" name="status1" style="width:140px;" >
<?php
if($status==3 || $status==4)
echo "<option value='4'>Submitted</option>";
else
echo "<option value='0'>Select</option>";
?>
<option value="2" <?php if($status==2) echo "selected='selected'"; ?> >Approved</option>
<option value="3" <?php if($status==3) echo "selected='selected'"; ?> >Rejected</option>
</select>

javascript disable multiselect box based on selections in another multiselect box

I have two multi select boxes one for country list and one for state list
<select multiple="multiple" name="country[]" id="country" >
<option value="0">Select a Country</option>
<?php
foreach($country_list as $key=>$value){
echo "<option value=\"$key\"";
if($html['Country Name']==$key|| $row['Country Name']==$key){
echo ' selected="selected"';
}
echo ">$value</option>\n";
}?>
</select>
<select multiple="multiple" name="state[]" id="state">
<option value="">Select a State</option>
<?php
foreach($state_list as $key=>$value){
echo "<option value=\"$key\"";
if($html['state']==$key|| $row['state']==$key){
echo ' selected="selected"';
}
echo ">$value</option>\n";
}?>
</select>
I have this javascript which enables the state box when the country selected is USA.
window.onload = function() {
var selectCountry = document.getElementById('country');
selectCountry.onchange = function() {
document.getElementById('state').disabled = (selectCountry.value != 'USA')? true : false;
};
};
But, I want the state box to be disabled when other countries are selected along with USA in the first one.
Any suggestions please? Thanks
Demo: http://jsfiddle.net/eBTgb/
$("#country").on("click change", function(){
var option_usa = $("option[value=6]", this);
if (option_usa.is(":selected") && option_usa.siblings(":selected").length == 0) {
$("#state").removeAttr("disabled");
}
else {
$("#state").attr("disabled", "disabled");
}
});
I hope understand you correctly.
This can be done using JQuery.
$("#state").hide();
$("#country").change( function () {
var countryName = $("#country").find("option:selected").html();
if(countryName == 'USA'){
$("#state").show();
} else {
$("#state").hide();
}
});
Heres the link to the JSFIDDLE

Categories