I have a select option to filter posts by category. On select change I want the ajax request to be sent and load the posts of the category selected. I currently have this working using a submit button, but I need this to work on select option change, but I cannot get it to work just using a select.
Below is the script and form i'm working with that works on submit using a button.
<form action="<?php echo site_url(); ?>/wp-admin/admin-ajax.php" method="POST" id="filter" class="ghost-select">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) :
echo '<select id="categoryfilter" name="categoryfilter"><option>Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
?>
<!-- <button>Apply filter</button> -->
<input type="hidden" name="action" value="myfilter">
<!-- onchange="this.form.submit();" -->
</form>
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'), // ajax
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
// filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
// filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
I have tired changing the initial submit function to the following, but it doesn't do anything:
$('#filter select').on('change', function() {
I've also tried adding onchange="this.form.submit();" to the select itself, but this submits the form and takes you away from the page to the url of the form action so I now know this isn't the right way to go.
I'm not sure what i'm missing so any help with this would be greatly appreciated!
Thanks
Related
I have looked at this site for three days. I admit I am new to using javascript. But I have used the many different solutions offered and none have worked. Please help.
I am trying to do something that should be simple: save a user choice of country from a dropdown box on an html5 page to a hidden post variable (using javascript onchange.) That is used in a post array on the same form for a php operation that sends the input to a mysql database. This is my code:
The hidden post variable doesn't update. From there I can't test the code logic. But my onchange code came from this site and is suppose to work.
References:
<script type="text/javascript" src="../../js/jquery-2.1.4.min_prod.js"> </script>
<script type="text/javascript" src="../../js/respond.min.js"> </script>
<script type="text/javascript" src="../../js/bootstrap.min.js"> </script>
form information:
<form name="form1" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" />
</form>
form element
$query="SELECT * from country ";
$query=$query."ORDER BY country asc";
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select id="country" onchange="send_name(this)">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
?>
<input type="hidden" id="c_php_value" name="c_php_value" value="">
Javascript
function send_name(selectObjectI) {
var value = selectObjectI.value;
$.ajax({
type: "POST",
url: "http://localhost/php/protected/form_addnews.php",
data:{c_php_value: value}
});
Post Submit Code
$country_id1 = trim($_POST['c_php_value']);
Thanks to a coder on utube, speaking german I might add, I discovered I don't need javascript, ajax or anything complicated to accomplish what I am trying to do.
I simply needed to do the following:
(1) Add a name="" to the dynamically created SELECT flag(name="country_id2").
(2) user chooses input with drop down box created.
(3) gather the $_POST after the form submit is set.
($country_id = $_POST['country_id2'])
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select name="country_id2" id="country_id2">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
I am working on POS web.
creating form for each item in cart/order i.e multiple forms in loop and giving them unique ids ('id'=>'cart_'.$line )(cart_1,cart_2).
and created an update link in loop for each form. code below
echo form_open($controller_name."/edit_item/$line", array('class'=>'form-horizontal', 'id'=>'cart_'.$line));
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'id'=>'quantity','class'=>'form-control'));
echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3', 'id'=>'discount', 'class'=>'form-control'));?>
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id="anchor" title=<?php echo $this->lang->line('sales_update')?> >
This fulfils the update requiremnt like when I update a quantity and click the link it updates the price.
But now the problem is that I want my form to submit on onChange event of quantity field.
1) First Try
<script type="text/javascript">
$("#quantity,#discount").on('change',function(){
var quantity=$("#quantity").val();
var discount=$("#discount").val();
if(quantity!=""&&discount!=""){
document.getElementById('anchor').click();
console.log('form send');
}
});
</script>
this is what I tired but it only works if there is only one item in order
2)Second try
function updateQuantity(anchorID){
if(anchorID != ""){
document.getElementById(anchorID).click();
}
}
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'onChange'=>'updateQuantity(HERE I WANT TO PASS "anchorID_LOOP VALUE")' 'id'=>'quantity','class'=>'form-control'));
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id='<?php echo 'anchorID_'.$line ?>' title=<?php echo $this->lang->line('sales_update')?> >
Rather than triggering a button.click() You should try the following:
echo form_open($controller_name."/edit_item/$line", array('class'=>'form-horizontal line-item', 'id'=>'cart_'.$line));
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'id'=>'quantity','class'=>'form-control cartline', 'data-form' => $line));
echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3', 'id'=>'discount', 'class'=>'form-control cartline', 'data-form' => $line));?>
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id="anchor" title=<?php echo $this->lang->line('sales_update')?> >
Notice I gave the form control an extra class and a data- attribute to hold the $line variable
So now I can catch the event and submit the form
$(function(){
$('.cartline').change(function(){
var line = $(this).attr('data-form');
$('#cart_' + line).submit();
});
});
To send the form via AJAX, you have to handle the form submit function (I gave the form a new class line-item)
$(".line-item").submit(function(event) {
event.preventDefault();
var line_form = $( this ),
url = line_form.attr( 'action' );
//Make your data
$.post( url, { data-field1: $('text1').val(), data-field1: $('text2').val() }, function(data){
alert('Form Posted')
});
});
Jquery/Ajax rookie here
This is how my code should work...
When the submit button is clicked, JavaScript handles the form and post the values to the same page. The values are used in a SQL query to update a column in the database. The value from the column is echoed out and updated each time the button is clicked (SQL UPDATE QUERY), all this would be done without refreshing the page using ajax (i.e "ONLY" the value from the database would be refreshed when the button is clicked and the page shouldn't scroll back to the top). The problem is my JavaScript isn't handling the form submission as i expect it to. The div around the value isn't refreshing, i have to redirect to a different page and back to see the changes (SQL query works). How do i solve my problem to achieve this?
file.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ajaxform').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
url: "file.php", // the file to call
success: function(response) { // on success..
$('#emailform').html("Thank you!"); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...................
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" id="ajaxform"
enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
echo '<div id="emailform"></div>';
}
?>
</body>
</html>
query.php
<?php
if( isset( $_POST['lkcv'] ) && is_array( $_POST['lkcv'] ) )
{
$idArray = array();
foreach( $_POST['lkcv'] as $value )
{
$idArray[] = intval( $value );
}
$db->query( "UPDATE comment SET like1 = like1 + 1 WHERE id IN (".implode(
',', $idArray ).")" );
}
?>
NOTE: file.php always has a dynamic url such as "file.php?post=1"
I don't know php, so apologies if some of this is wrong.
does file.php write out a full html page? If so, it should only be sending out a fragment as ajax deals with partial updates rather than pulling in an entire page.
In your success handler, you are only updating the #emailForm div, when really you also want to be replacing the content on the page with the new version.
2nd, in html, tags with an id are expected to be unique. You output
<div id="emailForm"></div>
in a loop, therefore, it isn't unique on the page, so you might not get the right one being updated
There is a parameter for $.ajax called cache, setting that will append a timestamp to your query, ensuring it is unique, no need to manually create a unique url.
$.ajax({
cache: false,
....
Lastly, to make sure that you are getting fresh content, check your web server logs to look for a http response, which means that the content hasn't changed, so the webserver sent a cached copy
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#content').on("submit", "form", function(e) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
cache: false,
url: "file.php?=" + $(e.currentTarget).find("name=lkcv[]").val(), // the file to call
success: function(response) { // on success..
$(e.currentTarget).html(response); // only replace the form that caused the submit
$('#emailform').html("Thank you!"); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...................
echo '<div id=content>';
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
}
echo '</div>';
echo '<div id="emailform"></div>';
?>
So I was having 2 dropDownLists in my _form.php and I have a radioButtonList which contains 2 options.
The problem I have is this, when I disable either one, one of the dropdown should be disabled. It did disable, BUT one of them will be turned into Undefined Index, whereas the other one is working fine when disabled.
This is my javascript:
$(document).ready(function(){
$('input[type=radio]').change(function(){
if(this.value == '0'){
$("#Booking_clientPackagedService_id").prop("disabled", false);
$("#Booking_service_id").prop("disabled", true);
$("#Booking_service_id").val('0');
}
else if(this.value == '1'){
$("#Booking_service_id").prop("disabled", false);
$("#Booking_clientPackagedService_id").prop("disabled", true);
$("#Booking_clientPackagedService_id").val('0');
}
});
})
Okay, so this is what happens. As you can see, IF I were to click on the option '1', the Booking_clientPackagedService_id will be disabled and to be submitted. But when I click on the button 'Save' in the form, it says
Error 500: Undefined index clientPackagedService_id
But If I were to choose on option '0' and submit, everything works just fine. service_id isn't giving any problem.
The below is my code to 2 dropDowns:
<div class="row">
<?php echo $form->labelEx($model,'clientPackagedService_id'); ?>
<?php $client = Client::model()->findByPk(1);?>
<?php echo $form->dropDownList($model, 'clientPackagedService_id', CHtml::listData($client->clientPackagedservices(array('condition'=>'client_id='.$client->id.' AND booking_id IS NULL')),'id','packagedServiceInfo')
,array(
'disabled'=>'disabled',
'prompt'=>'Select Packaged Service....',
'ajax' => array( 'type'=>'POST', //request type
'url'=>CController::createUrl('updateMasseuseAndStationListPSID'), //url to call.
'data'=>array('clientPackagedService_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
'dataType'=>'json',
'success'=>'js:function(data) {
var mass="#'.CHtml::activeId($model, 'masseuse_id').'";
$(mass).html(data.masseuse);
$(mass).trigger("chosen:updated");
$(mass+"_chzn").css("width","300px");
$(mass+"_chzn > .chzn-drop").css("width","298px");
var station="#'.CHtml::activeId($model, 'station_id').'";
$(station).html(data.station);
$(station).trigger("chosen:updated");
$(station+"_chzn").css("width","300px");
$(station+"_chzn > .chzn-drop").css("width","298px");
//alert(data.timeEnd);
var timeEnd="#'.CHtml::activeId($model, 'timeEnd').'";
$(timeEnd).val(data.timeEnd);
}',
)
)
); ?>
<?php echo $form->error($model,'clientPackagedService_id'); ?>
</div><!-- row -->
<div class="row">
<?php echo $form->labelEx($model,'service_id'); ?>
<?php echo $form->dropDownList($model, 'service_id', GxHtml::listDataEx(Service::model()->findAllAttributes(null, true)),
array(
//'disabled'=>'disabled',
'prompt' => 'Select Service....',
'ajax' => array( 'type'=>'POST', //request type
'url'=>CController::createUrl('updateMasseuseAndStationListSID'), //url to call.
'data'=>array('service_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
'dataType'=>'json',
'success'=>'js:function(data) {
//alert(data.masseuse);
var mass="#'.CHtml::activeId($model, 'masseuse_id').'";
$(mass).html(data.masseuse);
$(mass).trigger("chosen:updated");
$(mass+"_chzn").css("width","300px");
$(mass+"_chzn > .chzn-drop").css("width","298px");
var station="#'.CHtml::activeId($model, 'station_id').'";
$(station).html(data.station);
$(station).trigger("chosen:updated");
$(station+"_chzn").css("width","300px");
$(station+"_chzn > .chzn-drop").css("width","298px");
//alert(data.timeEnd);
var timeEnd="#'.CHtml::activeId($model, 'timeEnd').'";
$(timeEnd).val(data.timeEnd);
}',
)
));
?>
<?php echo $form->error($model,'service_id'); ?>
</div><!-- row -->
UPDATES After further debugging~
I found out the reason for it to behave that way.
$("#Booking_clientPackagedService_id").prop("disabled", true);
$("#Booking_clientPackagedService_id").val('0');
These 2 lines are the reason. Can anyone please advise me? Thanks~
UPDATES after further further debugging >.<~
I have a function in actionCreate():
$model->bookService($_POST['Booking']['clientPackagedService_id']);
basically, when the dropdown is disabled, this method wouldn't go through, thus, throwing an error 500 clientPackagedService_id Undefined index
Just add in a hidden duplicate field of the dropdownlist, in this case,
<?php echo $form->hiddenField($model, 'clientPackagedService_id'); ?>
Because disabled dropdownlists won't POST/GET to the PHP server side, therefore, adding in a hidden field will solve the problem
I have a page which has a form table. It displays select option when an option is selected the user clicks button and it runs updatephp.php which has query for updating. I need the select to be dynamically updated and display the success/error message like "updated" or "no results" on the screen how can I achieve this. Im not very good at ajax could someone guide me please.
displaytable.php
<form method="POST" action="choosecake.php">
<select id="bakeryid" name="bakeryid">
<option value="">Select</option>
<?php
$sql = "SELECT bakeryid, datefrom FROM cakes";
$sqlresult = $link->query($sql);
$sqllist = array();
if(mysqli_num_rows($sqlresult) > 0) {
while($row = mysqli_fetch_array($sqlresult))
{
echo "<option value=".$row['bakeryid'].">".$row['datefrom']."</option>";
}
$sqlencode = json_encode($sqllist);
echo $sqlencode;
} else {
echo 'No Results were found';
}
?>
</select>
<input type="hidden" value="<?php echo $bakeryid;?>" name="bakeryid"/>
<input type="submit" value="Submit" name="submit"/>
</form>
change your displaytable.php and generate an array of your cakes with id as key and the name as the value. Then echo the json encoded array which can be used directly in js.
Just to get a feeling, didn't test it.
$(document).ready(function() {
window.setTimeout(function() {
$.ajax({
url: "/displaytable.php"
}).done(function(data) {
var select = $('#selectId');
select.empty();
$.each(data, function(val, key) {
select.append($("<option></option>").attr("value", key).text(val);
});
});
}, 10000); // 10 seconds update interval
});
If your page must refresh (no ajax), use displaytable.php to handle the form submission. Then define a variable to hold your success or error message and put this variable where you want the message to display, like
if(!empty($success_message)) {
echo "<h2>$success_message</h2>";
}
When the form is submitted, simply assign a value to $success_message, and since the script handling the form submission is the same script which contains the form, the echo statement in the code above will display your message when the page reloads.