dynamic dependent dropdown using ajax codeigniter - javascript

I want to make dropdown where I select the value and it can fetch data from database without submit button.
I paste my code here I am student and making project I shall be very thankful to you please help...
My controller is
public function find($id)
{
$product=$this->user_model->find($id);
echo "ID ".$product->email;
}
Model is
public function find($id)
{
$this->db->where('id',$id);
return $this->db->get('users')->row();
}
View file:
<script type="text/javascript">
$(document).ready(function() {
$('#slt').change(function(){
var country_id = $('#slt').val();
$.ajax({
type: 'GET',
url: "<?php echo base_url('index.php/main/find/')?>"+country_id,
success: function(result)
{
$('#result').html(result);
}
});
});
});
</script>
<form>
<input type="button" value="find" id="btnfind"/>
<select name="opt" id="slt">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">one</option>
<option value="4">two</option>
</select>
<br/>
<div id="result"></div>
</form>

<script type="text/javascript">
$(document).ready(function(){
$('#slt').change(function(){
var country_id = $('#slt').val();
$.ajax({
type:'GET',
data:country_id,
url:"<?php echo base_url('index.php/main/find/')?>",
success:function(result)
{
$('#result').html(result);
}
});
});
});
</script>

Change $('#result').html(result) to $('#result').text(result)

Related

How can i use dropdown in table <td> tag

I have an Inline editable Table which updates the Mysql table for the team group column I want to use the drop-down list.
But the table is saving all the value of Dropdown instead of the one i have selected
Below is the code I'm working with and few screenshot for your reference
<td class="editable-col" contenteditable="True" col-index='5' oldVal ="<?php echo $res['TeamGroup'];?>" nowrap>
<?php echo $res['TeamGroup'];?>
<select required>
<option value="">None</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</td>
As suggested i'm adding the script-
<script type="text/javascript">
$(document).ready(function(){
$('td.editable-col').on('focusout', function() {
data = {};
data['val'] = $(this).text().trim();
data['id'] = $(this).parent('tr').attr('data-row-id');
data['index'] = $(this).attr('col-index');
if($(this).attr('oldVal') === data['val'])
{
return false;
}
$.ajax({
type: "POST",
url: "server.php",
cache:false,
data: data,
dataType: "json",
success: function(response)
{
if(response.status) {
$("#msg").removeClass('alert-danger');
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").removeClass('alert-success');
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
</script>

Prevent page from reloading after onchange a select menu

I apologize if this is a very simple question, however I am not able to find any answers or don't know what I am doing wrong here.Also I am new to ajax and jquery. Thanks for helping in advance!
I have a select menu which I want to submit to the page on change I have the following:
<from action="" method="post">
<select name="option">
<option value="a">a </option>
<option value"b">b </option>
<option value"c">c</option>
</select></form>
and
<script type="text/javascript" >
$('#option').change, (function(e)
{
e.preventDefault();
$.ajax({
type: 'post',
url: "",
data: $("form.option").serialize(),
success: function() {
}
});
return false;
});
</script>
and to check if it has submitted
<?php
if (isset($_POST['option'])) {
echo '<br />The ' . $_POST['option'] . ' submit button was pressed<br />';
}
?>
The form is submitted fine, however the page is still reloading on change, is there a way to stop the reloading of the page?
Any help would be appreciated!
try this code
<?php
if (isset($_POST['option'])) {
echo '<br />The ' . $_POST['option'] . ' submit button was pressed<br />';
exit;
}
?>
<form action="" method="post">
<select name="option" id="option">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</form>
<div id="msg">
</div>
<script type="text/javascript" src="../library/jquery-3.2.1.min.js"></script>
<script type="text/javascript" >
$('#option').change(function(e)
{
e.preventDefault();
var data="";
data=$("#option").val();
$.ajax({
type: 'post',
url: "",
data: {option:data},
success: function(result) {
$('#msg').html(result);
}
});
return false;
});
</script>
your output will be in div tag which option is submit the form
you can also display in alert
alert(result);
or using console in developer tool
console.log(result);
Try this
<select id="option" name="option">
<option value="a">a </option>
<option value"b">b </option>
<option value"c">c</option>
</select>
And your jquery should be
<script type="text/javascript" >
$('#option').change(function()
{
var option_val = $(this).val();
$.ajax({
type: 'post',
url: "",
data: "option="+option_val,
success: function(res)
{
alert(res)
}
});
});
</script>
Simple Example :
<?php
if (isset($_POST['option'])) {
echo '<br />The ' . $_POST['option'] . ' submit button was pressed<br />';
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>temporary test</title>
</head>
<body>
<select id="option">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$('#option').change(function(){
var option_val = $(this).val();
$.ajax({
type: 'post',
url: "",
data: "option="+option_val,
success: function(res)
{
alert(res)
}
});
});
</script>
</html>

Ajax Post request not working?

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

Filtering dropdown form with jquery.ajax

I have two dropdown getting value from database:
Table_Buildings
|id|---|building_name|
Table_Floors
|id|---|Floor_name|---|building(Foreign key to table_Buildings)|
and in my form
Dropdown: building)
$db->setQuery("SELECT buildings.building_name, floors.id
FROM buildings
INNER JOIN floors
ON buildings.id=floors.id"
Dropdown: floor)
$db->setQuery("SELECT floor_name, id FROM floors");
For filtering my dropdown I want to use this script:
<script type="text/javascript">
var xhr;
jQuery(function($) {
$('#filter_building').change(function(){
var filterBuilding = $('#filter_building').val();
if (xhr && xhr.abort) {
xhr.abort();xhr=false;
}
xhr = jQuery.ajax( {
url: 'index.php',
data: 'option=com_mycomponent',
success: function(data){
jQuery('#filter_building').replaceWith(data);
}
});
});
});
</script>
But somewhere is wrong and its not working.
$('#filter_building').change(function(){
var buildingId = $(this).val();
$.ajax({
url: "index.php",
type: "post",
data: {buildingId: buildingId},
success: function(data) {
$('select#floor-id').html(data);
// data = '<option>val1</option><option>val2</option>'
}
});
}):
I have sample jquery and function in index.php
Jquery and ajax
$('#filter_building').change(function(){
var buildingId = $('#filter_building').val();
$.ajax({
url: "index.php",
type: "post",
data: {buildingId: buildingId},
success: function(data) {
if(data != "false")
{
$('#Floor').html(data);
}
else{
alert("No value");}
}
});
});
And In index.php page
$buildingId = JRequest::getVar('buildingId');
$db->setQuery("SELECT floor_name, id FROM floors WHERE filter_building='".$_GET['filter_building']."'");
$db->query();
$num_rows = $db->getNumRows();
if($num_rows>0){
while($nt = $db->loadAssoc()){
echo "<option value=$nt['id']>$nt['floor_name']</option>";
}
}
else
{
echo "false";
}
<strong>
<div class="float-right">
<span>From: </span><input type="date" name="From1" id="From1" />
<span>To: </span><input type="date" name="To1" id="To1" />
<input type="submit" value="Get Details" onclick="GetDetailsFromToTransactions()" />
</div>
</div>
<div class="smallsize1 float-right" id="filterdropdown">
<select id="selectBox" onchange="FilterDate(value);">
<option value="0" Idselected>Select Filter</option>
<option value="1">Today</option>
<option value="-1">Last 1 Month</option>
<option value="-3">Last 3 Months</option>
<option value="-6">Last 6 Months</option>
<option value="-9">Last 9 Months</option>
<option value="-12">Last 1 Year</option>
<option value="-24">Last 2 Years</option>
</select>
</div>
</strong>

Select Onchange function in two dropdownlist

What I'm trying to do is create a chained select boxes and display the information when selects. How I can connect my first dropdown to my second dropdown? When I try to add this <select name="customers" id="customers" onchange="showUser(this.value)"> it also not working.
This like the function is http://www.w3schools.com/ajax/ajax_database.asp
What I need to do is like this http://www.melco-crown.com/eng/careerpop_js.php
What I have right now is this
<script>
function showUser(str,ids) {
var $txtHint = $('#txtHint');
if (str=="" || ids=="") {
$txtHint.html('');
return;
}
$txtHint.load('list.php?q='+str+'&id='+ids)
}
</script>
I don't have problem in list.php, what I can't do is the ajax function. Any help will appreciate.
Here's my full script
Script Loads the Information from database display in HTML table.
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str=="") {
$txtHint.html('');
return;
}
$txtHint.load('list.php?q='+str)
}
</script>
HTML FORM and SELECT BOXES
<form action="">
<select name="customers" id="customers" onchange="showUser(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
<div id="txtHint">Customer info will be listed here...</div>
Ajax Script for Chained Select box
<script type="text/javascript">
$(document).ready(function()
{
$("#customers").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>

Categories