I am using 2 drop down lists. One list comes from Ajax code. My question is this, how do I keep the ensure the value remains in the second drop down while the form is reloaded. I am using trigger change event for value of model drop down.
My code is below
---i
Trigger Change Jquery i used from stack overflow.
--i have one more table name model the value of vehicle comes from make table.
--
<?php
include "conn.php";
$exe=$con->query("select * from make");
?>
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$('#make').trigger("change");
//console.log(make);
function getModel()
{
var mid= document.getElementById("make").value;
//console.log(mid);
$.ajax({
type:"POST",
url :"model.php",
data:"makeid="+mid,
success:function(ans)
{
document.getElementById("model").innerHTML=ans;
}
});
}
</script>
</head>
<body>
<form method="post">
<table align="center">
<tr>
<td>Make</td>
<td>
<select name="make" id="make" onchange="return getModel()">
<?php
while ($row=$exe->fetch_object())
{
?>
<option value="<?php echo $row->make_id?>">
<?php if(isset($_POST['make']) && $_POST['make']==$row->make_id) echo "selected";?>
<?php echo $row->make_name?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Model</td>
<td><select name="model" id="model">
<option value="">.....</option>
</select></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
This code will store your dropdown value to the storage
let dropdownModel= document.getElementById("model").value
localStorage.setItem("myValue", dropdownModel);
This code will load your stored value from your dropdown and put it back to it
document.getElementById("model").value = localStorage.getItem("myValue");
Use jquery to call on change,
$(document).ready(function(){
$("#make").on('change', function(){
var make_id= $("#make option:selected").val();
$('#model').empty();
$.ajax({
url: 'model.php',
type: 'POST',
dataType: "text",
data: {
make_id: make_id,
}
}).done(function(data){
$('#model').html(data);
});//ajax success function
}).change();
});
in model.php make a drop down like this
<option>A</option>
<option selected >B</option>
With this code you can get the second drop down names model value. Then you can select it when the form has loaded.
<script>
$(document).ready(function() {
$("#make").trigger('change');
$("#model").selectedIndex = <?php echo $_POST['model']?>;
});
</script>
Related
I have an html form that I submit to a php server. If I submit the form the standard way with a submit button and an action="screen_custom.php", then it works fine. I see a page full of valid JSON data.
But if I submit the form using a jquery ajax call, then an empty json array is returned. I believe the php is unable to find the form values for some unknown reason. Anyway, how do I debug the php during an ajax call? The response must only include the data needed to populate a jquery DataTable. If I echo debugging output, then the datatable will fail to populate.
Here's some code that successfully submits the form to the php and returns good json data.
<form id="criteriaForm" method="post" action="screen_custom.php">
<table>
<tr>
<th>Filter By</th><th>Criteria</th><th title="Show this column">Show</th>
</tr>
<tr>
<td><label title="Percentage increase">Appreciation Potential (%)</label></td>
<td>
<select name="upside">
<option value="any">Any</option>
<option value="gt0">> 0%</option>
<option value="gt10">> 10%</option>
</select>
</td>
<td><input type="checkbox" id="showUpside" name="showUpside" value="true">
</tr>
</table>
<input type="submit" value="Run">
</form>
Here's some code that fails to return the same json data:
<form id="criteriaForm" method="post" action="">
<table>
<tr>
<th>Filter By</th><th>Criteria</th><th title="Show this column">Show</th>
</tr>
<tr>
<td><label title="Percentage increase">Appreciation Potential (%)</label></td>
<td>
<select name="upside">
<option value="any">Any</option>
<option value="gt0">> 0%</option>
<option value="gt10">> 10%</option>
</select>
</td>
<td><input type="checkbox" id="showUpside" name="showUpside" value="true">
</tr>
</table>
<button type="button" onclick="runCustomScreen()">Run</button>
</form>
And the javascript:
function runCustomScreen() {
$('#customTable').DataTable({
"ajax": {
type: 'POST',
url: "screen_custom.php",
data: $('#criteriaForm').serialize(),
complete: function(jqXHR, textStatus) {
console.log("Run was successful, textStatus="+textStatus);
},
error: function(e, textStatus, errorThrown) {
alert("textStatus="+textStatus +", errorThrown="+errorThrown);
}
}
});
return false; //needed if called by onclick event
}
Here's the parts of the php that handle the form data and return the json:
$upside = $_POST["upside"];
$sql = "SELECT * FROM stocks " .$where;
//echo '<script>'
//echo 'sql=' .$sql .'<br>';
//echo 'console.log(' .$sql .')';
//echo '</script>';
$rs = mysql_query($sql);
//store result in an array
$results = array();
while($row = mysql_fetch_object($rs))
{
$results[] = $row;
}
$data = json_encode($results);
echo '{"data":' .$data .'}';
//close the db connection
mysql_close($connection);
Note that if I uncomment any but the last echo, then the datatable won't populate. So how can I debug this?
I figured out how to debug it. In the chrome debugger, select the Network tab, then select "screen_custom.php" from the list, then select the Response tab. It shows the output from the php. I uncommented the echo sql statement and could see that in fact, the form parameters are not being read, as I suspected.
Then I googled on that problem and found the solution was to modify the data paramenter js as shown below:
data: function(d) {
var form_data = $('#criteriaForm').serializeArray();
$.each(form_data, function(key,val) {
d[val.name] = val.value;
});
},
I don't know why the first method didn't work as I could see the correct parameters being sent in the header. But this works.
Did you tried to use the isset($_POST['value']) method on your php script? where value is the name that you will assign to your submit button.
I am using CSS in a select box,
but my dynamic data is not displaying. :(
If I remove the class in select box area and get by id,
the data displays after choosing 'province'.
My data is shown in the Firebug console,
but not displayed in the select box 'kabupaten'/'city'.
Screenshot:
Code:
index.php
<table>
<tr>
<td>Provinsi</td>
<td>
<div class="control-group">
<div class="controls">
<select name="profinsi" class="profinsi" >
<option value="" selected="selected">-->Choose Province<--</option>
<?php $sql="select * from all_provinsi";
$rs=mysql_query($sql);
while($row=mysql_fetch_object($rs)){ ?>
<option value="<?php echo $row->id_prov; ?>"><?php echo $row->nama_prov; ?></option>
<?php } ?>
</select>
</div>
</div>
</td>
</tr>
<tr>
<td>Kabupaten</td>
<td>
<img src="loading.gif" width="10px" height="10px" id="imgLoad" style="display:none">
<select name="Kabupaten" class="kabupaten" >
<option value="" selected="selected">-->Choose City/Kabupaten<--</option>
</select>
</td>
</tr>
<tr>
<td>Kecamatan</td>
<td>
<img src="loading.gif" width="10px" height="10px" id="imgLoad" style="display:none">
<select name="Kecamatan" class="kecamatan">
<option value="" selected="selected">-->Choose Kecamatan<--</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="SUBMIT" /></td>
</tr>
</table>
<script type="text/javascript">
// Get province and send to class city/kabupaten
$("select.profinsi").change(function(){
var IDProfinsi = $("select.profinsi").val();
$("#imgLoad").show("");
$.ajax({
type: "POST",
dataType: "html",
url: "getkabupaten.php",
data: "prov="+IDProfinsi,
success: function(msg){
if(msg == ''){
alert('No Data');
}
else{
$("select.kabupaten").html(msg);
}
$("#imgLoad").hide();
}
});
});
</script>
<script type="text/javascript">
// Get city/kabupaten and send to class kecamatan
$("select.kabupaten").change(function(){
var IDKabupaten = $("select.kabupaten").val();
$("#imgLoad").show("");
$.ajax({
type: "POST",
dataType: "html",
url: "getkecamatan.php",
data: "kab="+IDKabupaten,
success: function(msg){
if(msg == ''){
alert('No Data');
}
else{
$("select.kecamatan").html(msg);
}
$("#imgLoad").hide();
}
});
});
</script>
Code: getkabupaten.php
<?php
include('koneksi.php');
$sel_prov="select * from datakabupaten where IDProfinsi='".$_POST["prov"]."'";
$q=mysql_query($sel_prov);
while($data_prov=mysql_fetch_array($q)){
?>
<option value="<?php echo $data_prov["IDKabupaten"] ?>"><?php echo $data_prov["namakabupaten"] ?></option><br>
<?php
}
?>
Code: getkecamatan.php
<?php
include('koneksi.php');
$sel_prov="select * from all_kecamatan where id_kabkot='".$_POST["kab"]."'";
$q=mysql_query($sel_prov);
while($data_prov=mysql_fetch_array($q)){
?>
<option value="<?php echo $data_prov["id_kec"] ?>"><?php echo $data_prov["nama_kec"] ?></option><br>
<?php
}
?>
If I'm reading your question right you want to have your list updated after a ajax request.
This answer Looks to cover exactly of what you need. Keypoints in the answer by "CMS" are the '.empty()' and '.append()'.
Also I don't think <br /> is necessary in between options of a select list.
EDIT 2/25/2015:
While I still feel my first answer is true, providing a link to a view that I can see whats going on a little better is good. I'm speculating at the inner workings in my answer so, my assessment is:
Consider the html pulled directly from the site:
<tr><td>Kabupaten</td><td>
<div class="selectify focus" tabindex="0" style="width: 189px;">
<div class="header">
<div class="selected" data-id="">-->Pilih Kabupaten<--</div><div class="icon"></div>
</div>
<div class="options" style="width: 189px; max-height: 290px; display: none;">
<div class="option" data-id="" data-text="-->pilih kabupaten<--">-->Pilih Kabupaten<--</div>
</div><!--endheader-->
</div>
<select name="Kabupaten" class="kabupaten" style="display: none;">
<option value="" selected="selected">-->Pilih Kabupaten<--</option>
</select>
</td></tr>
In the Ajax call this line $("select.kabupaten").html(msg); looks for a select list with the class of kabupaten. While your code does have a class and select list with that under the select list you are viewing constituting that you have 2 select lists and the one that has the class 'kabupaten' is hidden with style="display:none;"
I can only speculate if there is more going on in the background at this point. There is some obfuscated code in your template or include files but tracking down where <div class="header"> is coming from will allow you to correctly set the class '.kabupaten` on your select list.
I'm trying to post a selected item from a dropdown list on one php page so that I can access in another php page. The page does not have a submit button so I am using javascript at the bottom of the page. Here's the page that should put the item in post.
<!DOCTYPE html>
<html>
<head>
<?php session_start();?>
</head>
<body>
<select class="myList" name="Country" id="country-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
<option value="" selected="selected">Select Country</option>
<option value="Belgium" data-alternative-spellings="BE Belgiƫ Belgie Belgien Belgique" data-relevancy-booster="1.5">Belgium</option>
</select>
<Script>
$(function () {
$("#country-selector").change(function(){
var x = document.getElementById("country-selector").value;
alert(x);
$.post('page2.php', {'selectedCountry': x});
$.post('page2.php','val='+$(this).val(),function (response){
alert(response);
});
});
});
</script>
</body>
</html>
Then I want page2.php as the target page. I go to page2.php and try to view the post array like this:
<?php
session_start();
echo $_POST['selectedCountry'];
print_r($_POST);
?>
...but the selectedCountry item is not in the $_POST array. How can I put a selected item in a php post array with javascript?
Thanks.
$("#country-selector").change(function(){
var x = document.getElementById("country-selector").value;
$.post('page2.php', {'selectedCountry': x}).done(function(response) {
alert(response);
});
});
I have two files demo.php and post.php. How can I do in single
page instead of two page.
demo.php
<html>
<head>
<title>Dynamic Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" id="other" style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country" style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
</body>
post.php
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
?>
How can I use the post.php data in demo.php without passing data from one page to another.
Change the url of your ajax
$.ajax({
type: "POST",
url: "demo.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
And add this in your demo.php
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
?>
I have a few personal observations:
the first one it's in the approach: I don't think it was a bad idea to have two separate files. This is not really a good optimization. Now you want a single file to handle a GET request and POST in two different ways (one for AJAX one for normal POST in case you want your javascript to degrade gracefully.
you might want to remove that "onchange" attribute. Look into the concept of Unobtrusive JavaScript for why this is good practice
never trust user input: always sanitize and validate appropriately
bellow is a version of your file rewritten. Notices I've re factored the onChange with something more maintainable and I'm using JS to make the initial hiding of the input and submit button. This way if JS is disabled the user can still add countries.
in order to determine how the post was triggered I pass an extra flag ajax=1 to the post.
<?php
$country = filter_input(INPUT_POST, 'other');
// Ajax
if (isset($_POST['ajax']))
{
echo 'Successfully added country: ' . $country;
exit();
}
// normal post
else
{
echo $country;
}
?>
Dynamic Form
$(document).ready(function(){
$('#country').on('change', hideStuff);
// hide the buttons to add extra option
$('#other, #submit').hide();
function hideStuff()
{
var select = $(this);
var flag = select.val() === 'other';
$('#other, #submit').toggle(flag);
}
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize() + "&ajax=" + 1;
$.ajax({
type: "POST",
url: $(this).data('url'),
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form method="post" data-url="<?php echo basename(__FILE__); ?>">
<table>
<tr>
<td>
<select id="country" name="one">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input id="other" type="textbox" name="other">
<input id="submit" type="submit" name="submit" value="Add Country">
</td>
</tr>
</table>
</form>
</body>
that's very easy, just paste the below code on to the upper code.
And remove the jquery ajax call.
<html>
<head>
<title>Dynamic Form</title>
</head>
<body>
<form action="post">
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" id="other" style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country" style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
</body>
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
?>
You can change the url into demo.php and use the below one along with exit();,
<?php
if(isset($_POST['submit'])){
$Country = $_POST['other'];
echo $Country;
exit();
}
?>
first you change the url of $ajax
$.ajax({
type: "POST",
url: "demo.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
and then change your "demo.php"
<html>
<head>
<title>Dynamic Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
else{
?>
<form>
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other') {this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other"id="other"style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country"style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
<?php } ?>
</body>
Try this
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
var yData = $(this).serialize();
$.post('demo.php', {action:"other",yourData:yData}, function(msg) {
alert( "Data Saved: " + msg );
});
});
</script>
<?php
if($_REQUEST['action']=="other")
{
$country= $_REQUEST['yourData'];
echo $country;
exit;
}
?>
Hopefully this will help you but I don't understand what "data" is. Make sure it is a field or the variable which is supplying value that is required for the page.
$("form").on("submit",function() {
$.ajax({
type : "GET",
cache : false,
url : "post.php",
data : {
data : data
},
success : function(response) {
$('#content').html(response);
}
});
});
I am developing a list of submissions in the admin area of my website, which I can approve/disprove with a form, with an ID of the submission in a hidden input, and the select box with Approve/Reject in. When the select box is changed, the ajax submits the form, along with the hidden ID input, then the PHP script edits the submission in the database.
It was all working fine with one submission (1 form) on the page, but now there is more than one form, it is POSTing the wrong values to the PHP script.
<tbody>
<?php
// connect to mysql
mysql_connect('#######', '#######', '#######');
mysql_select_db('jcvideos');
// query
$query = mysql_query("SELECT * FROM videos");
// loop thru
while($row = mysql_fetch_assoc($query)) {
?>
<tr<?php if($row['accepted']==0) {echo " class='warning'";}?>>
<td><?php echo $row['id'];?></td>
<td>
<a href="//youtu.be/<?php echo $row['ytid'];?>" target="_blank">
<?php
$url = "http://gdata.youtube.com/feeds/api/videos/". $row['ytid'];
$doc = new DOMDocument;
$doc->load($url);
echo $doc->getElementsByTagName("title")->item(0)->nodeValue;
?>
</a>
</td>
<td><?php echo $row['date'];?></td>
<td>
<a href="mailto:<?php echo $row['submitter'];?>">
<?php echo $row['submitter'];?>
</a>
</td>
<td>
<form id="form<?php echo $row['id'];?>" class="reviewform" method="post" action="review.php">
<input type="hidden" value="<?php echo $row['id'];?>" name="vidid">
<select name="status">
<option value="0"<?php if($row['accepted']==0) {echo ' selected';}?>>Pending review</option>
<option value="1"<?php if($row['accepted']==1) {echo ' selected';}?>>Rejected</option>
<option value="2"<?php if($row['accepted']==2) {echo ' selected';}?>>Accepted</option>
</select>
</form>
</td>
<td><?php echo $row['showdate'];?></td>
</tr>
<?php
} // end of loop
?>
</tbody>
</table>
<?php include('../includes/footer.php');?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$("select").change(function(){
$('.reviewform').ajaxSubmit();
});
</script>
I tried using IDs, then it didn't POST at all. What am I missing here?
You can try this assign common class like i have assigned in fiddle (status) to selectbox then get the form by the change of its children (<select>) like in fiddle i tried to get the id of from by change event of its child element (<select>) ,once you got the id get the data of form and submit it
$('.status').on('change', function(){
var id=$(this).parent("form").attr('id');
alert(id)
$('#'+id).ajaxSubmit();
/* $("#"+id).serialize() form data */
});
See Fiddle
It depends on your event listener/selector:
$("select").change(function(){
$('.reviewform').ajaxSubmit();
});
This will always submit .reviewform even if a select of anoter form has been changed.
(Basicly it registers the function for the change event of all select tags in you page)
Please try:
$(".reviewform select").change(function(){
$('.reviewform').ajaxSubmit();
});
$(".anotherform select").change(function(){
$('.anotherform').ajaxSubmit();
});