I have a dropdown list with 5 options, whenever I click the submit button in the modal, the value posted to the controller is not the one I had selected.
Here is my view code
<div class="form-group">
<div class="col-md-4">
<select class="form-control" name="procode" id="procode" >
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="AOC">APS</option>
<option value="ATN">ADS</option>
<option value="AOC">ATW</option>
<option value="ATN">ATB</option>
</select>
</div>
</div>
And my ajax code for submiting the data to controller is here
var url;
url = "<?php echo site_url('person/ajax_add_claim')?>";
$.ajax({
url : url,
type: "POST",
data: $('#formclaim').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status)
{
$('#modal_form').modal('hide');
$('#modal_form').removeData();
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
$('#btnSave').text('save');
$('#btnSave').attr('disabled',false);
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#btnSave').text('save');
$('#btnSave').attr('disabled',false);
}
});
This is a silly question to answer. But here you go:
<div class="form-group">
<div class="col-md-4">
<select class="form-control" name="procode" id="procode" >
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="APS">APS</option>
<option value="ADS">ADS</option>
<option value="ATW">ATW</option>
<option value="ATB">ATB</option>
</select>
</div>
</div>
Do you notice the difference?
The option in your dropdown contains similar values, that might be the cause of the problem.
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="AOC">APS</option>
<option value="ATN">ADS</option>
<option value="AOC">ATW</option>
<option value="ATN">ATB</option>
Try replacing the values with some other data. Just to test, whether the code is working or not.
Show us a bit of controller code to see what and how you are displaying the dropdown data.
Can you please share your controller function and reload_table function of Javascript. i think you are not returning accurate data from Controller function. You should use like this.
$drop_downdata = $this->db->function(your db query);
/* you pass this data to view like this create a page with this name dropdown_page.php */
$dropdown_view['page'] = $this->load->view('dropdown_page',array('data'=>$drop_downdata),TRUE);
$this->output->set_content_type('application/json')->set_output(json_encode($dropdown_view));
View Page dropdown_page.php
<?php foreach($data as $value): ?>
<li><?=$value->column_name?></li>
<?php endforeach; ?>
you will simple get this Drop down in this way
`$("#dropdown_id or class").html(response.page)`.
It will show your dropdown according to your request
Related
i have two select option list with values retrieved from db .
<select id="userid" onchange="selSuj()">
<option value="1" selected="selected">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
<select id="subject">
<div id="determineSubj">
<option value="1" selected="selected">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</div>
</select>
<script>
function selSuj(){
var x = $('#userid').val();
$.ajax({
type:'POST',
url:'same page url',
data:{
'userid':x
},
success: function(result){
document.getElementById("determineSubj").innerHTML = result;
}
})
;
}
the first select option(userid),when option selected, should populate the corresponding values in the second select option(subject), using the user option value(eg 1,2,3) as search p.key to the subject db.
I have tried using ajax, it worked out well on alert(result), but does not update the second select option values. please help.
A select should not contain a <div>.
As we can see from this brief demo, doing so makes the div inaccessible to JavaScript, because it doesn't consider it to be a valid part of the DOM:
document.addEventListener("DOMContentLoaded", function() {
console.log(document.getElementById("determineSubj"));
});
<select id="subject">
<div id="determineSubj">
<option value="1" selected="selected">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</div>
</select>
In any case, even if it was valid, it's entirely unnecessary for your purpose. You can just update the HTML of the select element directly.
Change the HTML to:
<select id="subject">
<option value="1" selected="selected">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
And the "success" callback to:
success: function(result) {
document.getElementById("subject").innerHTML = result;
}
and there shouldn't be any problem.
I have two selects, the second one is hidden and it should be shown if the first select has been changed, I checked it through on('change', function(){ ... and it is working so far. I've checked and also showed a console.log when the first select box is changed.
The main problem here is when I picked a option from the first select box, it should send some request using AJAX. I've sent some request to fetch_sections.php and it should append or add data in my second select box.
This is my updated script:
<script>
$(document).ready(function() {
$('select').material_select();
$('#school-list').on('change', function() {
$.ajax({
url: 'fetch_sections.php',
type: 'post',
dataType: 'html',
data: {parent: $(this).val() },
success: function(data)
{
$('#section-list').empty();
$('#section-list').html(data);
console.log(data);
}
});
$('#hideThis').show("slow");
});
});
</script>
This is my fetch_sections.php (working, checked with PostMan):
<?php
require '../assets/php/init.php';
if ($_POST)
{
$schoolID = Essentials::sanitize($_POST['parent']);
$fetchSQL = "SELECT `sectionid`, `name` FROM `sections` WHERE schoolid = ?";
$fetch = $conn->prepare($fetchSQL);
$fetch->execute([$schoolID]);
$fetchRes = $fetch->fetchAll(PDO::FETCH_ASSOC);
if(!$fetchRes) {
echo '
<option value="" disabled selected>Unfortunately, there is no section here.</option>
';
} else {
foreach ($fetchRes as $section)
{
echo '
<option value="'.$section['sectionid'].'"">'.$section['name'].'</option>
';
}
}
}
This is my select HTML also updated:
<div class="row margin">
<div class="input-field col s12">
<select id="school-list" name="school-list">
<option value="" disabled selected>Choose your school</option>
...
</select>
<label>School</label>
</div>
</div>
<div class="row margin" id="hideThis" style="display:none">
<div class="input-field col s12">
<select id="section-list" name="section-list">
<option value="" disabled selected>Choose your section</option>
</select>
<label>Section</label>
</div>
</div>
Update [as suggested by ccKep]:
I can now see the data that I want through console.log(data), the thing that it outputs is:
<option value="9-1">9-A...</option>, now I want to add it to my main select list but it doesn't let me.
The output should be:
<select id="section-list" name="section-list">
<option value="" disabled selected>Choose your section</option>
<option value="9-1">9-A...</option>
</select>
I am trying to build a form where the user fills information in and clicks submit. Upon clicking, the page will never refresh. Form processing and data handling will happen after the user clicks.
I am trying to use jQuery and Ajax to accomplish this, so far this is what I have:
HTML
<form class="article_information_form" action="" method="POST">
<label>Title </label>
<input type="text" name="articleTitle"> <br>
<label>Article URL: </label>
<input type="text" name="articleUrl"> <br>
<p>Number of pages</p>
<select name="numPages">
<option value="" selected></option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br>
<?php echo $message;?> //For Debugging
<input type="submit" name="article_info_btn" value="Submit">
</form>
PHP
if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
$message = "Success!"; //For debugging
}
Ajax
$(document).on('submit', '.article_information_form', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : '',
success : function(data) {
alert("Success!");
}
})
})
Upon clicking the submit button, the success window popup alert is shown.
Though, the $message variable never prints out "success!" This means that its not processing the PHP $_POST.
How do I make it so that Ajax sends the information to the PHP $_POST?
$( ".article_information_form" ).on( "submit", function( event ) {
event.preventDefault();
$.post(window.location , $( this ).serialize() , function(result){
alert(result);
});
});
You didnt attach the data payload!!
Since you wanted the entire thing to be on a single page, this would be a possible way:
Full code for easy understanding:
<?php
//exececuted only if POST request as in the ajax below.
if($_SERVER[ 'REQUEST_METHOD']==='POST' ){
//your processing here
header( 'Content-Type: application/json');
//lets set the receivedToServer property to what data we got
$data = array();
$data['receivedToServer'] = $_POST;
//output data as json
echo json_encode($data);
//kill the page once the data is displayed
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<form class="article_information_form" action="" method="POST">
<label>Title </label>
<input type="text" name="articleTitle">
<br>
<label>Article URL: </label>
<input type="text" name="articleUrl">
<br>
<p>Number of pages</p>
<select name="numPages">
<option value="" selected></option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br>
<input type="submit" name="article_info_btn" value="Submit">
</form>
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$('.article_information_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '',
data: $(this).serialize(),
success: function(data) {
//the processed data available as data variable.
//lets log the data received at server property we set before
console.log(data.receivedToServer);
alert(data.receivedToServer.articleTitle);
}
});
})
</script>
</html>
You are not pass data to your method so it is not working. So first you will check how many argument have in method, then you send same number of string in params.
You should note one thing about argument are same name as use in method argument name.
$(document).on('submit', '.article_information_form', function(e)
{
e.preventDefault();
$.ajax({
type : 'POST',
url : '',
params : {articleTitle: 'Titlename', articleUrl : 'URLName',numPages : 'PagesNo'}
success : function(data)
{
alert("Success!");
}
})
});
On your form add an ID, in our case I put an id="form_submit" and action="action.php", you need to replace it with your own path where the action should do.
<form id="form_submit" class="article_information_form" action="action.php" method="POST">
also this line of the form,
<input type="button" id="submit" name="article_info_btn" value="Submit">
change the type type="bumit" to type="button" to prevent default submission.
and the jquery,
$('#submit').click(function() {
var submit_url = $(this).parent('form').attr('action');
$.ajax({
type : 'POST',
url : submit_url,
data : $('#form_submit').serialize(),
dataType : 'json',
success : function(data) {
alert("Success!");
}
})
})
This line var submit_url = $(this).parent('form').attr('action'); get the path on the action="" and use that path to passed data.
You need to add data to your ajax call:
$(document).on('submit', '.article_information_form', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
//url: '', by default is the current page url.
data: $('.article_information_form').serialize(),//This line
success: function(data) {
$('.article_information_form type["submit"]').before("<div>"+data+"</div>")
}
})
})
PHP:
if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
echo "Success!"; //For debugging
exit();
}
Like the others have said, you need to add a data parameter to your $.ajax() call.
Your other question - reading the comments - is about how you can get the PHP $message variable to show up without a page load.
That is, unfortunately, impossible without a page-refresh because PHP is rendered on the server side.
What I would suggest, is creating another PHP file that handles the logic that you're trying to create, and then using AJAX to throw the response back onto the current page. Achieving what I believe you want to do.
So! Example time.
first.php
<!doctype html>
<html>
<head><title>First</title></head>
<body>
<form id="myForm">
<input name="email" type="email" />
<button>Go!</button>
</form>
<div id="message"></div>
<script>
$('#myForm').on('submit', function(event){
event.preventDefault();
$.ajax({
type: 'POST',
data: $().serialize(); // send the form data to..
url: 'second.php', // your new PHP page
complete: function(xhr, status){
console.log('xhr', xhr);
console.log('status', status);
$('#message').text(status);
}
});
});
</script>
<body>
</html>
second.php
<?php
if (isset($_POST["email"]) {
echo "Success!";
} else {
echo "Error!";
}
?>
1- Your Ajax Code :-
<script>
$(function() {
$(".article_information_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "process_page.php",
type: "post",
data: $(this).serialize(),
success: function(html) {
$('#msg').html(html);
}
});
});
});
</script>
2- To print AJAX response add the following "div" under the "body" tag :-
##<div id='msg' ></div>
3- Create a PHP page "process_page.php" to receive the submitted data and then send the result
<?php
$numPages = $_POST['numPages'];
echo $numPages; //anything you echo here will be displayed in the <div id='msg'> at the main page
?>
good luck
I have an issue in checking form element SELECT at server PHP code.
I found a similar link here, but it is slightly different in discussion.
My HTML code is
<body>
<div id="header">
<h1>Please add your landed property to advertise</h1>
</div>
<div id="background">
<form name="advertiseForm" id="advertiseForm" method="post" >
<br /><br /><br />
<select name="stories" id="stories" required="required"/>
<option value="Stories" >Number of stories</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="morethan4">More than 4</option>
<select/>
<label for="stories">Please select for number of stories</label>
<div id="stories-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="bedrooms" id="bedrooms" required="required"/>
<option value="Bedrooms" >Number of bedrooms</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<select/>
<label for="numbedrooms">Please select for number of bedrooms</label>
<div id="bedrooms-error" class="error-box" style="color:#FF0000"></div>
</form>
</body>
I have two SELECT elements at my form and form elements are sent to server using AJAX using data: $("form").serialize(),.
</body>
<script>
function sendtoServer() {
$.ajax({
url: "advertisementdatavalidationatserver.php",
type: "POST",
data: $("form").serialize(),
success: function(ret){
alert(ret.message);
if(ret.error == true){
if(ret.message.indexOf("Storieserror")>=0){
$('#stories-error').css('display', 'block');
$('#stories-error').html('Please enter number of stories at your building');
}else{
$('#stories-error').html('');
}
if(ret.message.indexOf("Bedroomserror")>=0){
$('#bedrooms-error').css('display', 'block');
$('#bedrooms-error').html('Please enter number of bedrooms at your building');
}else{
$('#bedrooms-error').html('');
}
}else{
$('#stories-error').html('');
$('#bedrooms-error').html('');
}
},
error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
}
</script>
</html>
My PHP code at server side for validation is
<?php
$data = array();
$data['error'] = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['stories'] == "Stories"){
$data['error'] = true;
$data['message'][] = "Storieserror";
}
if ($_POST['bedrooms'] == "Bedrooms"){
$data['error'] = true;
$data['message'][] = "Bedroomserror";
}
}
// then echo the $data array you have built as JSON to use in jquery.
//This will be what is returned in your AJAX request
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($data);
?>
The problem here is for SELECT for bedrooms, no matter how I change option values to 1,2,3,4,.., the server side always comes back as Bedroomserror, that means no matter how I change other option values, client side always send 'Bedrooms' value to server.
Stories is working fine.
What could be the problem?
EDIT:
Now I found my problem. I see the serialized data as
alert($("form").serialize());
What the serialized data is shown in the attached image, interesting thing there is there are repeated data (underlined). The first one is fine stories=3&bedrooms=2&bathrooms=2. Then there is another repeated message with bedrooms=Bedrooms&bathroom=Bathrooms, I think my PHP code caught the second one and the value is never changed.
When recreating your code for testing here, I did not encounter the problem you describe. Selecting a numbered option for bedrooms did not display an error, and the returned value was correct.
To troubleshoot this type of issue, I'd suggest the following:
Make sure the values being serialized by your sendToServer javascript function are what you expect. Output them via console.log() or similar to check that what you select in the form is actually being sent to the PHP script.
I had to makes some changes to the code you provided to get it working. My assumption here is that you already have this in place, but it's not included in your question so I've referenced the changes I made below, as they were required to get the test working:
Add a valid DOCTYPE and head tag to the HTML markup
Add an input button to the form for submission
Add a script tag which pulls in jQuery
Wrap the call to your sendToServer function in a $(document).ready(function(){}); call, triggered by a click event on the input submit element (or however you submit the form)
[Optional] I added an else section after your if statement checking the $_POST['bedrooms'] value, so that I could check what the selected value was
Hope this helps.
in your html form code place a hidden field
<input type="hidden" id="bedroomsVal" name="bedroomsVal" value="" />
in php code check value of bedroomsVal
if ($_POST['bedroomsVal'] == "Bedrooms"){
//your logic
}
in js do this
$(document).ready(function(){
$("#bedroomsVal").val($("#bedrooms option:selected").text());
$("#bedrooms").change(function(){
$("#bedroomsVal").val($("#bedrooms option:selected").text());
});
})
At the first step you need to pass the parameters from your AJAX code to PHP page. then you can check the posted value in your PHP section.
HTML
<select name="stories" id="stories" required="required"/>
<option value="Stories" >Number of stories</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="morethan4">More than 4</option>
</select>
<select name="bedrooms" id="bedrooms" required="required"/>
<option value="Bedrooms" >Number of bedrooms</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<select/>
JavaScript
<script>
function sendtoServer() {
$.ajax({
url: "advertisementdatavalidationatserver.php",
type: "POST",
data: {story: $('#stories').val(), bedroom: $('#bedrooms').val()},
success: function(ret){
// Any logic when return TRUE;
},error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
}
PHP
Check the all posted parameters
<?php
if(! isset($_POST)){
// return FALSE;
}
else
{
// check the posted parameters
// write your query;
// return TRUE or retrieved value
}
?>
I have this simple dropdown menu in my codeigniter form. When clicking dzongkhag(district) it should display the list of geogs(towns), but, instead it do not do so. The drop down menu that I have is not the best one but that is what I could come up with after trying (for many weeks) many times unsuccessfully. I will be grateful if someone could help me out/solve/advice on this.
Here are the snippets.
view.php
<label >Dzongkhag: </label>
<select id="user_dzongkhag" name="dzongkhag" >
<option>Select Dzongkhag</option>
<option value="Bumthang">Bumtang</option>
<option value="Chhukha">Chhukha</option>
<option value="Dagana">Dagana</option>
<option value="Gasa">Gasa</option>
<option value="Haa">Haa</option>
<option value="Lhuentse">Lhuntse</option>
<option value="Monggar">Monggar</option>
<option value="Paro">Paro</option>
<option value="Pema Gatshel">Pema Gatshel</option>
<option value="Punakha">Punakha</option>
<option value="Samdrup Jongkhar">Samdrup Jongkhar</option>
<option value="Samtse">Samtse</option>
<option value="Sarpang">Sarpang</option>
<option value="Thimphu">Thimphu</option>
<option value="Trashigang">Trashigang</option>
<option value="Trashi Yangtse">Trashi Yangtse</option>
<option value="Trongsa">Trongsa</option>
<option value="Tsirang">Tsirang</option>
<option value="Wangdue Phodrang">Wangdue Phodrang</option>
<option value="Zhemgang">Zhemgang</option>
</select>
<label >Geog:</label>
<select id="user_geog" name="geog" >
<option> select geog</option>
</select>
javascript (which I implement it in the view.php instead of js folder)
$(document).ready(function(){
$('#user_dzongkhag').change(function(){
$('#user_geog').html('<option> Fetching...</option>');
var user_dzongkhag =$('#user_dzongkhag').val();
//alert(new_div);
$.ajax({
type:"post",
data:"user_dzongkhag="+user_dzongkhag,
url:"<?php echo site_url('ajax/select_auth_geog/'); ?>",
cache:false,
success:function(resp){
//alert(resp);
$('#user_geog').html(resp);
}
});
});
});
controller.php
public function select_auth_geog(){
$user_dzongkhag= $this->input->post('user_dzongkhag');
$returnGeog=$this->ajax_model->select_auth_geog($user_dzongkhag);
foreach ($returnGeog as $key) {
echo '<option value="'.$key['name'].'">'.$key['name'].' </option>';
}
}
model.php
public function select_auth_geog($user_dzongkhag){
if($user_dzongkhag=='Bumtang'){
$user_dzongkhag=1;
}elseif($user_dzongkhag=='Chhukha'){
$user_dzongkhag=2;
}elseif($user_dzongkhag=='Dagana'){
$user_dzongkhag=3;
}elseif($user_dzongkhag=='Gasa'){
$user_dzongkhag=4;
}elseif($user_dzongkhag=='Haa'){
$user_dzongkhag=5;
}elseif($user_dzongkhag=='Lhuntse'){
$user_dzongkhag=6;
}elseif($user_dzongkhag=='Monggar'){
......
........
Try switching these two lines, you may be deleting the select box value before it is stored in user_dzongkhag.
$(document).ready(function(){
$('#user_dzongkhag').change(function(){
$('#user_geog').html('<option> Fetching...</option>'); <-------------
var user_dzongkhag =$('#user_dzongkhag').val(); <-------------
//alert(new_div);
$.ajax({
type:"post",
data:"user_dzongkhag="+user_dzongkhag,
url:"<?php echo site_url('ajax/select_auth_geog/'); ?>",
cache:false,
success:function(resp){
//alert(resp);
$('#user_geog').html(resp);
}
});
});
});