I have a dropdown in my form which I used to filter data. I am using ajax onchange function to filter the data based on the selected list.
My dropdown looked something like this :
<select id="opt_level" name="opt_level">
<option value="level1">Level 1</option>
<option value="level2">Level 2</option>
<option value="level3">Level 3</option>
</select>
And here is the div that I wanted to display the onchange data :
<div id="opt_lesson_list">
<!-- Some statement here -->
</div>
When there is onchange on dropdown, it will go through this ajax function :
jQuery(document).ready(function($) {
$("#opt_level").on('change', function() {
var level = $(this).val();
if(level){
$.ajax ({
type: 'POST',
url: 'example-domain.com',
data: { hps_level: '' + level + '' },
success : function(htmlresponse) {
$('#opt_lesson_list').html(htmlresponse);
console.log(htmlresponse);
}
});
}
});
});
And going to the url example-domain.com to check if there is post made from ajax :
if(isset($_POST['hps_level'])){
// Statement to select from database
}
So after filtering done, data inside the <div id="opt_lesson_list"></div> should display the filtered data. But what happened is, the ajax response to the whole page which means that my whole form is multiplying and displayed in the div that I used to display onchange data.
EDIT
My PHP is just filtering data from database based on the value selected :
if(isset($_POST['hps_level'])){
$sql = "SELECT DISTINCT(hps_lessons) FROM holiday_program_setup WHERE hps_level = '".$_POST['hps_level']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<ul class="list-unstyled subjects">';
echo '<li class="bordered" style="width: 30%;">';
echo $row['hps_lessons'];
echo '</li>';
echo '</ul>';
}
}
$sql = NULL;
}
If I echo $_POST['hps_level']; I can get the value of the dropdown selected.
my whole form is multiplying and displayed in the div that I used to
display onchange data.
It seems like you are pointing your ajax url example-domain.com to the page where all your html page is and the ajax returning the whole html page to your div response <div id="opt_lesson_list"></div>.
Try to create another blank php page and put your php isset code in the new php file.
if(isset($_POST['hps_level'])){
// Statement to select from database
}
Replace your ajax url with the new php file url. By doing that, your ajax will grab all the data from the new file and display in your response div.
your provide valid url,becz data filter to hps_level
jQuery(document).ready(function($) {
$("#opt_level").on('change', function() {
var level = $(this).val();
alert(level);
if(level){
$.ajax ({
type: 'POST',
url: 'example-domain.com',
data: { hps_level: '' + level + '' },
success : function(htmlresponse) {
$('#opt_lesson_list').append(htmlresponse);
alert(htmlresponse);
},error:function(e){
alert("error");}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="opt_level" name="opt_level">
<option value="level1">Level 1</option>
<option value="level2">Level 2</option>
<option value="level3">Level 3</option>
</select>
<div id="opt_lesson_list">
<!-- Some statement here -->
</div>
Related
I have a multi select drop down. I need a div to be filled with pages based on the selections. I have this working for one selection at a time. I need it to also work when I select more than one option the corresponding pages will populate the div.
For exemple... if I select Item1 and Item2. I want the pages item1.php and item2.php displayed in my div. If I then delete item1 from the selection (using chosen.js) I need only item2.php to show since that is the only current selection.
Here is my current code:
$('#maindiv').on('change', function(event) {
var selected = $(this).val();
$.ajax({
url: 'includes/'+ selected + '.php',
type: 'POST',
data: { cat: selected },
})
.done(function(data) {
$('#displaydiv').html(data)
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
jsfiddle Link. You can't get any output from here but you have to use this in your server.
For more clarification about the page is get or not, see this jsfiddle link. Here you can see the page which will load.
jQuery:
$(function(){
$('#maindiv').on('change', function(event) {
$('#displaydiv').html("");
selected = $(this).val() + "";
arr = selected.split(",");
i = 0;
$(arr).each(function(){
$.get('includes/'+ arr[i] + '.php', function( data ) {
$('#displaydiv').append(data);
});
i++;
});
});
});
HTML:
<select multiple id="maindiv">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<div id="displaydiv">
</div>
I have a drop down menu that is populated from a mysql table via php. When an item is selected a second drop down menu is triggered using a variable from the first form. This works as expected when making a selection via onchange trigger.
I would like to change this though, and have the script fire when the drop down is loaded and the selected item (set from previous page) is pre-set, I dont want any user interaction.
Here is the form code
<div><select class="form-control m-b" name="id" onChange="get_engineers(this.value)" style="font-family: monospace">
<?php
$qry = "SELECT id,name FROM products WHERE Parent_team = $parent_team ORDER BY name" ;
$stmt = $mysqli->prepare($qry);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
if($product==$row['name']){
$selectCurrent='selected';
}else{
$selectCurrent='';}
echo '<option value="'.$row['id'].'" '.$selectCurrent.'>'.$row['name'].'</option>';
}
?>
</select>
</div>
</div>
And the second form drop down
<div class="form-group"><label class="control-label">Engineer</label>
<select class="form-control m-b" name="engineer" id="engineer" style="font-family: monospace">
<option selected="selected">--Select Engineer--</option>
</select>
</div>
And the script
<script>
function get_engineers(id)
{
$.ajax({
type: "GET",
url: "ajax_engineers.php", /* The engineer id will be sent to this file */
beforeSend: function () {
$("#engineer").html("<option>Loading ...</option>");
},
data: "id="+id,
success: function(msg){
$("#engineer").html(msg);
}
});
}
</script>
I tried onload instead of onchange but nothing happens.
thanks
First, add an id attribute to your first select:
<select id="my-unique-id" class="form-control m-b" name="id">
Then you can trigger it via the jQuery onload like so:
<script>
$(function(){
// This will run it on page load to catch any auto-filled values
get_engineers($('#my-unique-id').val());
// This will run it when the value is changed
$('#my-unique-id').change(function(){
get_engineers($(this).val());
});
});
</script>
I'm trying to set up a form so that it submits (without refreshing the page) when a selection is made from a dropdown menu. I currently have it set to submit when the dropdown is select, but it refreshes the page.
My code for the form is,
<form action="" method="get">
<select name="day" onchange="this.form.submit();">
<option>Please select a date</option>
<option value="Mon"><?php echo $monday; ?></option>
<option value="Tue"><?php echo $tuesday; ?></option>
<option value="Wed"><?php echo $wednesday; ?></option>
<option value="Thu"><?php echo $thursday; ?></option>
<option value="Fri"><?php echo $friday; ?></option>
</select>
</form>
I've tried several jquery tutorials on submitting forms without a refresh, but they all involve a submit button. I need one that binds the submitting of the form to when a choice is selected in the dropdown.
Any help would be much appreciated.
EDIT: Solved
Using some of the ideas from the answers here, some tutorials, and a lot of trial/error. I finally got it figure out. Here is the code that works
$('#day').change(function()
{
$.ajax({
type: 'post',
url: "tutoringlistsession.php",
data: $("form.day").serialize(),
success: function() {
$('#list').load('tutoringlist.php', function(){
});
$('#list').show("fast");
}
});
return false;
});
You need to bind to the form's submit event:
$("form").on('submit', function (e) {
//prevent form submission / page refresh
e.preventDefault();
//submit form with ajax
$.get(window.location, $(this).serialize());
});
I would also bind to the select with jQuery as well for cleanliness/consistency:
$("form select").on('change', function () {
$("form").trigger('submit');
});
I would also use more specific selectors, which requires updating your markup.
Submit form via ajax onChange of the select element:
$("select").on('change', function () {
var thisForm = $(this).closest('form');
$.get($thisForm.attr('action'), $thisForm.serialize());
});
I used the ideas posted in here and several tutorials to figure out the answer. The working code is below:
$('#day').change(function()
{
$.ajax({
type: 'post',
url: "tutoringlistsession.php",
data: $("form.day").serialize(),
success: function() {
$('#list').load('tutoringlist.php', function(){
});
$('#list').show("fast");
}
});
return false;
});
I have a MySQL table which looks like this:
ID OPTION
1 First
2 Second
The user sees the following:
<div id="options">
<select>
<option value="1">First</option>
<option value="2">Second</option>
</select>
</div>
I would like the user to have the option to insert into the table, as follows:
<div id="add">
<input type="text" name="newOption" placeholder="Your own option">
<input type="button" value="Add">
</div>
It would then select their newly-added option:
<div id="options">
<select>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3" selected>Third</option>
</select>
</div>
As the above code is part of a page which contains other form elements the page can't be reloaded, otherwise the data they've already typed will disappear. So I'd like to use jQuery.
EDIT: I have tried the following but it adds rows twice, sometimes even four times, for reasons I cannot fathom!
$("#button").click(function(){
var test = $("#<?php echo $selectName; ?>").val();
var dataString = 'select=<?php echo $select; ?>&selectName='+ test;
$.ajax({
type: "POST",
url: "optionAdd.php",
data: dataString,
cache: false,
success: function(html){
$("#<?php echo $select; ?>List").load("optionList.php?select=<?php echo $select; if ($_GET[required] == "no") { echo "&required=no"; } ?>");
}
});
});
The reason for the PHP above is I want to use multiples of this code on the same form and so I'm using GET to select the options, as it were.
You would need to send an AJAX request to server with the new data and get an ID returned for this new option. Once the ID is received you can create the option with the new ID as value and the user defined text
$('#add button').click(function(){
/* get value from previous input*/
var newOpt=$(this).prev().val();
/* make AJAX "POST" request*/
$.post( 'path/to/server/file', { newOption: newOpt}, function( newId ){
/* ajax successfully completed, add new option*/
$('#options select').append('<option value="'+ newId +'">'+newOpt+'</option>');
});
return false; /* prevent browser default handling of button click*/
})
At server receive the data as you would a form field with name="newOption" ie $_POST['newOption'] and send back a new ID as text
Alternatively you could send back all the options as html in sort order you want and replace all the options in the select.
/* ajax to replace all options with html from server*/
$.post( 'path/to/server/file', { newOption: newOpt}, function( response ){
/* ajax successfully completed, add new option*/
$('#options select').html( response);
});
I would suggest using jQuery AJAX to call a PHP Script to store the new option to the database, that returns the new ID and the given option name on success and then add the new entry to the <select> using Javascript.
I want to post some values from a simple HTML form, validate them with an ajax call and if successful submit to a PHP script and redirect to that script. I have got the ajax part set up, just not sure how to post and redirect (as if you would on a standard form submit without ajax).
Here's what I have:
HTML:
<div id=audiencesearch>
<h1>Audience Search</h1>
<form id="audiencesearchform">
<p>Passion Point</p>
<select id="passionselect">
<option selected="selected">Please select</option>
<option>3D</option>
<option>Music</option>
<option>Playstation</option>
</select>
<p>Gender Bias</p>
<select id="genderselect">
<option selected="selected">Please select</option>
<option>Male</option>
<option>Female</option>
</select>
<p>Sort Group By Age Range</p>
<select id="ageselect">
<option selected="selected">Please select</option>
<option>Under 21</option>
<option>21 - 30</option>
<option>31 - 40</option>
<option>41 - 50</option>
</select>
<br/>
<br/>
<input onClick="ajaxaudiencesearch()" class="submitaudiencesearch" value="Search" type="button"/>
Ajax Call:
<script type="text/javascript">
function ajaxaudiencesearch(){
var passionpoint = $("select#passionselect").val();
var genderbias = $("select#genderselect").val();
var agerange = $("select#ageselect").val();
var passedstring = 'passion='+ passionpoint + '&gender=' + genderbias + '&age=' + agerange;
$.ajax({
type: "POST",
url: "processaudiencesearch.php",
data: passedstring,
success:function(retval){
if (retval == 'oktoprocess'){
audiencesearchprocess();
} else {
audiencesearcherror();
}
}
})
}
function audiencesearcherror(){
$('#audienceerror').html('GOTTA SELECT EM ALL');
}
function audiencesearchprocess(){
window.location.href = "searchresults.php";
//THIS IS WHERE I WANT TO POST AND MOVE TO SEARCHRESULTS.PHP
}
</script>
PHP to handle Ajax:
<?php
include('sonymysqlconnect.php');
session_start();
$nullselection = "Please select";
//get the posted values
$postedpassion = ($_POST['passion']);
$postedgender = ($_POST['gender']);
$postedage = ($_POST['age']);
if (($postedpassion != $nullselection ) && ($postedgender != $nullselection ) && ($postedage != $nullselection)){
echo 'oktoprocess';
} else {
echo 'error';
}
?>
Preferably I could achieve this using jQuery. I'm sure it's extremely simple but I'm not sure how to do it?!
It's worth mentioning that this is all set up correctly. I have used PHP includes.
Thanks in advance...
Why not add action and method attributes to your form and then submit it with .submit()?
With plain html / php it is not even really a true redirect, its just the url value in "action" that can be found in the form element
<form action="/someUrl/someAction" method="POST">
...
</form>
If you're doing it with ajax (jquery), you'd say:
$.ajax({
url: '/someUrl/someAction',
type: 'POST',
data: {
argName1: 'argVal1',
argName2: 'argVal2'
},
success: function( response ) {
// keep in mind that response is usually in json...
// which means you'd be accessing
// the data in object notation: response.data.someVal
if(response == 'whatYouWanted') {
//do something... like redirect?
window.location = '/new/page';
}
});