Write Variable javascript in laravel - javascript

i am make ajax request on select box to return cities dependent on countries
but when i return old and test if this id of cities contain on array i can't write
the java script variable " key " that refer to city id on this line
i am attached photo of code with question
please help me
<script type="text/javascript">
$(document).ready(function() {
$('select[name="country_id"]').on('change', function() {
var countryID = $(this).val();
if(countryID) {
$.ajax({
url: '{!! url('/admin/getCities') !!}/'+countryID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="ship_to_ids[]"]').empty();
console.log('ok');
$.each(data, function(key, value) {
$('select[name="ship_to_ids[]"]').append('<option value="'+ key +'" {{ (in_array( key , old( "ship_to_ids",
isset($product) ? ($product->ship_to_ids?:[]) : []))) ? "selected" : " " }}>'+ value +'</option>');
});
}
});
}else{
$('select[name="ship_to_ids[]"]').empty();
}
});
});
</script>

Ok the tricky part is here
{{ (in_array( key , ...
in_array is looking for a variable as first parameter and you gave it a constant key so you need to pass your key variable.
Updated
you can do so in your javascript code
var option = '<option value="'+ key +'" {{ (in_array( ":key" , old( "ship_to_ids", isset($product) ? ($product->ship_to_ids?:[]) : []))) ? "selected" : " " }}>'+ value +'</option>';
option = option.replace(':key', key)
$('select[name="ship_to_ids[]"]').append(option);

Related

Making of an option selected in ajax call not working

I have tried below lines of code for making an option selected if it matches with the data's DepartmentName. It's not working. Please help !!!
function fillDepartments(selectedText)
{
$.ajax({
url: 'index.php?action=fetchAllDepartments',
type: 'POST',
dataType: 'JSON',
data:{},
success: function(data){
for(var i in data){
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'
+ data[i]['DepartmentName'] + selectedText == data[i]['DepartmentName'] ? "selected" : "" +
'</option>');
}
}
});
}
Apply a simple if-else condition:-
for(var i in data){
if(selectedText == data[i]['DepartmentName']){
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '" selected>'+ data[i]['DepartmentName']+'</option>');
}else{
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'+ data[i]['DepartmentName'] +'</option>');
}
}
seems like problem with below code where you are closing tag without including select in it
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'
//error as its out of opening bracket
+ data[i]['DepartmentName'] + selectedText == data[i]['DepartmentName'] ? "selected" : "" +'</option>');
you need to include selected in bracket5
<option value='abc' selected></option>
in your case it is
<option value='abc' > selected</option>//wrong

Include an element $id inside ajax query

When I edit my product, I want to my categories appear inside the dropdown. Currently it's just
-- Select your category --
For example, my $current_category_id = 2, the dropdown must display the good categories.
How to do that ?
tk
<div id="myAjax"><select name="move_to_category_id" id="category_id"><option value="0">-- Select your categorie --</option></div>
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
var selectedOptionVal = $('#category_id').val();
$.ajax({
url: '<?php echo $categories_ajax; ?>',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '';
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
var selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
Your code says, while clicking on the div you are doing an ajax call based on the selected value in the select box. But there will not be any value while clicking since you are updating the select box after that.
Call the ajax on on ready and populate your drop down box.

Populating JSON array to drop down reserved word column name conflict

This is the first time ill use JSON. I used the json_encode(myarrayhere) to return array value as shown below.
There is a corresponding value on change of selected value on dropdown.
I verified that I get the array data by using alert(dataArray) and it returns like this
[{"title":"First"},
{"title":"Second"},
{"title":"Third"} ]
I used the word title as column name for a table I'm using in my database.
But the problem now is how to properly populate them in a drop down. I tried to do value.title but it looks like that title is a reserved word/method in php
$.ajax({
type: 'POST',
data: {ctgy: selected},
url: 'awts.php' ,
datatype: 'json',
success: function (dataArray) {
alert(dataArray);
var items = '';
$.each(result,function(name,value) {
items += "<option value='"+value.title+"'>"+value.title)+"</option>";
});
$("#dropdownselectid").html(items);
}
});
Thanks in advance.
Firstly, if you check the console you'll see that you have a syntax error. You have an extra ) when you append value.title to the HTML string.
Secondly, your $.each() call is attempting to loop through result when your data is in a variable named dataArray.
Try this:
$.ajax({
type: 'POST',
data: { ctgy: selected },
url: 'awts.php',
datatype: 'json',
success: function(dataArray) {
var items = '';
$.each(dataArray, function(name, value) {
items += '<option value="' + value.title + '">' + value.title + '</option>';
});
$("#dropdownselectid").html(items);
}
});
Working example

how to append a html tag from an ajax call response

I have an ajax function :
$('#app-name').change(function () {//1
console.log("inside change");
var applname= this.value;
console.log(applname);
$.ajax({//2
url: 'foo',
method : 'GET',
dataType : "json",
contentType: "application/json",
data: {"AppID":"appname"},
success: function(data){
var order_data = data;
$('#foo-name').html('');
$.each(order_data, function(i, item) {//3
console.log(order_data[i]);
$('<option value='+ order_data[i] +'>'+order_data[i]).html('</options>').appendTo('#foo-name');
});//3
}
});//2
});//1
This function is doing everything else except appending value to the html.
Am i doing it wrong? Can you help solve this issues.
Place the closing </option tag in the jQuery object you create. Don't set it through the html() method. Try this:
$('<option value="' + order_data[i] + '">' + order_data[i] + '</option>').appendTo('#foo-name');
That said, you can also improve performance of your code by building the string in the loop and appending it to the select once, like this:
success: function(data) {
var options = '';
$.each(data.split(/\n/), function(i, item) {
options += '<option value=' + item.trim() + '>' + item.trim() + '</option>');
});
$('#foo-name').html(options);
}
Update You also need to split() the text you state that you're returning before looping through it.
Please use below code in your ajax success event.
success: function(data) {
var _html = '';
$.each(order_data, function(i, item) {
_html += '<option value='+ item +'>'+item+'</options>';
});
$('#foo-name').append(_html);
}

Issue filling select box via ajax call in Django

I am running into an issue creating cascading select boxes (backend Django-though I think this portion is mostly worked out). I have the following javascript code adapted from this stackoverflow response.
$(document).ready(function(){
$('select[name=experiment]').change(function(){
experiment_id = $(this).val();
request_url = '/admin/get_measurements/' + experiment_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data, function(){
$('select[name=measurement_a]').append('<option value="' + this.key + '">' + this.value +'</option>');
// $('select[name=measurement_a]').append($("<option />").val(this.key).text(this.value))
});
},
return: false
})
})
});
In my project I select an experiment which triggers a call to "get_measurements" function and receive a list of "measurements" which should populate the measurement select box. Currently when I select the experiment I see the json response as expected:
{1: "MyFirstMeasurment", 2: "MySecondMeasurement"}
The measurement select box received 2 new selections however, both of them have the text "undefined" as opposed to "MyFirstMeasurement" and "MySecondMeasurement". I am guessing this is something simple in my code, Thank you for the help, let me know if you need more information.
It turns out I needed to do a couple of things to fix this, thanks for the help and hints. Here is the final code.
$(document).ready(function(){
$('select[name=experiment]').change(function(){
experiment_id = $(this).val();
request_url = '/admin/get_measurements/' + experiment_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data, function(key, value){
$('select[name=measurement_a]').append("<option value='" + value + "'>" + value +</option>");
});
},
return: false
})
})
});

Categories

Resources