Cannot populate a select box with jquery - javascript

I have a select box that I is been populated by jQuery. The options are gotten from the server via a REST call and are then used to populate the select box.
The application is also supposed to work offline but when offline these REST calls fail. So what I'm doing is when the REST calls actually pass, I store these values inside localStorage and when offline and the REST call fails, I just get the stored values inside the localStorage and try to populate the select box.
However the select boxes still appear empty. I've printed the stored values in the console and it shows that these values where actually successfully stored and retrieved. I'm not sure why my select boxes still appear empty.
$.getJSON("/openmrs/ws/rest/v1/location", function(result) {
var locations = $("#identifierLocations");
localStorage.setItem("locations", result.results);
$.each(result.results, function() {
locations.append($("<option />").val(this.uuid).text(this.display));
});
}).fail(function(jqXHR, textStatus, errorThrown) {
var data = localStorage.getItem("locations");
if (data) {
var locations = $("#identifierLocations");
for (var i = 0; i < data.length; i++) {
locations.append($("<option />").val(data[i].uuid).text(data[i].display));
}
}
});
I used console.log inside .fail() and I can confirm that data actually has all stored location objects but why does my select box still appears empty.

The issue is because localStorage can only hold strings. You need to serialise the result.results before storing them, then deserialise when retrieving them. Try this:
$.getJSON("/openmrs/ws/rest/v1/location", function(result) {
localStorage.setItem("locations", JSON.stringify(result.results));
populateLocations(result.results);
}).fail(function(jqXHR, textStatus, errorThrown) {
var data = localStorage.getItem("locations");
if (data) {
populateLocations(JSON.parse(data));
}
});
function populateLocations(locations) {
var html = locations.map(function(o) {
return '<option value="' + o.uuid + '">' + o.display + '</option>';
}).join('');
$("#identifierLocations").html(html);
}

Related

Why Dropdown list data is refilling with same values, initially I'm loading the data using page_load and next calling ajax method in asp.net c#

Initially I'm loading the ddl data using page_load and next I'm using the AJAX method and fetching the dependency data using Web Method so when I'm selecting the dependency data using `AJAX' the data is coming but the ddl is filling with previous loaded dll data I'm not sure what is the issue.
Here is my code and examples :-
Initially I'm loading the ddl data using page_load event
if (!IsPostBack)
{
firstexpdate = GetExpDates("nifty", "ce");
firststrikeprice = GetStrikePrice("nifty", firstexpdate);
lotsize = GetLotSizeVal("nifty", firstexpdate);
ltpprice = GetGreeksPrice("nifty", firstexpdate, "ce");
}
Like below I'm getting the ddl data.
And here "NIFTY" textbox is autocomplete textbox if I enter minLength: 3 this logic will execute and once enter the acc the autocomplete logic will fire and able to fetching the data from WebMethod and next I'm calling the AJAX method(because once we select the autocomplete textbox data the next ce,date,13500 ... controls data should fill autometically) for auto filling the data.
Here is how I calling the AJAX method logic
$(document).ready(function () {
//Initially I'm calling this function
autocomplete();
//Page load even I written because I used all control under the `updatepanel`
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
autocomplete();
}
});
function autocomplete() {
$("#search").autocomplete({
source: function (request, response) {
// my source logic is here and able to fetching the data successfully
//once I fetch all the symbols and next I'm calling this method
doSearch(suburbs); //Calling the Symbol Display Method{in this suburbs I'm filling the response data}
},
minLength: 3 //This is the Char length of inputTextBox
});
}
function doSearch(suburbs) {
//And here I written all my required logic and next I'm calling this method for auto fill data
//Like how I explained above query
var smbltext = $(this).text(); //Here will come `ACC` Symbol in autocomplete textbox
AutoFillUsingSymbol(smbltext); // Filling the dependency fields data
}
//This is the full logic of auto filling the controls once we select the`autocomplete`textbox data
function AutoFillUsingSymbol(symbol) {
if (symbol != '') {
var paramsmbl = { entredsmbl: symbol, selectedinstrument: $('#AutoTradeTop_Instrument option:selected').text()};
//alert(paramsmbl.entredsmbl);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoTrade.aspx/AutoFillData",
data: JSON.stringify(paramsmbl),
dataType: "json",
dataFilter: function (data) {
return data;
},
success: function (data) {
//Clearing before filling the data into ddl
$('#AutoTradeTop_expdate').empty();
$('#AutoTradeTop_strikeprice').empty();
$('#autotrade_lotsizeid').html('');
$('#LTPliveAmount').html('');
var length = data.d.length;
//data.d.each(function (index, element) {
//}
$.each(data.d, function (key, value) {
//alert(value);
if (value.indexOf("-") != -1) {
//alert(value + "date found");
$("#AutoTradeTop_expdate").append($("<option></option>").val(key).html(value));
}
else {
if (!(key == length - 2 || key == length - 1)) {
//alert(value + " value found ");
$("#AutoTradeTop_strikeprice").append($("<option></option>").val(key).html(value));
}
else {
if (key == length - 2) {
//alert(value + "LotSizeVal found");
$('#autotrade_lotsizeid').html(value);
}
else if (key == length - 1) {
//alert(value + "LTP Price found");
$('#LTPliveAmount').html(value);
}
}
}
});
},
error: function ajaxError(data) {
alert(data.status + ' : ' + data.statusText);
}
});
}
}
Once this AJAX logic hit AutoFillUsingSymbol(symbol) It will go to WebMehod logic and able to fetching the required data and filling into ddl list.
before filling into ddl data I'm clearing(emptying the dropdown list data) the ddl data and refilling
$('#AutoTradeTop_expdate').empty();
$('#AutoTradeTop_strikeprice').empty();
$('#autotrade_lotsizeid').html('');
$('#LTPliveAmount').html('');
Here is the example image of auto filling data once we select acc symbol and date is loading what I selected symbol acc
But if I select any one date the dropdown list data is clearing and filling the previous symbol data `nifty' see the above first image for reference.
example image
Note :- I know if we fill or change the dropdownlist client side code, then the list of values does not persist but initially I filled the ddl data in the page_load event and next I wrote the AJAX method but why the values are not loading properly.
Suggest me what is the issue and where I did the mistake
I'm beginner in the client side code development .

How to make dropdown based query mysql in javascript? [duplicate]

This question already has answers here:
Fetching data from MySQL database to HTML dropdown list
(4 answers)
Closed 7 years ago.
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'"> Barang: ';
row += '<select name="???">';
row += '<option value="A1">A1</option>';
row += '<option value="A2">A2</option>';
row += '<option value="A3">A3</option>';
row += '<option value="A4">A4</option>';
row += '</select>';
row += ' Satuan: <input type="text" size="5" name="satuan[]" value="'+frm.add_satuan.value+'"> Quantity: <input type="text" name="qty[]" value="'+frm.add_qty.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"><hr color=red></p>';
$('#itemRows').append($(row));
frm.add_qty.value = '';
frm.add_nama.value = '';
frm.add_satuan.value = '';
};
</script>
How to make drop-down list but with query mysql to show A1, A2, dll.
When submit button for drop-down can't post data anything. Can I store data with this javascript. For text input success post data.
DO NOT DO WHAT YOU ARE TRYING TO DO. You should never, ever, ever write queries on the front-end. You should do your absolute best to hide every detail of the server/database from the user. It is a massive security risk. Please read about SQL injection attacks for starters.
How you should do this:
Store the values of the dropsdowns in JavaScript. Let's keep them in a single object to make life easy:
Your JS:
var options = {
A1: $("#rowNum select option[value='A1']").text(),
A2: $("#rowNum select option[value='A2']").text(),
A3: $("#rowNum select option[value='A3']").text(),
A4: $("#rowNum select option[value='A4']").text()
};
// Now, send this object to your PHP via an AJAX call. Let's assume for simplicity that you will do this using jQuery:
$.ajax({
url: 'my/php/script.php',
data: options,
success: function (data) { console.log('Yay, it worked!'); },
error: function (jqXHR, textStatus, error) { console.log('crap it didn't work', jqXHR, textStatus, error); }
});
Your PHP
<?php
$options = $_REQUEST['options']
// You need to verify the options are valid (and don't have bad values) but that's a different question
// Build your query here. Your PHP is run on the server only so no one else will see it or be able to change it.
You can try this code with some modification. Use jQuery's each to iterate over the array value.
$('#emptyDropdown').empty();
// Parse the returned json data
//var opts = $.parseJSON(data);//Remove comment if you are using JSON
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i, d) {
// You will need to alter the below to get the right values from your data.
$('#emptyDropdown').append('<option value="' + d.yourID + '">' + d.yourValue + '</option>');
});

Set form data without creating DOM inputs

I have an empty form tag, and a function which generates 4000 hidden inputs which contains the data to be send by the form.
Generating the 4000 hidden inputs is pretty fast (takes about 4ms). However, the browser freezes for about 1 second when i am appending the hidden inputs in the form tag.
I have also wrapped the hidden inputs in a <div/> tag, but doesn't helps too much.
Is there any way to set the form data programmatically, without using the input DOM elements?
Something like:
$form[0].setData([{ id: 1, value: "A" }, { id: 2, value: "B" }]);
$form.submit();
Here is the function which generates the hidden inputs
function saveUIPositions() {
var $form = $("#saveUIPositionsForm");
$form.empty();
console.time("ui");
var array = [];
array.push("<div>");
var items = dataTable.dataView.getItems();
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i];
var index = dataTable.dataView.getRowById(item.Id) + 1;
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Item_Id' value='");
array.push(item.Id);
array.push("' />");
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Index' value='");
array.push(index);
array.push("' />");
}
array.push("</div>");
console.timeEnd("ui");
// here it gets very costly (and not because of array.join())
$form.append(array.join(""));
$form.submit();
};
Maybe you can send this data using ajax ? If so you will not have to generate and append your 4K hidden inputs to the DOM.
If ajax is not an option, can you give us the code generating and appending your inputs ? Maybe it can be optmized.
I wrote a small jsFiddle (open your debug console to see time informations)
to illustrate the difference between a generate then append all solution:
for(var i=0; i<4000; i++)
inputs += '<input type="hidden" value="' + i + '"/>'
$('form').append(inputs);
and generate and append each:
for(var i=0; i<4000; i++)
$form.append('<input type="hidden" value="' + i + '"/>');
You don't even really need a form element when working in just Javascript, data can be sent to your server with an ajax request.
$.ajax({
url: "myScript.php", //The script on your server that deals with the data
data: {
dataA: "a",
dataB: "b",
dataC: "c" //Your form input name and value key pairs
},
success: function(data){
alert("Form Submitted, Server Responded:"+data); //The server response
},
error: function(data){
alert("Error contacting server:"+data); //Error handler
}
});
You don't even need to reload the page when the form is submitted. Unless you want to, then just add:
location.href="http://link.com";
to the success callback.
You don't need to add the inputs to the DOM, you could create an array of the data an post the form via ajax e.g.
inputNames = 'YourInputNameHere'; // Could be an array of names
generatedData = arrrayOfData //presumably generated elsewhere
for (i=0;i<400;i++) {
formData[inputName][i] = generatedData[i]
// if you are using an array of names you want to change the above line to
// formData[inputName[i]] = generatedData[i]
}
$('body').on('submit', '#myForm', function(e) {
e.preventDefault();
postUrl = 'url/to/send/data';
// get any other use inputs that might have been taken from user ignore
// this line if there are no inputs
formData[] = $(this).serialize();
$.ajax(
{
url: postUrl,
type: 'POST',
data: formData,
dataType: 'html',
success: function( data )
{
// redirect, post message whatever
}
}
)
});
Hope this helps and makes sense.

JQuery $.ajax Google Books API using phonegap and jQueryMobile

How can I make this code work, the problem is that I can't seem to be able to acces the data returned, I know that it connects to the server, but for somereason it wont work, for example, I tried extracting the title but nothing appears.
$.ajax({
url : "https://www.googleapis.com/books/v1/volumes?q=harry+potter",
dataType : "jsonp",
async : true,
//if ajax call succeeds perform this action
success : function(result) {
ajax.parseJSONP(result);
},
//if there is an error to the ajax call perform this action
error : function(request, error) {
alert('Network error has occurred please try again!');
}
});
//parseJsonP and add new elements to list-view
var ajax = {
parseJSONP : function(result) {
//iterate each returned item
$.each(result, function(i, row) {
$('#listview_test').append('<li><h3>' + row.volumeInfo.title + '</h3></a></li>');
}); //end iteration of data returned from server and append to the list
$('#listview_test').listview('refresh'); // refresh the list-view so new elements are added to the DOM
}
}
My confusion is on the callback method, in their example Books API has a code like is shown down, but I dont get it this part q=harry+potter&callback=handleResponse, how can I make this while using the $.ajax method. Tried understanding all the pieces but still very confusing?
<body>
<div id="content"></div>
<script>
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
}
}
</script>
<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
</body>
Try replacing your following code:
$.each(result, function(i, row) {
for this one:
$.each(result.items, function(i, row) {
As per the google example code the data is located in an array called items within the returned object.

Show popup/alert if account has related entity records

I have created a custom entity called Alert. I have associated this with the out of the box Account entity.
What I want to do now is to customise the Account form so that when a user opens it, it checks if the current account has any active alerts. If it does, it should show a message informing them of this (a javascript alert?) and then navigate to the alerts view for the account.
I've done some basic javascript in CRM but I'm not sure how to query related entities.
Note Active alert is defined by the Display From and Display Until dates in the Alert being active dates (Display From <= Today AND Display Until >= Today).
Update
Thanks for pointing me in the direction of oData. I now have the following function which is looking up the account set but expanding the relationship with the alerts. I'm trying to figure out how to check if there are any alerts, currently my code always triggers the javascript alert.
function CheckForAlerts(accountId)
{
var odataSelect = "http://mscrmdev/Test/xrmservices/2011/OrganizationData.svc/AccountSet?$expand=new_account_new_alert_Account&$filter=AccountNumber eq '" + accountId + "'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest)
{
// Use only one of these two methods
// Use for a selection that may return multiple entities
ProcessReturnedEntities(data.d.results);
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
});
}
function ProcessReturnedEntities(ManyEntities)
{
var oneEntity = ManyEntities[0];
if (oneEntity != null)
{
alert('There are active alerts associated with this account.');
}
}
The best way to do this will be via an oData query from the javascript. The CRM 2011 SDK comes with some helper functions for oData calls like this. You will want to use the 'retrieveMultiple' method which will allow you to retrieve all 'alerts' with a lookup to the 'account' in question.
First add the 'RESTJQueryEditor.js' file from the SDK to your form and then you can add your own custom script to perform the retrieve. I then suggest creating the message which you wish to show the user in the callback success function, something like the following:-
retrieveMultiple('nameOfYourAlertEntitySet', '?$filter=myAccountLookupName eq ' + accountId, function(alerts){
if(alerts.length > 0)
{
var message = '';
for(var index = 0; index<alerts.length; index++)
{
message += 'alert: ' + alerts[index].name;
}
alert('Found associated alerts: ' + message);
}
else
{
alert('No associated alerts found for this account');
}
},
function(){
// Log an exception
});
You will want to make the alert message a little nicer of course and adjust your attribute names accordingly, but this is the flavour of what you want to do I believe. Additionally, you can add any further criteria on the alert entity in the filter by use of the 'and' keyword.
Let me know if you have any issues.

Categories