No data is displayed error in Fusioncharts - javascript

I used ajax to render the chart.I have two files index.php ,selectchart.php.In index.php, i have used ajax to render chart.
<div class="chart-area">
<div id="chart-1"><!-- Fusion Charts will render here--></div>
<div id="chart-mon"><!-- Fusion Charts will render here--></div>
Above, chart-1 div used to annual report,then we choose month the chart will display as per choose.
</div>
<p><select class="btn btn-light btn-icon-split" id="country" name="country">
<option>--Select Month--</option>
<option value="01">JAN</option>
<option value="02">FEB</option>
<option value="03">MAR</option>
<option value="04">APR</option>
<option value="05">MAY</option>
<option value="06">JUN</option>
<option value="07">JUL</option>
<option value="08">AUG</option>
<option value="09">SEP</option>
<option value="10">OCT</option>
<option value="11">NOV</option>
<option value="12">DEC</option>
</select></p>
Javascript
<script type="text/javascript">
$('#country').change(function() {
var selectedcountry = $(this).children("option:selected").val();
//alert(selectedcountry);
$.ajax({
type : "POST",
url : "selectchart.php?country="+selectedcountry,
data : selectedcountry,
success: function(result)
{
$("#chart-1").hide();
//$("#myDiv").show();
alert(result);
var myChart = new FusionCharts("column2D", "myThird", 400, 300, "json", result);
myChart.render("chart-mon");
}
});
});
</script>
I have alert the result [objectoject] showed.But in chart-mon no data is diplayed showed.but I run the selectchart.php
selectchart.php
include("includes/fusioncharts.php");
$selectdata = $_REQUEST['country'];
$dbhandle = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
$strQuerymon = "SELECT name, amount FROM income WHERE month = '$selectdata'ORDER BY amount DESC LIMIT 10";
$resultmon = $dbhandle->query($strQuerymon) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
if ($resultmon) {
$arrDatamon = array(
"chart" => array(
"showValues" => "0",
"theme" => "zune"
)
);
$arrDatamon["data"] = array();
while($rowmon = mysqli_fetch_array($resultmon)) {
array_push($arrDatamon["data"], array(
"label" => $rowmon["name"],
"value" => $rowmon["amount"]
)
);
}
$jsonEncodedDatamon = json_encode($arrDatamon);
echo $jsonEncodedDatamon;
header('Content-type: text/json');
}
{"chart":{"showValues":"0","theme":"zune"},"data":[{"label":"washing","value":"1000"},{"label":"cleanin","value":"444"},{"label":"rwr","value":"333"},{"label":"sample","value":"300"},{"label":"werew","value":"33"},{"label":"demo","value":"10"}]} these values are displayed.[enter image description here][1]

Solution 1:
I think you passed wrong:
Instead of it
var myChart = new FusionCharts("column2D", "myChartId" , 400, 300, "json", "result");
You have to pass:
var myChart = new FusionCharts("column2D", "myChartId" , 400, 300, "json", result);
Because result(it's variable) is your response which is came from your selectchart.php page.

Related

Why i cant clear my dropdownlist preselect? [duplicate]

This belong to codes prior to Select2 version 4
I have a simple code of select2 that get data from AJAX.
$("#programid").select2({
placeholder: "Select a Program",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "ajax.php",
dataType: 'json',
quietMillis: 200,
data: function (term, page) {
return {
term: term, //search term
flag: 'selectprogram',
page: page // page number
};
},
results: function (data) {
return {results: data};
}
},
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
This code is working, however, I need to set a value on it as if in edit mode. When user select a value first time, it will be saved and when he needs to edit that value it must appear in the same select menu (select2) to select the value previously selected but I can't find a way.
UPDATE:
The HTML code:
<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">
Select2 programmatic access does not work with this.
SELECT2 < V4
Step #1: HTML
<input name="mySelect2" type="hidden" id="mySelect2">
Step #2: Create an instance of Select2
$("#mySelect2").select2({
placeholder: "My Select 2",
multiple: false,
minimumInputLength: 1,
ajax: {
url: "/elements/all",
dataType: 'json',
quietMillis: 250,
data: function(term, page) {
return {
q: term,
};
},
results: function(data, page) {
return {results: data};
},
cache: true
},
formatResult: function(element){
return element.text + ' (' + element.id + ')';
},
formatSelection: function(element){
return element.text + ' (' + element.id + ')';
},
escapeMarkup: function(m) {
return m;
}
});
Step #3: Set your desired value
$("#mySelect2").select2('data', { id:"elementID", text: "Hello!"});
If you use select2 without AJAX you can do as follow:
<select name="mySelect2" id="mySelect2">
<option value="0">One</option>
<option value="1">Two</option>
<option value="2">Three</option>
</select>
/* "One" will be the selected option */
$('[name=mySelect2]').val("0");
You can also do so:
$("#mySelect2").select2("val", "0");
SELECT2 V4
For select2 v4 you can append directly an option/s as follow:
<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
<option value="TheID" selected="selected">The text</option>
</select>
Or with JQuery:
var $newOption = $("<option selected='selected'></option>").val("TheID").text("The text")
$("#myMultipleSelect2").append($newOption).trigger('change');
other example
$("#myMultipleSelect2").val(5).trigger('change');
To dynamically set the "selected" value of a Select2 component:
$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});
Where the second parameter is an object with expected values.
UPDATE:
This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}
Example:
$('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});
Thanks to #NoobishPro
Html:
<select id="lang" >
<option value="php">php</option>
<option value="asp">asp</option>
<option value="java">java</option>
</select>
JavaScript:
$("#lang").select2().select2('val','asp');
jsfiddle
Also as I tried, when use ajax in select2, the programmatic control methods for set new values in select2 does not work for me!
Now I write these code for resolve the problem:
$('#sel')
.empty() //empty select
.append($("<option/>") //add option tag in select
.val("20") //set value for option to post it
.text("nabi")) //set a text for show in select
.val("20") //select option of select2
.trigger("change"); //apply to select2
You can test complete sample code in here link: https://jsfiddle.net/NabiKAZ/2g1qq26v/32/
In this sample code there is a ajax select2 and you can set new value with a button.
$("#btn").click(function() {
$('#sel')
.empty() //empty select
.append($("<option/>") //add option tag in select
.val("20") //set value for option to post it
.text("nabi")) //set a text for show in select
.val("20") //select option of select2
.trigger("change"); //apply to select2
});
$("#sel").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
function formatRepo(repo) {
if (repo.loading) return repo.text;
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + repo.full_name + "</div>";
if (repo.description) {
markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
}
markup += "<div class='select2-result-repository__statistics'>" +
"<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
"<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
"<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatRepoSelection(repo) {
return repo.full_name || repo.text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://select2.org/assets/a7be624d756ba99faa354e455aed250d.css">
<select id="sel" multiple="multiple" class="col-xs-5">
</select>
<button id="btn">Set Default</button>
I did like this-
$("#drpServices").select2().val("0").trigger("change");
var $option = $("<option selected></option>").val('1').text("Pick me");
$('#select_id').append($option).trigger('change');
Try this append then select. Doesn't duplicate the option upon AJAX call.
In the current version on select2 - v4.0.1 you can set the value like this:
var $example = $('.js-example-programmatic').select2();
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });
// Option 2 if you can't trigger the change event.
var $exampleDestroy = $('.js-example-programmatic-destroy').select2();
$(".js-programmatic-set-val").on("click", function () { $exampleDestroy.val("CA").select2('destroy').select2(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
using "trigger(change)"
<select class="js-example-programmatic">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
<optgroup label="Pacific Time Zone">
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</optgroup>
<optgroup label="Mountain Time Zone">
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
</optgroup>
<optgroup label="Central Time Zone">
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="IL">Illinois</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="OK">Oklahoma</option>
<option value="SD">South Dakota</option>
<option value="TX">Texas</option>
<option value="TN">Tennessee</option>
<option value="WI">Wisconsin</option>
</optgroup>
<optgroup label="Eastern Time Zone">
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="IN">Indiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="OH">Ohio</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</optgroup>
</select>
using destroy:
<select class="js-example-programmatic">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
<optgroup label="Pacific Time Zone">
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</optgroup>
<optgroup label="Mountain Time Zone">
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
</optgroup>
<optgroup label="Central Time Zone">
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="IL">Illinois</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="OK">Oklahoma</option>
<option value="SD">South Dakota</option>
<option value="TX">Texas</option>
<option value="TN">Tennessee</option>
<option value="WI">Wisconsin</option>
</optgroup>
<optgroup label="Eastern Time Zone">
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="IN">Indiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="OH">Ohio</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</optgroup>
</select>
<button class="js-programmatic-set-val">set value</button>
$('#inputID').val("100").select2();
It would be more appropriate to apply select2 after choosing one of the current select.
Set the value and trigger the change event immediately.
$('#selectteam').val([183,182]).trigger('change');
I think you need the initSelection function
$("#programid").select2({
placeholder: "Select a Program",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "ajax.php",
dataType: 'json',
quietMillis: 200,
data: function (term, page) {
return {
term: term, //search term
flag: 'selectprogram',
page: page // page number
};
},
results: function (data) {
return {results: data};
}
},
initSelection: function (element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("ajax.php/get_where", {
data: {programid: id},
dataType: "json"
}).done(function (data) {
$.each(data, function (i, value) {
callback({"text": value.text, "id": value.id});
});
;
});
}
},
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
HTML
<select id="lang" >
<option value="php">php</option>
<option value="asp">asp</option>
<option value="java">java</option>
</select>
JS
$("#lang").select2().val('php').trigger('change.select2');
source: https://select2.github.io/options.html
For Ajax, use $(".select2").val("").trigger("change"). That should solve the problem.
In Select2 V.4
use $('selector').select2().val(value_to_select).trigger('change');
I think it should work
$("#select_location_id").val(value);
$("#select_location_id").select2().trigger('change');
I solved my problem with this simple code. Where #select_location_id is an ID of select box and value is value of an option listed in select2 box.
An Phan's answer worked for me:
$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});
But adding the change trigger the event
$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'}).change();
Sometimes, select2() will be loading firstly, and that makes the control not to show previously selected value correctly. Putting a delay for some seconds can resolve this problem.
setTimeout(function(){
$('#costcentreid').select2();
},3000);
you can use this code :
$("#programid").val(["number:2", "number:3"]).trigger("change");
where 2 in "number:2" and 3 in "number:3" are id field in object array
This work for me fine:
initSelection: function (element, callback) {
var id = $(element).val();
$.ajax("url/" + id, {
dataType: "json"
}).done(function (data) {
var newOption = new Option(data.title, data.id, true, true);
$('#select2_id').append(newOption).trigger('change');
callback({"text": data.title, "id": data.id});
});
},
You can use this code:
$('#country').select2("val", "Your_value").trigger('change');
Put your desired value instead of Your_value
Hope It will work :)
Official Select2 documentation says:
For Select2 controls that receive their data from an AJAX source, using .val() will not work. The options won't exist yet, because the AJAX request is not fired until the control is opened and/or the user begins searching.
To set value in select2 field place <option> tag inside <select> tag during page rendering:
<select id="input-degree">
<option value="1">Art</option>
</select>
When page is loaded you'll see Art in select2 field. If we click on this field data will be fetched from the server via ajax and other options will be shown.
Preselecting options in an remotely-sourced (AJAX) Select2
For Select2 controls that receive their data from an AJAX source, using .val() will not work. The options won't exist yet, because the AJAX request is not fired until the control is opened and/or the user begins searching. This is further complicated by server-side filtering and pagination - there is no guarantee when a particular item will actually be loaded into the Select2 control!
The best way to deal with this, therefore, is to simply add the preselected item as a new option. For remotely sourced data, this will probably involve creating a new API endpoint in your server-side application that can retrieve individual items:
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
I did something like this to preset elements in select2 ajax dropdown
//preset element values
$(id).val(topics);
//topics is an array of format [{"id":"","text":""}, .....]
setTimeout(function(){
ajaxTopicDropdown(id,
2,location.origin+"/api for gettings topics/",
"Pick a topic", true, 5);
},1);
// ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url
You should use:
var autocompleteIds= $("#EventId");
autocompleteIds.empty().append('<option value="Id">Text</option>').val("Id").trigger('change');
// For set multi selected values
var data = [];//Array Ids
var option = [];//Array options of Ids above
autocompleteIds.empty().append(option).val(data).trigger('change');
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
// append the new option
$("#EventId").append('<option value="' + response.id + '">' + response.text + '</option>');
// get a list of selected values if any - or create an empty array
var selectedValues = $("#EventId").val();
if (selectedValues == null) {
selectedValues = new Array();
}
selectedValues.push(response.id); // add the newly created option to the list of selected items
$("#EventId").val(selectedValues).trigger('change'); // have select2 do it's thing
});
If you are using an Input box, you must set the "multiple" property with its value as "true". For example,
<script>
$(document).ready(function () {
var arr = [{ id: 100, text: 'Lorem Ipsum 1' },
{ id: 200, text: 'Lorem Ipsum 2'}];
$('#inputID').select2({
data: arr,
width: 200,
multiple: true
});
});
</script>
In select2 < version4 there is the option initSelection() for remote data loading, through which it is possible to set initial value for the input as in edit mode.
$("#e6").select2({
placeholder: "Search for a repository",
minimumInputLength: 1,
ajax: {
// instead of writing the function to execute the request we use Select2's convenient helper
url: "https://api.github.com/search/repositories",
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
q: term, // search term
};
},
results: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter the remote JSON data
return { results: data.items };
},
cache: true
},
initSelection: function(element, callback) {
// the input tag has a value attribute preloaded that points to a preselected repository's id
// this function resolves that id attribute to an object that select2 can render
// using its formatResult renderer - that way the repository name is shown preselected
var id = $(element).val();
if (id !== "") {
$.ajax("https://api.github.com/repositories/" + id, {
dataType: "json"
}).done(function(data) { callback(data); });
}
},
formatResult: repoFormatResult, // omitted for brevity, see the source of this page
formatSelection: repoFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
Source Documentation : Select2 - 3.5.3
Just to add to anyone else who may have come up with the same issue with me.
I was trying to set the selected option of my dynamically loaded options (from AJAX) and was trying to set one of the options as selected depending on some logic.
My issue came because I wasn't trying to set the selected option based on the ID which needs to match the value, not the value matching the name!
For multiple values something like this:
$("#HouseIds").select2("val", #Newtonsoft.Json.JsonConvert.SerializeObject(Model.HouseIds));
which will translate to something like this
$("#HouseIds").select2("val", [35293,49525]);
This may help someone loading select2 data from AJAX while loading data for editing (applicable for single or multi-select):
During my form/model load :
$.ajax({
type: "POST",
...
success: function (data) {
selectCountries(fixedEncodeURI(data.countries));
}
Call to select data for Select2:
var countrySelect = $('.select_country');
function selectCountries(countries)
{
if (countries) {
$.ajax({
type: 'GET',
url: "/regions/getCountries/",
data: $.param({ 'idsSelected': countries }, true),
}).then(function (data) {
// create the option and append to Select2
$.each(data, function (index, value) {
var option = new Option(value.text, value.id, true, true);
countrySelect.append(option).trigger('change');
console.log(option);
});
// manually trigger the `select2:select` event
countrySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
}
and if you may be having issues with encoding you may change as your requirement:
function fixedEncodeURI(str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");
}
To build ontop of #tomloprod's answer. By the odd chance that you are using x-editable, and have a select2(v4) field and have multiple items you need to pre-select. You can use the following piece of code:
$("#select2field").on("shown", function(e, editable){
$(["test1", "test2", "test3", "test4"]).each(function(k, v){
// Create a DOM Option and pre-select by default~
var newOption = new Option(v.text, v.id, true, true);
// Append it to the select
$(editable.input.$input).append(newOption).trigger('change');
});
});
and here it is in action:
var data = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 2,
text: 'duplicate'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
$("#select2field").editable({
type: "select2",
url: './',
name: 'select2field',
savenochange: true,
send: 'always',
mode: 'inline',
source: data,
value: "bug, wontfix",
tpl: '<select style="width: 201px;">',
select2: {
width: '201px',
tags: true,
tokenSeparators: [',', ' '],
multiple: true,
data:data
},
success: function(response, newValue) {
console.log("success")
},
error: function(response, newValue) {
if (response.status === 500) {
return 'Service unavailable. Please try later.';
} else {
return response.responseJSON;
}
}
});
var preselect= [
{
id: 1,
text: 'bug'
},
{
id: 4,
text: 'wontfix'
}
];
$("#select2field").on("shown", function(e, editable){
$(preselect).each(function(k, v){
// Create a DOM Option and pre-select by default~
var newOption = new Option(v.text, v.id, true, true);
// Append it to the select
$(editable.input.$input).append(newOption).trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
<a id="select2field">bug, wontfix</a>
I guess that this would work even if you aren't using x-editable. I hope that htis could help someone.
I use select2 with ajax source with Laravel. In my case it simple work cycling option i receive from page and add Option to select2..
$filtri->stato = [1,2,...];
$('#stato') is my select2 with server side load
<script>
#foreach ($filtri->stato as $item)
$('#stato').append(new Option("{{\App\Models\stato::find($item)->nome}}",{{$item}}, false, true));
#endforeach
</script>
In my case I can call text of option with find method, but it's possible do it with ajax call

How can I do pagination in html vue js?

How can I able to to do pagination in html vue js. When I click on first page I need to set the offset as 0, when I click on 2 page i need to send offset as 100 and so on. How can I able to send offset like that.
My html code for pagination is
<div class="col-md-12">
<div class="pull-right">
<div class="pagination">
<ul>
<li>Prev</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>Next</li>
</ul>
</div>
</div>
</div>
<div class="items-per-page">
<label for="items_per_page"><b>Property per page :</b></label>
<div class="sel">
<select id="items_per_page" name="limit" v-model="limit">
<option value="3">3</option>
<option value="6">6</option>
<option value="9">9</option>
<option selected="selected" value="12">12</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
<option value="60">60</option>
</select>
</div><!--/ .sel-->
</div><!--/ .items-per-page-->
Based on the offset I need to go on adding the pages. How can it be possible.
My views.py is
#csrf_exempt
def search(request):
if request.method == 'POST':
category = request.POST.get('category')
city = request.POST.get('city')
name = request.POST.get('name')
d = {
'category': category,
'city': city,
'name': name,
}
return render(request, "search.html", d);
else:
# do the thing you want to do in GET method
return render(request,"search.html",{});
My urls.py is
url(r'^search',views.search),
My vue js code is
<script>
searchContent = new Vue({
el: "#searchContent",
data: {
vector: {}
}
});
categories = new Vue({
el: '#categories',
data: {
offset: '',
limit:'',
place: '',
category: '',
inventory: '',
name: '',
city: '',
district: '',
},
methods: {
prefetch: function() {
var filter = {};
if (this.category != '')
filter['category'] = this.category;
if (this.inventory != '')
filter['inventory'] = this.inventory;
if (this.name != '')
filter['name'] = this.name;
if (this.city != '')
filter['city'] = this.city;
if (this.district != '')
filter['district'] = this.district;
if (this.place != '')
filter['place'] = this.place;
//Here I need to provide offset and limit
filter['limit'] = this.limit;
filter['offset'] = this.offset.
if (this.content !== false)
this.content.abort()
this.content = $.ajax({
'url': '/filter/',
data: filter,
dataType: "JSON",
type: "POST",
success: function(e) {
window.searchContent.vector = e.data;
console.log(e);
}
})
}
}
})
</script>
So based on selection of pages in pagination, How can I able to send the corresponding offset value, Please help me to have a solution. I haven't done pagination before
If I select 1, i need to send offset as 50, if 2-100. if 3-150 and so on, I have given in an href IS IT CORRECT.
How can I able to implement easily

Add working hours of a Organization

If I select Sunday, Monday and working hours from 08.00 to 20.00 I need to send 1&08:00&20:00,2&08:00&20:00. How can I able to implement the same in vue javascript?
My current code is
<script>
submitBox = new Vue({
el: "#submitBox",
data: {
articles: [],
services: [],
username: '',
category: '',
subcategory: [],
image: '',
hours: '',
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
handelSubmit: function(e) {
var vm = this;
data = {};
data['lat'] = this.$refs.myLatField.value;
data['lng'] = this.$refs.myLngField.value;
data['username'] = this.username;
data['category'] = this.category;
data['subcategory'] = this.subcategory;
data['image'] = this.image;
data['hours'] = this.hours;
$.ajax({
url: 'http://127.0.0.1:8000/api/add/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status) {
alert("Registration Success")
window.location.href = "https://localhost/n2s/registersuccess.html";
} else {
vm.response = e;
alert("Registration Failed")
}
}
});
return false;
}
},
});
</script>
My html form is
<div id="submitBox">
<form method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
<input type="checkbox" value="1" v-model="hours">Sunday
<select>From
<option value="">08.00</option>
<option value="">12.00</option>
<option value="">20.00</option>
<option value="">24.00</option>
</select>
<select>To
<option value="">08.00</option>
<option value="">12.00</option>
<option value="">20.00</option>
<option value="">24.00</option>
</select><br>
<input type="checkbox" value="2" v-model="hours">Monday
<select>
<option value="">08.00</option>
<option value="">12.00</option>
<option value="">20.00</option>
<option value="">24.00</option>
</select>
<select>
<option value="">08.00</option>
<option value="">12.00</option>
<option value="">20.00</option>
<option value="">24.00</option>
</select><br>
</form>
</div>
I am able to pass all other values. So, I haven't included that in the form.
How can I able to select day and working hours and pass it accordingly. Please help me to solve the same
I am not familar with vue.js but you can try something like:
new Vue({
el: '#example-3',
data: {
day:[
{name:"Sunday",val:1},
{name:"Monday",val:2}
],
string:''
},
methods: {
generate: function (event) {
var arr = [];
this.day.map(function(v,i) {
console.log(v.selected == true,);
if(v.selected == true)
{
arr.push(v.val+'&'+v.from+'&'+v.to);
}
});
this.string = arr.join(',');
}
}
})
html:
<div id='example-3'>
<div v-for="value in day">
<input type="checkbox" id="sun" value="value.val" v-model="value.selected">
<label for="sun">{{value.name}}</label>
<select v-model="value.from">From
<option value="08.00">08.00</option>
<option value="12.00">12.00</option>
<option value="20.00">20.00</option>
<option value="24.00">24.00</option>
</select>
<select v-model="value.to">To
<option value="08.00">08.00</option>
<option value="12.00">12.00</option>
<option value="20.00">20.00</option>
<option value="24.00">24.00</option>
</select>
<br>
</div>
<button v-on:click="generate">generate</button>
<span>string: {{ string }}</span>
demo:https://jsfiddle.net/d8ak8ob6/1/

How to change the value of the drop-down on change event?

I have two drop-down lists which are from same table. One contains employee code and second one contains employee name. If I change the employee code then other drop-down should show the employee name relevant to code and if I change the employee name then it should show the code. I am able to successfully retrieve the values but I am unable to show value in the drop-down. Following is my code:
$("select#code").on("change", function () {
getNameFunc($(this).val())
});
$("select#empName").on("change", function () {
getCodeFunc($(this).val())
});
function getNameFunc(value) {
$.ajax({
url: '#Url.Action("getName", "Employees")',
data: { id: value },
cache: false,
type: "GET",
success: function (data) {
$("#empName").val(data.Name);
}
});
}
function getCodeFunc(value) {
$.ajax({
url: '#Url.Action("getCode", "Employees")',
data: { id: value },
cache: false,
type: "GET",
success: function (data) {
$("#code").val(data.Code);
}
});
}
My drop-down list:
#Html.DropDownList("EmpCode", null, htmlAttributes: new { id = "code" })
#Html.DropDownList("EmpName", null, htmlAttributes: new { id = "empName" })
In alert function, I am getting expected value but the problem is displaying it in to drop-down list.
Simple , Try it , Let me assume selects render as , this is dummy test , best approch you must save value = EmpID
Emp Name dropdown
<select id="name">
<option value="EmpID1"> Name 1 </option>
<option value="EmpID2"> Name 2 </option>
</select>
Emp Code dropdown
<select id="code">
<option value="EmpID1"> Code 1 </option>
<option value="EmpID2"> Code 2 </option>
</select>
Inside your ajax , if you want change/load name front the of the dropdown then
Value set by value
$('#name').val(data.EmpID1)
Similarly reverse
$('#code').val(data.EmpID1)
Value set by text / name
$('#name option:selected').text(data.Name)
Check this code. You might get help from this.
Note that I have not implemented ajax call in this code.
$("#emp_code").on("change",function(){
$("#emp_name").val($("#emp_code").val());
});
$("#emp_name").on("change",function(){
$("#emp_code").val($("#emp_name").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Emp Code:</label>
<select id="emp_code">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br/>
<label>Emp Name:</label>
<select id="emp_name">
<option value="1">ABC</option>
<option value="2">XYZ</option>
<option value="3">PQR</option>
<option value="4">JKL</option>
</select>

jQuery select2 dynamic options

I have a multiselect that I want to use as a search box so that the user can search by category, event type, location and keywords. It has the following structure:
<select name="search-term[]" multiple="multiple">
<optgroup label="Categories">
<option value="category_4">Internal</option>
<option value="category_2">Business</option>
<option value="category_5">External</option>
<option value="category_1">Science</option>
<option value="category_6">Sports and Social</option>
</optgroup>
<optgroup label="Event Types">
<option value="eventtype_2">Meeting</option>
<option value="eventtype_3">Social Activity</option>
<option value="eventtype_4">Sporting Activity</option>
<option value="eventtype_1">Symposium</option>
</optgroup>
<optgroup label="Locations">
<option value="location_2">Office 1</option>
<option value="location_3">Office 2</option>
<option value="location_1">Office 3</option>
</optgroup>
</select>
I have initialised select2 with the tags option set to true so like so:
$('select').select2({
tags : true,
createTag: function (params)
{
return {
id: 'keyword_' + params.term,
text: params.term,
newOption: true
}
}
});
This allows users to enter a new option if it doesn't exist and takes care of the keywords requirement. Any new tags are appended with keyword_ so that the server knows how to handle them when the form is submitted.
This is all working as I expected however the issue I've come across is if someone wants to search for a keyword that is called the same as one of the other options then they aren't able to create a new keyword tag it will only let them select the existing option. For example if I search Office 1 I may want to search for events that are located at office 1 or I may want to do a keyword search so that I am searching for events that have office 1 in the title. The problem is currently I'm only able to select the location option I'm not able to create a new tag. Does anyone know how I could achieve this?
I achieved this in the end by using an AJAX datasource which gives you much more control over what options are shown to the user. Here is my code:
$('select').select2({
ajax: {
url: "/server.php",
dataType: 'json',
type: "GET",
delay: 0,
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id,
children: item.children
}
})
};
},
cache: false
},
templateSelection: function(item)
{
return item.parent+': '+item.text;
}
});
Contents of server.php:
<?php
$term = !isset($_GET['term']) ? null : ucfirst($_GET['term']);
$categories = array('Meeting', 'Seminar', 'Sports and Social');
$locations = array('Cambridge', 'London', 'Northwich');
$matching_categories = array();
$matching_locations = array();
foreach($categories as $i => $cat) {
if(is_null($term) || stripos($cat, $term)!==false) {
$matching_categories[] = array(
'id' => 'category_'.$i,
'text' => $cat,
'parent' => 'Category'
);
}
}
foreach($locations as $i => $loc) {
if(is_null($term) || stripos($loc, $term)!==false) {
$matching_locations[] = array(
'id' => 'location_'.$i,
'text' => $loc,
'parent' => 'Location'
);
}
}
$options = array();
if(!empty($matching_categories)) {
$options[] = array(
'text' => 'Category',
'children' => $matching_categories
);
}
if(!empty($matching_locations)) {
$options[] = array(
'text' => 'Location',
'children' => $matching_locations
);
}
if(!is_null($term)) {
$options[] = array(
'text' => 'Keyword',
'children' => array(
array(
'id' => 'keyword_'.$term,
'text' => $term,
'parent' => 'Keyword'
)
)
);
}
echo json_encode($options);

Categories