AJAX form executed by onblur OR change event - ajax

I have a form where the user will enter a number into a text field. Then, select another number from a dropdown menu. I want the AJAX to execute each time they go from field to field. This is so that it does a calculation in real-time.
I would imagine the text field would be using "onblur" and the dropdown using "change" or "onchange"... but how do I write the script to do EITHER depending on which field they are currently on? Can you set it to do both?
EDIT: New attempt with new variable labels.
<script type="text/javascript">
function postData(){
var widthX = $('#width_str').val();
var heightX = $('#height_str').val();
var prodidX = $('#prodid').val();
var roomX = $('#room_str').val();
$.post('db_query.php',{widthX:widthX, heightX:heightX, prodidX:prodidX, roomX:roomX},
function(data){
$("#search_results").html(data);
});
}
$(function() {
$("#lets_search").bind('submit',function() {postData()});
$("#room_str").bind('change', function() {postData()});
$("#width_str").bind('change', function() {postData()});
$("#height_str").bind('change',function() {postData()});
});
</script>
Part of the form here....
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
<input type="hidden" value="1" value="<?php echo stripslashes($_GET['prodid']); ?>" name="prodid" id="prodid">
room name:
<select name="room_str" id="room_str">
<option value="Dining">Dining</option>
<option value="Bathroom">Bathroom</option>
<option value="Kitchen">Kitchen</option>
</select>
height:
<select name="height_str" id="height_str">
<option value="30">30"</option>
<option value="31">31"</option>
<option value="32">32"</option>
<option value="33">33"</option>
<option value="34">34"</option>
<option value="35">35"</option>
<option value="36">36"</option>
<option value="37">37"</option>
</select>
<br>
width:
<select name="width_str" id="width_str">
<option value="30">30"</option>
<option value="31">31"</option>
<option value="32">32"</option>
<option value="33">33"</option>
<option value="34">34"</option>
<option value="35">35"</option>
<option value="36">36"</option>
<option value="37">37"</option>
</select>
<input type="submit" value="send" name="send" id="send">
</form>
The php page that processes the data...
<?php
include('db_pbconnection.php');
$tax = .06;
$tax2 = 1.06;
$grandtotal = 50;
$query = mysql_query(" SELECT * FROM price_dimensions WHERE prodid = '".$_POST['prodidX']."' AND height >= '".$_POST['heightX']."' AND width >= '".$_POST['widthX']."' ORDER BY height ASC, width ASC LIMIT 1 ");
echo '<div>';
while ($data = mysql_fetch_array($query)) {
echo '
<div style="background-color:pink;">
<div style="clear:both; font-size:18px;">height: '.$data["height"].'</div><br>
<div style="clear:both; font-size:18px;">width: '.$data["width"].'</div>
<div style="clear:both; font-size:18px;">unit price: '.$data["price"].'</div>
<div style="clear:both; font-size:18px;">tax: '.(($data["price"])*($tax)).'</div>
<div style="clear:both; font-size:18px;">grand total:'.(($data["price"])*($tax2)).'</div>
</div>';
}
echo '</div>';
?>

If I understand you correctly, you can call the AJAX from any area by moving the code into a separate function and binding any event to that function.
function postData(){
var value = $('#str').val();
var valueH = $('#strH').val();
var prodid = $('#prodid').val();
$.post('db_query.php',{valueH:valueH, value:value, prodid:prodid},
function(data){
$("#search_results").html(data);
});
return false;
}
$(function() {
$("#lets_search").bind('submit',function() {postData()});
$("#strH").bind('change', function() {postData()});
$("#str").bind('blur',function() {postData()});
});

Related

how to show selected dropdown in codeigniter using ajax

Problem is in my edit page the one dropdown value is selected but the other dropdown who called with first dropdown value is not show hear the code is
$(document).ready(function() {
// alert('onload');
// alert($('#company_name').val())
$('#company_name').change(function() {
var id = $('#company_name').val();
if (id != '') {
$.ajax({
url: BaseURL + 'admin/campaign/fetch_template',
type: 'POST',
data: {
id: id,
},
success: function(data) {
$('#template').html(data);
}
});
} else {
$('#template').html('<option value="selected">Select Template</option>');
}
});
});
I want to add this a selected value of dropdown.....
<select onchange='getTemplate(this.value);' class="form-control" id="template" name="template" data-placeholder="Select a option">
<option value="">Select Template</option>
</select>
this is the dropdown which i want to get selected value &
<select class="form-control" name="company" class="form-control " data-placeholder="Select a option" id="company_name">
<option value="1">Select Company</option>
<?php foreach ($company as $con) { ?>
<option value="<?php echo $con->company_id ?>" <?php echo $edit['id'] == $con->company_id ? 'selected' : '' ?>><?= $con->name; ?>
</option>
<?php } ?>
</select>
and this is where i call a company name to select the templeate each company

Getting value from (select2) to another filed input laravel

I have select2 field input. After using select2 its will showing new column and data from this input selected.
I have referenced like this link. So after I using select2, this value will show in a new column. But I don't know how to catch this data. I am using Laravel and this is my controller and view:
Controller
$collection = Alat::get(['nama_alat','no_inventaris','status_alat','id']);
foreach ($collection as $item) {
$inven[$item->id] = $item->no_inventaris.'-'.$item->nama_alat;
}
This is will shown in columns no_inventaris and nama_alat in the select2. But in the $collection, I have status_alat, this data is what I need to display in another column.
This is my view:
// This is form Select2
<div class="form-group">
<label>Pilih Inventaris</label>
<select class="form-control select2bs4" name="alat_id" id="alat_id" style="width: 100%;" aria-hidden="true" onchange="Show()">
<option value=""></option>
#foreach($inven as $id => $item )
<option value="{{ $id }}">{{ $item }} </option>
#endforeach
</select>
</div>
// This is form what i need to show another value
<div class="form-group" id="divid" style="display:none">
<label class="control-label" for="title">Kondisi Alat Sekarang:</label>
<input type="text" name="" class="form-control" id="value" data-error="Please enter title." readonly />
<div class="help-block with-errors"></div>
</div>
Here's my Javascript:
<script>
function Show()
{
var fieldValue = $('#alat_id').val();
if(fieldValue == "")
{
document.getElementById("divid").style.display = 'none';
}
else{
document.getElementById("divid").style.display = 'inline'
}
}
</script>
This data I need to catch in the controller $collection as status_alat. How can I catch this data after input the select2 and showing in the new column? This column is shown, but I don't know how to catch this data. Sorry for my bad English
The best solution should be using ajax, it is quite complicated to access a PHP collection variable inside a javascript. If it were me, I would create a function that fetch the selected select2 data by its id. This is my example code :
<script>
function select2Changed()
{
var alat_id = $('#alat_id').val();
if(fieldValue == ""){
document.getElementById("divid").style.display = 'none';
} else{
document.getElementById("divid").style.display = 'inline';
$.ajax({url: "[url]/get-alat-status/"+alat_id, success: function(result){
document.getElementById("value").value = result;
}});
}
}
</script>

select box using AJAX

I have a select form which has three fields, Location, Estate and Size that populate dynamically using ajax.
When a user selects a town, the estates drop down options appear with respect to the town selected.
When the user clicks on search button, results based on the selection should appear.
According to my code, when I dd the variables $Estate and $Size in my post method, I get the values selected by the user on the form. This is what I want.
However, when I dd $Location, I get the id number instead of the value the user selected on the form.
This is my form :
<form class="form-inline" id="search-bar" action="{{route('post_index')}}" method="post">
{{ csrf_field() }}
<select class="form-control productcategory" name="Location" id="product_cat_id">
<option value="0" disabled="true" selected="true">Town</option>
#foreach($cities as $city)
<option value="{{$city->id}}">{{$city->product_cat_name}}</option>
#endforeach
</select>
<select class="form-control productname" name="Estate">
<option value="0" disabled="true" selected="true">Estate</option>
</select>
<select class="form-control" name="Size">
<option value="0" disabled="true" selected="true">Size</option>
<option value="Bedsitter">Bedsitter</option>
<option value="One Bedroom">One Bedroom</option>
<option value="Two Bedroom">Two Bedroom</option>
<option value="Three Bedroom">Three Bedroom</option>
</select>
<button type="submit" class="btn btn-default">Search</button>
</form>
This is my AJAX code :
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change', '.productcategory', function(){
//console.log("Shit is working");
var new_id=$(this).val();
//console.log(cat_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findEstateName')!!}',
data:{'id':new_id},
success:function(data){
//console.log('success');
console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>chose estate</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].Estate+'">'+data[i].Estate+'</option>';
}
div.find('.productname').html(" ");
div.find('.productname').append(op);
},
error:function(){
}
});
});
$(document).on('change','.productname',function (){
var prod_id=$(this).val();
var a=$(this).parent();
console.log(prod_id);
var op="";
});
});
</script>
This is my post method :
public function postIndex(){
//echo "success";
$Location = Input::get('Location');
$Estate = Input::get('Estate');
$Size = Input::get('Size');
$validator= Validator::make(
array(
'Location'=>$Location,
'Estate'=>$Estate,
'Size'=>$Size
),
array(
'Location'=>'required',
'Estate'=>'required',
'Size'=>'required'
)
);
if ($validator->fails()) {
return redirect()->route('home-index')->withErrors($validator);
// echo "fail";
}else{
$houses=DB::table('houses')->where('Location', $Location)->where('Size', $Size)->where('Estate', $Estate)->get();
dd($Location);
//$towns = DB::table('houses')->pluck('Location', 'Location');
//$estates = DB::table('houses')->pluck('Estate', 'Estate');
$cities=ProductCat::all();
$data = [
'house' => $houses,
//'towns' => $towns,
//'estates' => $estates,
'cities' => $cities
];
//dd($data);
if (count($houses)) {
return View('pages.home', $data);
}else{
Session::flash('fail', 'Sorry, no results found...');
return View('pages.home',$data, ['FailMessage' => 'Sorry no results found..'])->withHouse($houses);
}
}
}
What do I need to do so that when I dd $Location, I get the Location name selected by the user?

Active record codeigniter does not update database when passed thru Ajax

The problem is that when i use submit, codeigniter process the script cleanly. But when I passed the data thru ajax. script works fine. It even outputs the array when i use print_r. Its just that it doesn't update the database. everything is fine until the activerecord script.
Here is my controller script. (I just simplified it).
What I did was there is a script that would create an empty row. Thus, it will retrieve the Article id which will be used to save the article.
Here is the save article function.
Controller:
function saveArticle(){
$this->userarticle_model->trial();
}
Model:
function trial(){
$userid = $this->session->userdata('userid');
$articleId = $this->input->post('article_id');
$articleData = array(
'sfc_articleAuthor' =>$userid ,
'sfc_articleTitle' => $this->input->post('article_title'),
'sfc_articleContent' => $this->input->post('article_content'),
'sfc_articleStatus' => 'saved',
'sfc_articleTag' =>$this->input->post('article_tag'),
'sfc_articleCategory' => $this->input->post('article_category')
);
$this->db->where('sfc_articleId', $articleId);
$this->db->update('sfc_articles', $articleData);
}
AJAX:
(Sorry, I just copied this from a tutoral.)
$(document).ready(function(){
$('.save').click(function() {
$('#article_form').hide(0);
$('#message').hide(0);
var article_title = $('#article_title').val();
var article_tag = $('#article_tag').val();
var article_id = $('#articleId').val();
var article_category = $('#article_category').val();
var article_content = $('#article_form').find('.nicEdit-main').text();
var article_status = 'saved';
var dataString = 'article_title='+ article_title + '&article_tag=' + article_tag + '&article_category=' + article_category + '&article_content=' + article_content + '&article_status=' + article_status;
$.ajax({
type : 'POST',
url : 'http://localhost/ci_usage/index.php/article/saveArticle',
dataType : 'json',
data: dataString,
success : function(data){
$('#waiting').hide(500);
if (data.error === false)
$('#article_form').show(10);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#article_form').hide(10);
$('#article_form').show(3);
}
});
return false;
});
});
View:
<?php echo form_open('article/processArticle',array('id'=>'article_form'));?>
<?php echo validation_errors(); ?>
<div id="sidebar_options">
<div class="sidebar_title">Article Settings</div>
<ul>
<li>
<label>Tags</label><br />
<input type="text" name="article_tag" size="15" value="<?php echo set_value('article_tag');?>" id="article_tag"/>
</li>
<li>
<label>Category</label><br />
<select name="article_category" id="article_category">
<option value="1">Test Category 1</option>
<option value="">Test Category 2</option>
<option value="">Test Category 3</option>
<option value="">Test Category 4</option>
</select>
</li>
<li>PDF version</li>
</ul>
</div>
<div id="option_panel">
<input type="text" name="article_title" size="30" placeholder="Title" value="<?php echo set_value('article_title');?>" id="article_title"/>
<input type="submit" value="Publish" name="publish" />
<input type="button" value="Preview" class="save"/>
<input type="button" value="Save" class="see"/>
</div>
<div id="write_panel" style="width:700px; margin-left:50px; width:800px;"></div>
<div id="write_area">
<textarea name="article_content" id="article_content" style="height:690px; width:800px;" ></textarea>
<input type="hidden" value="<?php echo $articleId;?>" name="article_id" id="articleId"/>
</div>
</div>
<?php echo form_close();?>
I really scratched my head on this.
Just got the answer. Forgot to add to put the last variable into the datastring in the ajax file.

How to use AJAX to populate state list depending on Country list?

I have the code below that will change a state dropdown list when you change the country list.
How can I make it change the state list ONLY when country ID number 234 and 224 are selected?
If another country is selected it should be change into this text input box
<input type="text" name="othstate" value="" class="textBox">
The form
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
The javascript
<script>
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Just check the countryId value before you do the AJAX request and only perform the request if the countryId is in the allowable range. In the case where the countryId doesn't match, I would hide the select (probably clear it's value, too) and show an already existing input that was previously hidden. The reverse should be done if an allowable country is chosen.
jQuery example below:
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
I think the simple thing to do is to provide a state dropdown and a text entry box with different ids. Set the display of both to none and then you just need to surround your contents of getState() with
if (countryId == 233 || countryId == 234) {
/* Ajax state population here */
dropdownId.display = 'block';
textEntryId.display = 'none';
}
else {
textEntryId.display = 'block';
dropdownId.display = 'none';
}
(where dropdownId and textEntryId are the ids of the relevant UI components) so you enable/display the display for the state dropdown or the text entry upon selection.
JQuery is all well and good, but I wouldn't introduce it just to solve this problem.
EDIT: here is a solution that works quite well for the task, adapting the lines of Tvanfosson:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
</script>
<select style="background-color: #ffffa0" name="country" id=country >
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" id=othstate value="" class="textBox" style="display: none;">
As you can see, I eliminated the <form> element which is not absolutely necessary but can be added (and then has to be used properly in case JS is deactivated at the users end. See
here.
I also eliminated the onchange event which is being replaced by the 'change()` jquery function.
**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "ajaxServer.jsp",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
<style>
select { width: 10em }
</style>
</head>
<body>
<form>
<table>
<tr>
<td> <label>Country:</label></td>
<td> <select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
</tr>
<tr><td >
<label>States:</label></td>
<td> <select id="response">
<option>Select State</option>
</select>
</td></tr>
</table>
</form>
</body>
</html>
**ajaxServer.jsp**
<option>Select State</option>
<%
String count=request.getParameter("country");
String india[]={"Mumbai", "New Delhi", "Bangalore"};
String usa[]={"New Yourk", "Los Angeles","California"};
String uk[]={"London", "Manchester", "Liverpool"};
String states[];
if(count.equals("india"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+india[i]+"</option>");
}
}
else if(count.equals("usa"))
{
for(int i=0;i<usa.length;i++)
{
out.print("<option>"+usa[i]+"</option>");
}
}
else if(count.equals("uk"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+uk[i]+"</option>");
}
}
%>
VK API just select country , get it id and select city from
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
var _getCountry = function() {
$j.ajax({
url: "http://api.vk.com/method/database.getCountries",
data: {
'v': 5.5,
'need_all': 0,
'code' : 'RU,UA,BY,KZ,KG,LV,EE'
// 'count': 10
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each country");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
country_options.push(newOption);
});
document.getElementById('countrylist').innerHTML = country_options;
}
});
}
var _getCity = function(country_id) {
$j.ajax({
url: "http://api.vk.com/method/database.getCities",
data: {
'v': 5.61,
'need_all': 0,
'country_id': country_id
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each city");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
city_options.push(newOption);
});
document.getElementById('citylist').innerHTML = city_options;
}
});
}
var city_options = [];
var country_options = [];
$j(document).ready(function () {
_getCountry();
$j('#country').on('input',function() {
var opt = $j('option[value="'+$j(this).val()+'"]');
var countryid = opt.attr('id');
_getCity(countryid);
});
});
</script>
<div class="form-group">
<label class="col-lg-4 control-label">Страна:</label>
<div class="col-lg-8">
<div class="controls">
<input name="country" list="countrylist" id="country" class="form-control" />
<datalist id="countrylist">
</datalist>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Город:</label>
<div class="col-lg-8">
<input name="city" list="citylist" id="city" class="form-control"/>
<datalist id="citylist">
</datalist>
</div>
</div>
////////////////// connection file con.php rishabh
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db( 'testajax' );
?>
/////////////////////////// index.php rishabh
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php
include('con.php');
?>
<form>
<div class="frmDronpDown">
<div class="row">
<table><tr><td><label>Country:</label><br/>
<select name="country" id="country" data-name="country" class="demoInputBox" onChange="getCountry(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct country FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['country']; ?>"><?php echo $result['country']; ?></option>
<?php
}
?>
</select> </td>
<td>
<label>Phone:</label><br/>
<select name="phone" id="phone" data-name="phone" class="demoInputBox" onChange="getPhone(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct phone FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['phone']; ?>"><?php echo $result['phone']; ?></option>
<?php
}
?>
</select>
</td></tr></table>
</div>
<div id="state-list"></div>
</div>
</form>
<script>
function getCountry(val) {
var dataname = $('#country').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
function getPhone(val) {
var dataname = $('#phone').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
</script>
// ////////////////////data file data.php rishabh
<?php
$val = $_POST["value_name"];
$colomn = $_POST["colomn_name"];
include('con.php');
$sql_aa = mysql_query("SELECT * FROM statecont where ".$colomn."='$val'"); ?>
<table>
<tr><td>State</td><td>Countery</td></tr>
<?php while($result_aa=mysql_fetch_array($sql_aa)){ ?>
<tr><td><?php echo $result_aa['state']; ?></td><td><?php echo $result_aa['country']; ?></td></tr>
<?php } ?>
</table>

Resources