How to add if statements to Ajax - ajax

I do mostly PHP programming, but am stuck on an Ajax problem since I do not know Javascript or Ajax very well at all. I have a combo select menu right now and I would like to hide the third select menu (direction) if the first choice is = 'train'. I read that some browsers do not support the hide function, so the next best option is to keep the third select menu disabled when the second option is chosen assuming the first is train. If it is bus, then the third select menu should still show. Here is my javascript right now and as I'm sure you can imagine it doesn't work.
$(document).ready(function(){
if ($("select#agency").attr('value') == 'cta-train') {
$("select#direction").attr("disabled","disabled");
}
$("select#route").attr("disabled","disabled");
$("select#agency").change(function(){
$("select#route").attr("disabled","disabled");
$("select#route").html("<option>wait...</option>");
var id = $("select#agency option:selected").attr('value');
$.post("select_route.php", {id:id}, function(data){
$("select#route").removeAttr("disabled");
$("select#route").html(data);
});
});
});
$(document).ready(function(){
if ($("select#agency").attr('value') == 'cta-train') {
$("select#direction").attr("disabled","disabled");
}
else {
$("select#direction").attr("disabled","disabled");
$("select#route").change(function(){
$("select#direction").attr("disabled","disabled");
$("select#direction").html("<option>wait...</option>");
var id = $("select#route option:selected").attr('value');
$.post("select_direction.php", {id:id}, function(data){
$("select#direction").removeAttr("disabled");
$("select#direction").html(data);
});
});
}
});
Any help would be greatly appreciated!

Seems like you dont want ajax, you want to use javascript to hide a select if another select has a certain element in it. Then use your ajax to file the select as needed. Here is an example of that http://jsfiddle.net/2FQwQ/
<select id='direction'>
<option value='train'>train</option>
<option value='car'>car</option>
<option value='pogo stick'>pogo stick</option>
<select>
<select id='agency'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<select>
<select id='route'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<select>
Script
//SEts your html up to hide the secelt if train
function amITrain() {
if ($('#direction').val() === "train"){
$('#route').hide();
$('#route').attr('disabled');
}else{
$('#route').show();
$('#route').removeAttr('disabled');
}
}
$('#direction').change(amITrain);
//When you get the ajax back, you would fill the select like this, then call the function
$('#direction').html("<option value='train'>train</option><option value='car'>car</option> <option value='pogo stick'>pogo stick</option>");
amITrain();

Related

Dynamic dropdown in laravel 5.8

here's what i want to happened
- First dropdown (Parent)
- Second dropdown (Child)
- The options on the second dropdown will depend on the selected value of the first dropdown.
I am using laravel 5.8.
In Your view
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control{{ $errors->has('state') ? ' is-invalid' : '' }}" onchange="dropdown(this.value);" name="state" id="state">
<option>--select state--</option>
<option value="Kerala">Kerala</option>
<option value="Karnataka">Karnataka</option>
<option value="Tamil Nadu">Tamil Nadu</option>
</select>
<select class="form-control{{ $errors->has('district') ? ' is-invalid' : '' }}" name="district" id="district">
<option>Please choose state from above dropdown</option>
</select>
<script >
function dropdown(msg){
var state=msg;
$.ajax({
url: 'getdistrict/'+state,
type: 'get',
dataType: 'json',
success: function(response){
$("#district").empty();
var len = 0;
if(response['data'] != null){
len = response['data'].length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response['data'][i].id;
var name = response['data'][i].name;
var option = "<option value='"+name+"'>"+name+"</option>";
$("#district").append(option);
}
}
}
});
}
In your controller
public function district($id)
{
$userData['data'] = DB::table('alldistricts')
->where('state', $id)
->orderBy('name', 'asc')
->get();
echo json_encode($userData);
exit;
}
In your web.php
Route::get('/getdistrict/{id}','RegistrationController#district')->name('getdistrict');
To achieve this you must know front end script like Vue js or at least native javascript. I'll show how to achieve this using vue js and axios package and native js and ajax.
Vue js and axios:
Documentation:
1)https://vuejs.org (for vue js)
2)https://www.npmjs.com/package/axios (for axios package)
include this line in you header.
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
Note: I used Vue js cdn for development mode. Make sure to change to production mode on live. Check the documentation for further.
Then add this in the form:
<form method='post' action="http://example.com/location" id="developers">
<select name="developer_type" v-on:change="getLanguages" v-model="developerType">
<option disabled> Select Developer Type </option>
<option value="front"> Front-End Developer </option>
<option value="back"> Back-End Developer </option>
<option value="full"> Full Stack Developer </option>
</select>
<select name="Coding_language">
<option disabled v-if="developerType!=null"> Select Developer Type First </option>
<option disabled v-else="developerType!=null"> Select Coding Language </option>
<option v-for="lang in codingLaguanges" value="lang"> #{{lang}} </option>
</select>
</form>
Note: use #{{}} if only you use Laravel blade as your template engine Otherwise use only {{}}
Then add this on footer script
let developerForm = new Vue({
el:'#developers',
data:{
developerType:null,
codingLanguages:null
},
methods:{
getLanguages: function () {
axios
.post('/developers/getLanguages',{
type: developerForm.developerType
})
.then(response => (
developerForm.codingLanguages = response.data.languages
));
}
}
});
Note:I have used v-on:change and v-model in select instead of using watcher ands-model because this concept will be easier if you are new to vue js, Otherwise use Watcher itself. Check Vue js Documentation. However Both will work in this case.
In .post give you correct url to get result.
then define your route
Route::post('/developers/getLanguages', ['as'=>'dev.getLang','uses'=>'web\DevController#getLanguages']);
Note this is laravel part. you ca see Documentation in https://laravel.com
then in your DevController add this method
public function getLanguages(Request $request){
//do something to fetch result from db. Let us consider user has selected backend as developer type and there is array named Languages and it contains elements named php, python and java. i.e. $languages = ['php','python','java'].
return response()->Json(['languages'=>$languages],200);
}
Note: This will be your method for Controller to know detailed about controller check laravel documentation mentioned in previous note. Here you can retrieve the variable value from db also. but I used only sample values. In return I used array in json because you can n number of variables in that array(For example you can use statusCode to identify your error in future and much more.). Then make sure the name of the key in json array and name of the object in axios while retrieving is same. And I used status code as 200 because the browser take response of the request is successful. if you use 400 browser take response of the request is error.
This is the easiest method you can achieve.
You can also use jquery ajax and jquery or native javascript and javascript ajax to achieve this. But it has some complexity and limitation.
If you need code for native js or jQuery comment it and I will post it

Laravel VUE JS dynamic drop down menu

Why doesn't this work?
Here is my select tag:
<select class="form-control" v-model="provider">
<option value="0">Select Provider</option>
<option v-for="provider in providers" :value="provider.provider_id">{{provider.name}}</option>
</select>
Code which loads the data:
loadProviders(){
axios.get('api/provider').then(({data}) => (this.providers = data.data));
data is then stored in:
data(){
return{
providers : {}
}
}
I've checked the developer networks tab of Chrome and it does return the data from the database.
However the value(provider.name) doesnt show up in the dropdown options menu.
This issue has already been solved: the model for Provider had an error all along.
The issue is, that you are destructuring the API response, but don't take into account that when assigning to data.
axios.get('api/provider').then((data) => (this.providers = data.data));
and
axios.get('api/provider').then(({data}) => (this.providers = data));
both work.
Update your select box
<select v-model="provider">
<option v-for="(value,key) in provider"
:value="value.provider_id">
{{value.name}}
</option>
</select>
Make sure you received proper data from your API.
assign data to provider variable. it will appeare in select box

Getting the target element name in data- attribute of the parent element through JQuery

I have two elements a source and target (sort of linked select). I wish to get the target element's name in the source element's data- attribute. Is it possible? The following code does not work.
<label>States</label>
<select class='sparent' data-select-target='child'>
<option value=''>Select State</option>
<option value='AZ'>AZ</option>
<option value='PA'>PA</option>
<option value='TX'>TX</option>
</select>
</label>
<div name='child' class='schild'>value</div>
JQuery Code :
$(".sparent").change(function(){
var id = $(this).val();
var target = $(this).data("select-target");
$.get("includes/chainedselect.php", {id:id}, function(data){
$(target).html(data);
});
});
However, if I replace $(target).html(data); with $("child").html(data); it works.
Can anyone help me figure this out? Thanks for your time.
Rename your data attribute data-select-target='child' to this:
data-select-target='schild'
And $(target).html(data); to this:
$('.' + target).html(data);
and try again.
try this,
$('div[name="'+target+'"]').html(data);
you are providing 'child' in the selector, but you missed to provide whether it is an 'id', 'class' or 'tag'.

ajax code for jsp

How to write Ajax code to retrieve information on to a particular part of webpage when we select option from a dropdown box?
I want information of a particular item that I had selected from a dropdown menu on particular part of my webpage.
Let's say your markup looks something like:
<select id="dropdown">
<option value="1">Some option</option>
<option value="2">Other option</option>
<option value="3">Helpfull option</option>
<option value="4">Don't pick this option</option>
</select>
<div id="details"></div>
In order to make AJAX calls I would use some sort of library. Using for instance jQuery will be much easier than writing code that handles ajax calls across different browsers. The code could look like this:
$('#dropdown').on('change', function(e) {
var currentValue = $('#dropdown').val();
$.get('<someurl>', function(data) {
$('#details').html(data);
});
};
Replace '<someurl>' with the url to the resource you want. Doing this without using jQuery or similar library is a bit more involved. For some guidance you can look at this answer: https://stackoverflow.com/a/2557268/355499

Calling colorbox from a dropdown list

I'm trying to implement calling colorbox items from a dropdown menu. Using this example, http://www.jacklmoore.com/colorbox/example4/, how could I simply call these links from a drop down menu? It seems to work fine in every browser except IE without any additional scripting. I'm sure it's going to be simple fix for anyone with true coding skills. Can anyone help me out?
I found something similar after a quick google search
I can't say whether or not this works, but why don't you give it a shot working this code into your jsfiddle, and I'll see if I can help you debug any issues that arise.
from: https://groups.google.com/forum/?fromgroups=#!topic/colorbox/OM85IPMoyP4
<select name="howheard" id="howheard" class="validate[required]">
<option value="http://example1.com">Example 1</option>
<option value="http://example2.com">Example 2</option>
<option value="http://example3.com">Example 3</option>
</select>
EDIT: updadate colorbox() init:
<script>
$(document).ready(function(){
$("#howheard").change(function () {
var thisHref = $(this).val();
$.colorbox({iframe:true, width:"80%", height:"80%", href: thisHref});
});
});
</script>

Resources