how to format currency in ajax - javascript

I have ajax data and want to change the format of numbers into currency, how to change the format? in php used echo number_format($list->REAL_SUBPRO_VAL, 2, ',', '.'), how about in ajax?
this is my ajax
function status(id_branch) {
$('#status').show(function(){
$.ajax({
url:"<?php echo base_url() ?>home/list_investasi_status/" + id_branch,
success(res){
var data = JSON.parse(res);
console.log(data);
$('#nama_cabang3').text(data.data2['DISPLAY_NAME']);
var data_status = "";
$.each(data.data, function(key, val){
data_status += "<tr>\
<td>" + val.RKAP_INVS_ID + "</td>\
<td>" + val.RKAP_INVS_TITLE + "</td>\
<td>" + val.RKAP_INVS_COST_REQ + "</td>\
<td>" + val.RKAP_INVS_VALUE + "</td>\
<td>" + 'Detail' + "</td>\
</tr>";
});
$('#show_status').html(data_status);
/*dropdown*/
var d_status = "";
$.each(data.data3, function(key, val){
d_status += "<option >" + val.STATUS_NAME + "</option>";
});
// value="val.STATUS_NAME"
$('#show_d_status').html(d_status);
}
})
});
example: val.RKAP_INVS_VALUE = 10000000, i want to format value to 1.000.000. help please thanks

Try the javascript splice method to insert a . into the string at the places you need. Here is the function doing it:
Moreover, you can use the php method number_format($list->REAL_SUBPRO_VAL, 2, ',', '.') and return your data in JSON so you will get a preformatted text.
var main = '1000000';
var ins = '.';
insert = function insert(main_string, ins_string, pos) {
if (typeof(pos) == "undefined") {
pos = 0;
}
if (typeof(ins_string) == "undefined") {
ins_string = '';
}
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var newstring = insert(main, ins, 1);
alert(insert(newstring, ins, 5));

Related

How can I check checkbox which is exists in model sepereted by coma from database (as shown below in code) using MVC asp.net?

Below is code of javascript. I want my checkboxes are selected based on coma seperated values from database. please let me know where i am mistaken
function GetStatesList() {
debugger;
var makeList = [];
var url = '/IAAISettings/GetStatesList';
$.ajax({
type: 'POST',
url: url,
success: function(stateList) {
var makeChkList = ""
for (var i = 0; i < stateList.length; i++) {
var st = stateList[i];
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + stateList[i] + "\" name=\"State_" + stateList[i] + "\" checked=\"" + #Model.States.Contains("Alaska") ? "checked" + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
document.getElementById('StateschkList').innerHTML = makeChkList;
},
error: function(r) {
OnFailure(r);
},
failure: function(r) {
OnFailure(r);
}
});
}
I found issue. because of js is client side and model loads before js load it was not getting modal value and to get value we have to use this line
#Html.Raw(Json.Encode(Model.States));
function GetStatesList() {
debugger;
var arrstates = [];
var url = '/IAAISettings/GetStatesList';
$.ajax({
type: 'POST',
url: url,
success: function (stateList) {
var makeChkList = ""
var st =#Html.Raw(Json.Encode(Model.States));
arrstates = st.split(",");
console.log(st);
for (var i = 0; i < stateList.length; i++) {
var str = stateList[i];
if (arrstates.includes(stateList[i])) {
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + stateList[i] + "\" name=\"State_" + stateList[i] + "\" checked=checked\"" + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
else {
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + i + "\" name=\"State_" + i + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
}
document.getElementById('StateschkList').innerHTML = makeChkList;
},
error: function (r) {
OnFailure(r);
},
failure: function (r) {
OnFailure(r);
}
});
}

Jquery DataTables showing "No data available in table" althou the data is displayed

I am trying to complete my code that dynamically produces a table using Jquery DataTables plugin.
The code works up to a point, it displays the data but above the data it also displays "No data available in table".
From what I have read it is something to do with the table initialisation, Can anyone see where I am going wrong.
$(document).ready(function(){
$('#userTable').DataTable( {
"ordering": false,
paging: false,
searching: false,
language: {
emptyTable: "No data available in table", //
loadingRecords: "Please wait .. ", // default Loading...
zeroRecords: "No matching records found"
},
"stripeClasses": [ 'odd-row', 'even-row' ]
});
$.ajax({
url: 'server_processing.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var recordid = response[i].RecordID;
var deviceid = response[i].DeviceID;
var mediatype = response[i].MediaType;
var screenlocation = response[i].ScreenLocation;
var promotionname = response[i].PromotionName;
var fromdate = response[i].FromDate;
var fromtime = response[i].FromTime;
var todate = response[i].ToDate;
var totime = response[i].ToTime;
var promotionimage = response[i].PromotionImage;
var orientation = response[i].Orientation;
var enddate = todate +' '+totime;
var startdate = fromdate +' '+fromtime;
var now = new Date();
var nowdate = fixDigit(now.getDay()) + '-' +fixDigit(now.getMonth() + 1) + '-' + now.getFullYear()+' ' +now.getHours() + ":" + now.getMinutes();
// Utility function to prepend zeros to single digits:
function fixDigit(val){
return val.toString().length === 1 ? "0" + val : val;
}
var tr_str = "<tr class='TableText'>" +
"<td style='color:#333;font-size:0.8em;'>" + promotionname + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + deviceid + " " + screenlocation + "</td>" +
"<td align='center' style='color:#333;font-size:0.8em;'>" + orientation + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + promotionimage + "</td>" +
"<td align='center' style='color:#333;font-size:0.8em;'>" + mediatype + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + fromdate + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + todate + "</td>"
if( (new Date(startdate).getTime() > new Date(nowdate).getTime())) {
tr_str += "<td align='center' style='color:#333;font-size:0.8em;' class='Active'>Active</td>";
} else {
tr_str += "<td align='center' style='color:#333;font-size:0.8em;' class='Scheduled'>Scheduled</td>";
}
tr_str += "<td align='center' style='color:#333;font-size:0.8em;'><input type='button' name='edit' value='Edit' id=" + (i+1) + " class='btn btn-info btn-xs btn-block edit_data'></td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
});
Many thanks in advance for you help and time.
This is because you are appending content without deleting previous, "no data" massage is a row, so you should clear it before for loop:
success: function(response){
var len = response.length;
$("#userTable tbody").html("");
for(var i=0; i<len; i++){
var recordid = response[i].RecordID;
var deviceid = response[i].DeviceID;
...
One thing, this is not the best way to insert data in datatables.

Change position of data in tables

I have written JavaScript which retrieves data and sets it into a series of tables as shown below.
$(function()
{
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'9BBF789F-E5BA-449D-A595-BAA326E2C8FF')/Items?$expand=Category&$select=Id,Related_x0020_Working_x0020_PracId,Title,Reference,Policy_x0020_Type,Category/Title&$orderby=Category/Title asc",
type:"get",
headers: { "accept": "application/json;odata=verbose" },
success: function(dataObj)
{
//to uniquely identifiy the accordion.
var intCat = 0;
var arrPolicies = [];
var arrCategories = [];
//Get the policies and seperate out the categories from the returned REST call
for(var i =0; i < dataObj.d.results.length; i++)
{
var strCategory = dataObj.d.results[i].Category.Title;
arrPolicies.push({
"Id" : dataObj.d.results[i].Id,
"Title" : dataObj.d.results[i].Title,
"Category" : strCategory,
"Ref" : dataObj.d.results[i].Reference,
"PolicyType" : dataObj.d.results[i].Policy_x0020_Type,
"WorkingPracticeId" : dataObj.d.results[i].Related_x0020_Working_x0020_PracId
});
//setting category if not found
//in array
if(arrCategories.indexOf(strCategory) == -1)
{
//Add the category to the list...
arrCategories.push(strCategory);
}
}
//Output the menu to the screen for each category - one by one
arrCategories.forEach(function(varCategory)
{
var strCatIdentifier = "tblCategory_" + intCat;
var strCatImgIdentifier = "tblCategory_image_" + intCat;
var strCategoryInfo = "<table>"+
"<tbody>" +
"<tr>"+
"<td class='category'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatIdentifier + ","+strCatImgIdentifier+")'>"+
"<img id='"+strCatImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand category'/>"+
"</a> "+
varCategory +
"</td>"+
"</tr>"+
"<tr><td>"+
"<table id='" + strCatIdentifier + "' class='indent hidden'>";
//looping through policies - add the details into the category table's cell
arrPolicies.forEach(function(varPolicy)
{
//checking the category attached to the policy is the same as what
//category it is on
if(varPolicy.Category == varCategory)
{
//checking to see if the
if(varPolicy.PolicyType == "Policy and Responsibility")
{
strCategoryInfo += "<tr>"+
"<td class='policy'>" +
"<a href='#'>"+
"<img src='"+_spPageContextInfo.webAbsoluteUrl+"/SiteAssets/Images/arrowicon.png' alt='View Document'/>"+
"</a>"
+ varPolicy.PolicyType + ": "+varPolicy.Ref +" - " + varPolicy.Title +
"</td>"+
"</tr>";
}
//If Working Practice - add in the sub-table (3rd level table) for attachments
if(varPolicy.PolicyType == "Working Practices")
{
var strCatWPIdentifier = "tblWorkingPractice" + varPolicy.Id;
var strCatWPImgIdentifier = "sub_level_image" + varPolicy.Id;
strCategoryInfo += "<tr>"+
"<td class='working_practice'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatWPIdentifier + ","+strCatWPImgIdentifier+")'>"+
"<img id='"+strCatWPImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand working practice'/>"+
"</a> "+
varPolicy.PolicyType + " - " + varPolicy.Title+
"</td>"+
"</tr>";
var intAttachmentCount = 0;
//Build a table by looping through the policies array AGAIN and only use the policies where the Policy Type is 'Attachment' AND the 'WorkingPracticeID' is the same as the pilocy ID
arrPolicies.forEach(function(varWPAttachment)
{
if(varWPAttachment.WorkingPracticeId == varPolicy.Id && varWPAttachment.PolicyType == "Working Practice Attachment")
{
intAttachmentCount++;
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
varWPAttachment.PolicyType +" - "+ varWPAttachment.Title+ " - " + varPolicy.Title+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
});
if(intAttachmentCount == 0)
{
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
"Sorry, no attachments found for this practice."+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
}
}
});
//Close the 'Category details' table
strCategoryInfo += "</table>";
//Close the table for the category...
strCategoryInfo += "</td></tr>" +
"</tbody>"+
"</table>";
intCat++;
$('#divQualityFrameworkMenu').append(strCategoryInfo + "<br />");
});
},
error: function(error)
{
alert("Error");
}
});
});
I want to be able to organise them so that related data is grouped together ie Policies are above working practices.
How would I go about doing this
This seems pretty easy. After the first for (var d = 0; [...] ) loop, but before the arrCategories.forEach([...]), just sort arrPolicies to your choosing:
arrPolicies.sort(function(policy1, policy2) {
//Policies BEFORE Working Practicies:
if (policy1.PolicyType === "Policies and Responsibilities" && policy2.PolicyType === "Working Practices") {
return -1;
}
//Working Practicies AFTER Policies:
if (policy1.PolicyType === "Working Practices" && policy2.PolicyType === "Policies and Responsibilities") {
return 1;
}
//[Include any other orderings you might have...]
//If you've reached the end here, then you must not care about the ordering of these policies, so just make them "equal":
return 0;
});

check session value (ajax)

Im making a site but i want to check the value of a session so i can show a button depending on what the users role is.
the problem im having is that i cant get the value of the session into SessionValue
i will also add that the file is a .js
what i have so far:
function getGroups() {
var SessionValue = <?php print($_SESSION['user_role']); ?>;
$.ajax({
url: 'services/functions.php',
data: {
action: 'getGroups'
},
type: 'post',
success: function (output) {
var result = JSON.parse(output);
result = result.results;
$(result).each(function (index, element) {
var out = "<div class='row'>";
out += "<div class='col-md-3'>";
out += "<img class='img-responsive image_" + index + "' src=" + element.group_image + ">";
out += "</div>";
out += "<div class='col-md-9'>";
out += "<h3>" + element.group_title + "</h3>";
if(SessionValue == "admin"){
out += "<button class='btn btn-primary pull-right' type='button' id='submitPost'>Delete</button>";
}
out += "<h4 class='hidden_" + index + "'>" + moment(element.group_playdate, 'HH:mm:ss').format('HH:mm') + "</h4>";
out += "<p class='hidden_" + index + "'>" + element.group_description + "</p>";
out += "</div>";
out += "</div>";
out += "<hr/>";
$(".groupContainer").append(out);
$(".hidden_" + index).hide();
$(".image_" + index).hover(
function () {
$('.hidden_' + index).fadeIn(200);
},
function () {
$('.hidden_' + index).fadeOut(100);
}
);
});
},
error: function (output) {
console.error("Something went wrong while loading the groups from the database.");
}
});
}
the session is started and the user_role is also defined #login.

clearInterval() not working correctly

I've recently been trying to repeat a jQuery AJAX request every two seconds. PLEASE NOTE: I've looked at the other questions on SO and not of them seem to apply to my situation, i've also looked at the documentation.
Snippet:
else if (text == "load") {
$(".response").text("working!");
var traffic = function load() {
$.ajax({url:"load.php",success:function(result){
var obj = jQuery.parseJSON(result);
var ids = obj.map(function(el) {
return "<tr><td>" + el.id + "</td><td>" + el.ip + "</td><td>" + el.proxyip + "</td><td>" + el.ping + "</td><td>" + el.time + "</td></tr>";
});
$(".response").html("<table><tr><td><strong>ID</strong></td><td><strong>IPs</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr>" + ids + "</table>");
}});
};
var trafficInterval = setInterval(traffic, 2000);
To cancle the timeout, i check to see if the text is not equal to "load", if it isnt equal to load, i cancle the timeout
else {
$(".response").text("'" + badCommand + "'" +" is not a valid command, type 'help' for a list of commands.");
clearInterval(trafficInterval);
}
HOWEVER, when i change the input of the textfield, the table will still load every two seconds, the timeout hasn't been cancled and i can't seem to see why.
Here's the whole function for people wondering
$("textarea").keyup(function(){
var text = $(this).val();
$(".log").text(text);
// Commands
if (text != "") {
var badCommand = $("textarea").val();
if (text == "help") {
$(".response").html("Commands:<br/><span class='indent'>traffic -url|all</span><span class='indent'>google #search term</span><span class='indent'>youtube #search term</span><span class='indent'>portfolio</span>")
} else if (text == "traffic") {
$(".response").html('Live traffic from:<br/><table><tr><td><strong>IP</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr><?php try { $db = new PDO("mysql:host=$mysql_host;dbname=$mysql_db", $mysql_user, $mysql_pass); $sql = "SELECT * FROM traffic ORDER BY id DESC LIMIT 50"; foreach ($db->query($sql) as $row) { echo "<tr>"; echo "<td class='details'>" . $row["ip"] . "</td>"; echo "<td class='details'>" . $row["proxyip"] . "</td>"; echo "<td class='details'>" . $row["ping"] . "</td>"; echo "<td class='details'>" . $row["time"] . "</td>"; echo "</tr>"; } $db = null; } catch(PDOException $e) { $e->getMessage(); } ?></tr></table>');
} else if (text == "load") {
$(".response").text("working!");
var traffic = function load() {
$.ajax({url:"load.php",success:function(result){
var obj = jQuery.parseJSON(result);
var ids = obj.map(function(el) {
return "<tr><td>" + el.id + "</td><td>" + el.ip + "</td><td>" + el.proxyip + "</td><td>" + el.ping + "</td><td>" + el.time + "</td></tr>";
});
$(".response").html("<table><tr><td><strong>ID</strong></td><td><strong>IPs</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr>" + ids + "</table>");
}});
};
var trafficInterval = setInterval(traffic, 2000);
} else {
$(".response").text("'" + badCommand + "'" +" is not a valid command, type 'help' for a list of commands.");
clearInterval(trafficInterval);
}
}
if (text == "") {
var noCommand = $("textarea").val();
$(".response").text(" ");
}
// End Commands
});
FYI:
Putting the clearInterval(); AFTER the code stops it from working,
Putting the clearInterval(); BEFORE the code does nothing.
The clearInterval(trafficInterval); MUST be working because if i place it at the end of the first function, nothing happens when i type "load"
It's not the timer either, i tried it instead to automatically update whenever the mouse is moved and the exact same thing happens...
This is a scoping issue. The interval needs to be outside the scope of the event handler call:
var trafficInterval = null;
$("textarea").keyup(function(){
var text = $(this).val();
$(".log").text(text);
// Commands
if (text != "") {
var badCommand = $("textarea").val();
if (text == "help") {
$(".response").html("Commands:<br/><span class='indent'>traffic -url|all</span><span class='indent'>google #search term</span><span class='indent'>youtube #search term</span><span class='indent'>portfolio</span>")
} else if (text == "traffic") {
$(".response").html('');
} else if (text == "load") {
$(".response").text("working!");
var traffic = function load() {
$.ajax({url:"load.php",success:function(result){
var obj = jQuery.parseJSON(result);
var ids = obj.map(function(el) {
return "<tr><td>" + el.id + "</td><td>" + el.ip + "</td><td>" + el.proxyip + "</td><td>" + el.ping + "</td><td>" + el.time + "</td></tr>";
});
$(".response").html("<table><tr><td><strong>ID</strong></td><td><strong>IPs</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr>" + ids + "</table>");
}});
};
trafficInterval = setInterval(traffic, 2000);
} else {
$(".response").text("'" + badCommand + "'" +" is not a valid command, type 'help' for a list of commands.");
clearInterval(trafficInterval);
}
}
if (text == "") {
var noCommand = $("textarea").val();
$(".response").text(" ");
}
// End Commands
});
See fiddle # http://jsfiddle.net/sLooj4on/ (can see polling fail in dev tools, stops when text is removed from input)
It's hard to tell without looking at the rest of the code, but your trafficInterval variable could be out of scope. Try initializing outside of the if/else statement
trafficInterval is only defined within the if statement. You're trying to clear it in the wrong scope. I still lack a bit of context here but you can try this:
var trafficInterval;
$("textarea").keyup(function() {
var text = $(this).val();
$(".log").text(text);
// Commands
if (text != "") {
var badCommand = $("textarea").val();
if (text == "help") {
$(".response").html("Commands:<br/><span class='indent'>traffic -url|all</span><span class='indent'>google #search term</span><span class='indent'>youtube #search term</span><span class='indent'>portfolio</span>")
} else if (text == "traffic") {
$(".response").html('Live traffic from:<br/><table><tr><td><strong>IP</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr><?php try { $db = new PDO("mysql:host=$mysql_host;dbname=$mysql_db", $mysql_user, $mysql_pass); $sql = "SELECT * FROM traffic ORDER BY id DESC LIMIT 50"; foreach ($db->query($sql) as $row) { echo "<tr>"; echo "<td class='
details '>" . $row["ip"] . "</td>"; echo "<td class='
details '>" . $row["proxyip"] . "</td>"; echo "<td class='
details '>" . $row["ping"] . "</td>"; echo "<td class='
details '>" . $row["time"] . "</td>"; echo "</tr>"; } $db = null; } catch(PDOException $e) { $e->getMessage(); } ?></tr></table>');
} else if (text == "load") {
$(".response").text("working!");
var traffic = function load() {
$.ajax({
url: "load.php",
success: function(result) {
var obj = jQuery.parseJSON(result);
var ids = obj.map(function(el) {
return "<tr><td>" + el.id + "</td><td>" + el.ip + "</td><td>" + el.proxyip + "</td><td>" + el.ping + "</td><td>" + el.time + "</td></tr>";
});
$(".response").html("<table><tr><td><strong>ID</strong></td><td><strong>IPs</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr>" + ids + "</table>");
}
});
};
trafficInterval = setInterval(traffic, 2000);
} else {
$(".response").text("'" + badCommand + "'" + " is not a valid command, type 'help' for a list of commands.");
clearInterval(trafficInterval);
}
}
if (text == "") {
var noCommand = $("textarea").val();
$(".response").text(" ");
}
// End Commands
Move the variable declaration
var trafficInterval = null;
before the keyup eventhandler (to move it to the outside scope). See working, stripped down example here:
http://jsbin.com/yitiquwoce/1/

Categories