Ajax function onload - javascript

I use this code:
var selected = {
country_id: <?php echo (int)$country_id;?>,
state_id: <?php echo (int)$state_id;?>,
city_id: <?php echo (int)$city_id;?>
},
countryMap = '<?php echo $countryMap;?>',
stateMap = '<?php echo $stateMap;?>',
cityMap = '<?php echo $cityMap;?>';
$("select.event-shipping-country").off().on("change", function() {
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
});
$("select.event-shipping-state").off().on("change", function() {
var $self = $(this);
cityMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'city', 'action' => 'get-cities' ], 'shipping_c_a') ?>',
data: { state: $self.val(), country: $("select.event-shipping-country").val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-city").find("option:gt(0)").remove();
selected.state_id = $self.val();
if(!result.length)
{
return;
}
var html = '';
for(var idx in result)
html += '<option ' + (selected.city_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-city").append(html);
stateMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
},
type: 'POST'
});
stateMap = $self.val() ? $self.text() : '';
});
$("select.event-shipping-city").off().on("change", function() {
selected.city_id = $(this).val();
cityMap = $(this).val() ? $(this).find('option[value="' + $(this).val() + '"]').text() : '';
});
This function select states based on selected country. Problem is that I have only one country with ID 117. But even if I have only one default option selected I must select it again to and only than will show states, but I need that states loads on page loading by selecting country id 117.
Thank you.

$("select.event-shipping-country").off().on("change", function() {
Above line will be called only on change of country.
Call the same function on document.ready() or document.onload also for first time loading and on change will remain same for change on country.
The way to do this is keep the whole code inside separate function and call that function on document.ready() or document.onload and on change of country also
function onCountryChange() {
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
}
$("select.event-shipping-country").off().on("change", onCountryChange );
document.ready(function() {
onCountryChange();
});

Try Like This, Just pass ur code inside a function and call those function at document.ready()
var selected = {
country_id: <?php echo (int)$country_id;?>,
state_id: <?php echo (int)$state_id;?>,
city_id: <?php echo (int)$city_id;?>
},
countryMap = '<?php echo $countryMap;?>',
stateMap = '<?php echo $stateMap;?>',
cityMap = '<?php echo $cityMap;?>';
function onCountryChange(){
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
}
$("select.event-shipping-country").off().on("change", function() {
onCountryChange();
});
function onStateChange(){
var $self = $(this);
cityMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'city', 'action' => 'get-cities' ], 'shipping_c_a') ?>',
data: { state: $self.val(), country: $("select.event-shipping-country").val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-city").find("option:gt(0)").remove();
selected.state_id = $self.val();
if(!result.length)
{
return;
}
var html = '';
for(var idx in result)
html += '<option ' + (selected.city_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-city").append(html);
stateMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
},
type: 'POST'
});
stateMap = $self.val() ? $self.text() : '';
}
$("select.event-shipping-state").off().on("change", function() {
onStateChange();
});
function onCityChange(){
selected.city_id = $(this).val();
cityMap = $(this).val() ? $(this).find('option[value="' + $(this).val() + '"]').text() : '';
}
$("select.event-shipping-city").off().on("change", function() {
onCityChange();
});
$(document).ready(function () {
onCountryChange();
onStateChange();
onCityChange();
});

Related

dynamic select option and dynamic data from php

I tried develop add several selectbox dynamically and get data from selectbox my codes:
this codes add new selectbox and work
var y = 1;
var z = 1;
$('#add_kind').on('click', function () {
var html = '';
html += '<div class="prInput-row">';
html += '<select name="kind_id" class="halfselect kinds">';
html += '<option value="0">Kinds</option>';
html += '<?php foreach($kinds as $kind): ?>';
html += '<option value="<?php echo $kind->id;?>"><?php echo $kind->name;?></option>';
html += '<?php endforeach; ?>';
html += '</select>';
html += '<select name="kind_desc_id" class="halfselect kind_descriptions">';
html += '<option value="0">Kind Descriptions/option>';
html += '</select>';
html += '<input type="text" name="stock_piece" class="halfselect" placeholder="Stock Piece"/>';
html += '</div>';
$('#kind_area').append(html);
$('.kinds').each(function () {
$(this).attr('class', 'halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class', 'halfselect kind_descriptions_'+z);
z++;
});
});
$('.kinds').each(function () {
$(this).attr('class','halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class','halfselect kind_descriptions_'+z);
z++;
});
this codes get data from db and not work,
var i = 1;
$(".kinds_"+i).on('change', function() {
var kindID = $(this).val();
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
i++;
});
how can change those codes and how can get dynamically datas
this picture my example
#anon, I solved thank you so much but 2 times write codes but how can write one time ?
$("#add_kind").click(function(){
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
});
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
you can get all element that have class started with "kinds_" with selector $("[class^=kinds_]") then do a loop to get your class index. So maybe something like this will work:
$.each($("[class^='kinds_']"), function() {
var selector = "."+$(this).attr("class");
$(document).on('change', selector, function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
})

Change Ajax Post parameters & returned HTML based on alternating dependant dropdowns

I have 3 dropdowns containing values that are populated on page load
<select class='form-control' id='make' placeholder='Make:'>
<select class='form-control' id='model' placeholder='Model:'>
<select class='form-control' id='version' placeholder='Version:'>
I have a function that updates the values in the 'other' dropdowns that aren't clicked, based on the value of the dropdown that is clicked - but I have this function repeated 3 times, for each dropdown
$('#model').change(function(){
let selectedModel = $(this).val();
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: {model: selectedModel},
success:function(data)
{ $('#make').html('');
$('#version').html('');
let makeJSON = JSON.parse(data)[0];
let versionJSON = JSON.parse(data)[2];
for (let i = 0; i < makeJSON.length; i++) {
if (makeJSON[i].mMake!= '' && makeJSON[i].mMake!= null) {
$('#make').html($('#make').html() + '<option value="' + makeJSON[i].mMake + '">' + makeJSON[i].mMake + '</option>');
}
}
for (let i = 0; i < versionJSON.length; i++) {
if (versionJSON[i].mVersion != '' && versionJSON[i].mVersion != null) {
$('#version').html($('#version').html() + '<option value="' + versionJSON[i].mVersion + '">' + versionJSON[i].mVersion + '</option>');
}
}
}
});
});
And the PHP looks something like this:
$model = $_REQUEST['model'];
$sqlupdateModel = "SELECT DISTINCT mMake, mVersion FROM Cars WHERE mModel = '$model';
$stmtModel = sqlsrv_query( $conn, $sqlupdateModel);
if( $stmtModel === false)
{
die( print_r( sqlsrv_errors(), true));
}
$updateModel = [];
while( $row = sqlsrv_fetch_array( $stmtModel, SQLSRV_FETCH_ASSOC)){
$updateModel[] = $row;
}
echo json_encode(array($updateMake, $updateModel, $updateVersion));
...and this all works fine,
Basically, I'm looking for a simpler solution for reusing the function (both JS & PHP) instead of rewriting it 3 times!
In terms of what I have attempted,
$('#make, #model, #version').change(function(){
let columnValue = $(this).val();
.......
data: {model: columnValue},
success:function(data)
{$(this).html(''); //this doesn't work obviously!
After this I'm snookered
This one should work for JS side, you will have to check mapping function for response
$('#make, #model, #version').change(function(ev){
let selected = $(this).val();
let id = ev.target.id;
let data = {};
data[id] = selected;
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: data,
success:function(data)
{
let options = ['make', 'model', 'version']
const response = {
make: JSON.parse(data[0].map(make => make.mMake)),
model: JSON.parse(data[1].map(make => make.mModel)),
version: JSON.parse(data[2].map(make => make.mVersion))
}
options.filter(option => option !== id).forEach(option => setDropdown(option, response[option]));
}
});
});
function setDropdown(id, data) {
const id = `#${id}`
$(id).html('');
for (let i = 0; i < data.length; i++) {
if (data[i] != '' && data[i] != null) {
$(id).html($(id).html() + '<option value="' + data[i] + '">' + data[i] + '</option>');
}
}
}

How to addClass if autocomplete input is empty?

I would like to know how to add a class if autocomplete input is empty? There's a function which autocompletes the address when putting the post code. If for example address_1 is empty, it adds the class form-control, else it adds the class sem-bordas.
I tried:
$('#input-address-1').on('change', function() {
if ($(this).val() == '') {
$(this).next().removeClass("form-control");
} else {
$(this).next().addClass("sem-bordas");
}
});
But without success.
Thats all the function
$(function(){
$('input[name="postcode"]').blur(function(){
var cep = $.trim($('input[name="postcode"]').val().replace('-', ''));
//$.getScript ("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+cep, function(){
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados){
if(!("erro" in dados)){
$('input[name="address_1"]').val(dados.logradouro);
$('input[name="address_1"]').parent().parent().fadeIn('slow');
$('input[name="address_2"]').val(dados.bairro);
$('input[name="address_2"]').parent().parent().fadeIn('slow');
$('input[name="city"]').val(unescape(dados.localidade));
$('input[name="city"]').parent().parent().fadeIn('slow');
$('select[name="zone_id"]').parent().parent().fadeIn('slow');
$('select[name="country_id"]').find('option[value="30"]').attr('selected', true);
$.post('index.php?route=account/register/estado_autocompletar&estado=' + unescape(dados.uf), function(zone_id){
$.ajax({
url: 'index.php?route=account/register/country&country_id=30',
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>');
},
complete: function() {
$('.fa-spin').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
var html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == zone_id) {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
}
});
});
}
});
});
});
$(document).on('input','#input-address-1', function() {
if ($(this).val() == '') {
$(this).next().addClass("sem-bordas");
} else {
$(this).next().removeClass("sem-bordas");
}
});
Let me explain, thats all my function to verify if the address exist or not
$(function(){
$('input[name="postcode"]').blur(function(){
var cep = $.trim($('input[name="postcode"]').val().replace('-', ''));
//$.getScript ("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+cep, function(){
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados){
if(!("erro" in dados)){
$('input[name="address_1"]').val(dados.logradouro);
$('input[name="address_1"]').parent().parent().fadeIn('slow');
$('input[name="address_2"]').val(dados.bairro);
$('input[name="address_2"]').parent().parent().fadeIn('slow');
$('input[name="city"]').val(unescape(dados.localidade));
$('input[name="city"]').parent().parent().fadeIn('slow');
$('select[name="zone_id"]').parent().parent().fadeIn('slow');
$('select[name="country_id"]').find('option[value="30"]').attr('selected', true);
$.post('index.php?route=account/register/estado_autocompletar&estado=' + unescape(dados.uf), function(zone_id){
$.ajax({
url: 'index.php?route=account/register/country&country_id=30',
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>');
},
complete: function() {
$('.fa-spin').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
var html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == zone_id) {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
}
});
});
}
});
});
});
Soon after putting the postcode and an address was not found, I would like to add a class to the fields that were not filled. The goal is to highlight fields that have not been filled
I found the solution
After
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
Put this code
if($.trim($('#input-address-1').val()) == ''){
$('#input-address-1').addClass('form-control');
}else {
$('#input-address-1').removeClass('form-control');
$('#input-address-1').addClass('sem-bordas');
}
Thanks everyone for helping. I think thats the solution

str_replace inside js from Ajax call data

i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');

Codeigniter Smiley Not Showing Up In Preview Area

I have created a area where user can type in some text and also add smiley into the text area. smiley helper
How ever when I click on my preview button it does not show the generated smiley.
Question how to make sure on the preview are if has any smiles on
question will show up in preview properly. I use preg_replace_callback on my preview function on controller. and also .replace on script Update I found this on user guide but not sure where to add it on code
Generate the smiles here.
<?php
class Question extends CI_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->helper('smiley');
}
public function create() {
$this->load->library('table');
$image_array = get_clickable_smileys(base_url('assets/img/smiley'), 'question');
$col_array = $this->table->make_columns($image_array, 8);
$data['smileys'] = $this->table->generate($col_array);
$this->form_validation->set_rules('title', 'title', 'trim|required');
$this->form_validation->set_rules('question', 'question', 'trim|required|callback_question');
if ($this->form_validation->run() == true) {
}
$data['page'] = 'question/create';
$this->load->view($this->config->item('config_template') . '/template/template_view', $data);
}
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$match = array(
'<' => '<',
'>' => '>',
);
$new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
}, $string);
$data['question'] = $new_data;
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
}
Script On View
<script type="text/javascript">
$('#preview-question').on('click', function (e) {
$.ajax({
url: "<?php echo base_url('question/preview');?>",
type: 'POST',
data: {
question: $('#question').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
dataType: 'json',
success: function(response){
if (response.success) {
$('#preview').html(response.question);
if ($("#preview").find("pre").length > 0){
var html = $('#preview pre').html().replace(/</g, "<").replace(/>/g, ">");
$('#preview pre').html(html);
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
}
} else {
}
}
});
e.preventDefault();
});
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$(document).ready(function(){
$('#bold').click(function() {
wrapText('question', "<strong>", "</strong>");
});
$('#italic').click(function() {
wrapText("question", "<i>", "</i>");
});
$('#underline').click(function() {
wrapText("question", "<u>", "</u>");
});
$('#pre').click(function() {
wrapText("question", "<pre>", "</pre>");
});
});
</script>
Got it working
I had to use $data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$match = array(
'<' => '<',
'>' => '>',
);
$new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
}, $string);
$data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}

Categories

Resources