I am trying to make a small webpage doing the following :
1. The user selects a level then depending on the choice, there will be some options appearing as checkboxes.
2. The user can choice one or multiples options
I would like to make appear on the same page dynamically the options he or she chooses and the value associated to this. The value is stored in a mySQL database.
The first step is working but not the second one. If some one could help me ? Once the checkbox is checked or not, the page is not updating.
Here is my test code :
Code HTML
<script>
$(document).ready(function(){
$('#id_class').on('change', function(){
var _class = $(this).val();
if(_class){
$.ajax({
type:'GET',
url:'ajaxData.php',
data:'_class='+_class,
success:function(html){
$('#id_opt').html(html);
}
});
}else{
$('#id_opt').html('<option value="">Complete CP first</option>');
}
});
});
$(document).ready(function(){
$('#id_sci').on('click change', function(){
var _sci = $(this).val();
if(_sci){
$.ajax({
type:'GET',
url:'ajaxDataPrice.php',
data:'_sci='+_sci,
success:function(html){
$('#id_price').html(html);
}
});
}else{
$('#city').html('<option value="">Complete CP first</option>');
}
});
});
</script>
<body>
<form action="test_menu.php" method="POST">
<select id="id_class" name="_class">
<optgroup label="Primaire">
<option value="CP">CP</option>
<option value="CE1">CE1</option>
<option value="CE2">CE2</option>
<option value="CM1">CM1</option>
<option value="CM2">CM2</option>
</optgroup>
<optgroup label="Collège">
<option value="6ème">6ème</option>
<option value="5ème">5ème</option>
<option value="4ème">4ème</option>
<option value="3ème">3ème</option>
</optgroup>
</select>
<input id="id_intern" type="checkbox" name="_intern" value="Yes"> Interne / Externe
<div id="id_opt">
</div>
<br>
<b>Montant à payer :</b>
<div id="id_price">
</div>
<p>
Code PHP
if(!empty($_GET['_sci']))
{
if ($_SESSION['_nbOpt'] > 0)
{
if ($_GET['_sci'] == "Yes")
$_SESSION['_nbOpt'] += 1;
else
$_SESSION['_nbOpt'] -= 1;
}
elseif ($_SESSION['_nbOpt'] == 0)
{
if ($_GET['_sci'] == "Yes")
$_SESSION['_nbOpt'] += 1;
}
$_priceOpt = $_SESSION['_nbOpt']*5;
$_priceTotal = 6 + $_priceOpt;
echo 'Prix matières : 6 € <br>
Prix matières opt : '.$_priceOpt.' € <br>
Prix total : '.$_priceTotal.' € <br>';
;
}
You should use the ajax GET for sending data as below. I think your $_GET might not received the data in php. Once changed the code clear all your browser caches and check.
<script>
$(document).ready(function(){
$('#id_class').on('change', function(){
var _class = $(this).val();
if(_class){
$.ajax({
type:'GET',
url:'ajaxData.php',
data:{'_class':_class}, //changes done here
success:function(html){
$('#id_opt').html(html);
}
});
}else{
$('#id_opt').html('<option value="">Complete CP first</option>');
}
});
});
$(document).ready(function(){
$('#id_sci').on('click change', function(){
var _sci = $(this).val();
if(_sci){
$.ajax({
type:'GET',
url:'ajaxDataPrice.php',
data:{'_sci':_sci}, //changes done here
success:function(html){
$('#id_price').html(html);
}
});
}else{
$('#city').html('<option value="">Complete CP first</option>');
}
});
});
</script>
Related
how can i use a set_select option on ajax part for a dynamic dependent dropdown list, this list is clearing after validation errors, so i want to use set_select option here. kindly see below code:
<script type="text/javascript">
$(document).ready(function() {
$('select[name="relegion"]').on('change', function() {
var regID = $(this).val();
if(regID) {
document.write("ok");
$.ajax({
url: '/demo/main/selectcaste/'+regID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="caste"]').empty();
$('select[name="caste"]').append('<option value=1>'+ "Not Interested to specify" +'</option>');
$('select[name="caste"]').append('<option value=2>'+ "InterCaste" +'</option>');
$.each(data, function(key, value) {
$('select[name="caste"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="caste"]').empty();
}
});
});
Maybe you need something like this,
View code.
<select name="category" id="category">
<option>Pilih Kategori Kelas</option>
<option value="1">category 1</option>
<option value="2">category 2</option>
</select>
<select name="sub_category" id="sub_category">
<option>Pilih category Kelas</option>
</select>
AJAX code.
$(document).ready(function(){
$('#category').on('change',function(){
var category_id = $(this).val();
if(category_id){
$.ajax({
type:'POST',
url:'<?php echo base_url()."profile_kelas/get_sub_category";?>',
data: {
category_id : category_id
},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option>Pilih Sub category Kelas</option>');
}
});
});
My Controller code.
public function get_sub_category(){
$data = $this->model_profile->get_sub_category($_POST['category_id']);
foreach ($data as $row) {
echo '<option value="'.$row->id.'">'.$row->sub_category.'</option>';
}
}
You can make your parent category dynamically.
In my project, I use jqpagination. And I want to define the records of each page, so I use select tag in my web page.
The problem is when I change select tag, the value returned from lstajax.php is not the same. sometimes it is xie1, but sometimes it is xie2.
I have tested, the returned value is random. For example, when i chosed 30 first, the value is xie1. When i chosed 30 next time, the value maybe xie1 or maybe xie2.
My js code:
<link rel="stylesheet" href="jsui/jqpagination.css" />
<script src="jsui/jquery-3.2.1.min.js"></script>
<script src="jsui/jquery.jqpagination.js"></script>
<script>
$(document).ready(function()
{
var rtnv = "<?php session_start();echo $_SESSION['rtNum']?>";
var pgrNum=$('#pgnId').val();
var mpn=Math.ceil(rtnv/pgrNum);
$('.pagination').jqPagination({
max_page:mpn,
page_string:'Page {current_page} of {max_page}',
paged:function(page){
$.ajax({
dataType:'html',
type:"POST",
url:"lstajax.php",
data:{pageNum:page,pgrNum:pgrNum},
success:function(data)
{
$('#div2').html(data);
}
});
}
});
$('#pgnId').change(function(){
var pages="1";
$('.pagination').jqPagination('option','current_page',pages);
var rtnvs = "<?php session_start();echo $_SESSION['rtNum']?>";
var pgrNums=$('#pgnId').val();
var mpns=Math.ceil(rtnvs/pgrNums);
$('.pagination').jqPagination('option','max_page',mpns);
$.ajax({
dataType:'html',
type:"POST",
url:"lstajax.php",
data:{pageNums:pages,pgrNums:pgrNums},
success:function(data)
{
$('#div2').html(data);
}
});
});
});
</script>
My lstajax.php code:
<?php
if(isset($_POST['pageNum']))
{
echo "xie1";
}
if(isset($_POST['pageNums']))
{
echo "xie2";
}
?>
My html code:
<div class="pagination" style="clear:both;display:block;margin-left:40%">
«
‹
<input type="text" readonly="readonly" data-max-page="80"/>
›
»
<label>eachpage:</label>
<select name="pgNum" id="pgnId">
<option value="10">10</option>
<option value="15">15</option>
<option value="20" selected="selected">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
var options={'trigger':false}
in the method:
base.cassMthod=function(method,key,value)
in the file:
jquery.jqPagination.js
How do I want to post a form using jquery serialize function? I tried to post the form value but on the php part, the value is not shown. Below are my codes:
html
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
jQuery
$(document).on("click", "#submit", function(e){
e.preventDefault();
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
data = $('form').serialize();
$.post('result.php',
{
data : data
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
});
PHP
if(isset($_REQUEST["sort"])){
$sort = $_REQUEST['sort'];
$id_staff = $_REQUEST['id_staff'];
echo "Your Id : $id_staff <p/>";
echo "You choose : $sort";
}
If I console.log(data), I get: id_staff=12345&sort=1
Your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):
"param1=someVal¶m2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array that contains all the form element as indexes
If you are using .serialize, you can get rid of this:
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
You data will be available as follows with .serialize:
your-url.com/sort=yoursortvalue&id_staff=youridstaff
It should be:
$(document).ready(function(e) {
$("#myform").submit(function() {
var datastring = $( this ).serialize();
$.post('result.php',
{
data : datastring
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
})
})
On PHP side you simple need to access it using the $_GET['sort'].
Edit:
To view the data, you should define a div with id result so that the result returned is displayed within this div.
Example:
<div id="result"></div>
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
I am able to do it this way:
jQuery
<script type="text/javascript">
$(document).ready(function() {
var form = $("#myform");
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'result.php',
data: form.serialize(),
success: function(response) {
console.log(response);
$("#result").html(response);
},
error: function() {
alert('Error Submitting');
}
})
})
})
</script>
PHP
if(isset($_POST["id_staff"])){
$sort = $_POST['sort'];
$id_staff = $_POST['id_staff'];
echo "<p>Your Id : $id_staff</p>";
echo "You choose : $sort";
}
Do give a comment if it need improvement or better solution.
I have a select option, to get the value from this, I used jquery (please see below code). After I display the selected value in the textbox, I'm now having problem on how to get the value of textbox to process a such code. Even simply echo of the value is not working. What's the problem with the code? Please help. Thanks.
Select option:
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
Jquery:
$('#shiptype').change(function () {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
}
});
Text Field:
<input type='text' id='strkey' name='keyname' />
Display the value:
$key = $_POST['keyname'];
echo $key;
Please try this code :
HTML file contains this below code. File name test.html.
Form to submit your data.
<form id="frm_post">
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
<input type="text" name="name" id="strkey">
<input id="btn_post" type="button" name="submit" value="Submit">
</form>
This is a div for your output.
<div>
<p id="output"></p>
</div>
This is jquery for ajax call function.
<script>
$(document).ready(function(){
$('#shiptype').change(function() {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
}
});
$("#btn_post").click(function(){
var parm = $("#frm_post").serializeArray();
$.ajax({
type: 'POST',
url: 'your.php',
data: parm,
success: function (data,status,xhr) {
console.info(data);
$( "#output" ).html(data);
},
error: function (error) {
console.info("Error post : "+error);
$( "#output" ).html(error);
}
});
});
});
</script>
And for PHP File to get the post value like this below. File name your.php.
<?php
// $key = $_POST['keyname'];
// echo $key;
print_r($_POST);
?>
Your post result will be show up in output id. Hope this help you out. :D
This question is SOLVED - solution is on the bottom of the question.
Let's say I have this form:
<form id="form1" action="" method="POST">
<select name="cars">
<option value="">Choose a car</option>
<option value="Ferrari">Ferrari</option>
<option value="Lamborghini">Lamborghini</option>
</select>
<select name="colors">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
Php:
$cars = $_POST['cars'];
$colors = $_POST['colors'];
echo "Car: ".$cars." - Color: ".$colors."";
Ajax:
<script type='text/javascript'>
$('select[name="colors"]').on('change', function(){
$.ajax({
type: "POST",
url: "phpfile.php",
data: $("#form1").serialize(),
success: function(data){
$('#target1').html(data);
}
});
return false;
})
</script>
I want to show on html the results:
<div id="target1"></div>
I want to show the results when I choose the color (The 2nd dropdown):
onchange="this.form.submit()"
IT IS DONE:)
I used this code and it I am getting what I want:
<script type='text/javascript'>
$("#colorID").on("change", function() {
var $form = $("#form1");
var method = $form.attr("method") ? $form.attr("method").toUpperCase() : "GET";
$.ajax({
url: 'phpfile.php',
data: $form.serialize(),
type: method,
success: function(data){
$('#target1').html(data);
}
});
});
</script>
Technically you dont need ajax to get what your asking for but heres jQuery ajax example:
Change your HTML to:
<select name="colors" onchange="this.form.submit()">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
$( "#form1" ).submit(function( event ) {
event.preventDeafault();
alert('form submitted');
$.ajax({
type: "POST",
url: "<YOUR PHP FILE PATH>",
data: $("#form1").serialize(),
success: function(data){
alert('ajax success');
$('#target1').html(data);
}else{
alert('ajax error');
}
});
return false;
})
In your PHP:
print_r($_POST);
$car = $_POST['car'];
$color = $_POST['color'];
echo "<p>Car: ".$car." - Color: ".$color."</p>";
This is untested - I've just typed it out on my phone during my lunch break!
To debug the php add this line ( to unsure the post worked):
print_r($_POST);
Use your browser developer tools to debug your AJAX and JS
I've add alerts to help you debug - you can remove these when its working