Javascript in Ms CRM (with odata query) is not working? - javascript

I created a javaScript(by the way i learned it yesterday only )
this script is set to fire upon OnSave event of Accounts entity .
I build a odata query using query builder tool that i found on Internet which is supposed to retrive all the tasks ($select=ActivityId,CreatedOn ) and whcih are created before 2015-01-26T18:30:00.000Z ($filter=CreatedOn ge datetime'2015-01-26T18:30:00.000Z')
here is the actual query from query builder :
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/TaskSet?$select=ActivityId,CreatedOn&$filter=CreatedOn ge datetime'2015-01-26T18:30:00.000Z'",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: true,
success: function (data, textStatus, xhr) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var ActivityId = results[i].ActivityId;
var CreatedOn = results[i].CreatedOn;
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
in the query builder it returns result :
[
{
"CreatedOn": "/Date(1422342587000)/",
"ActivityId": "c23ba479-f3a5-e411-80dc-c4346bada6a4"
},
{
"CreatedOn": "/Date(1422342783000)/",
"ActivityId": "ba7754ee-f3a5-e411-80dc-c4346bada6a4"
},
{
"CreatedOn": "/Date(1422343425000)/",
"ActivityId": "12d40a6d-f5a5-e411-80dc-c4346bada6a4"
}
]
in the result i found that created on returns date as value "CreatedOn": "/Date(1422343425000)/", ..
I wanted to retrive all the tasks created 7 days prior to creating an new record in Accounts entity ..So i wrote logic got the current dat in terms of generic value var current_date = Date().valueOf() and subtracted 7 days in milisecs (7*24*60*60*1000=604800000)
var week_earlier = current_date - 604800000;
in the code below you can see what i did
function retrive()
{
//var date =2015-01-26T18:30:00.000Z;
var current_date = Date().valueOf();
var week_earlier = current_date - 604800000;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/TaskSet?$select=ActivityId,CreatedOn&$filter=CreatedOn ge datetime'"+week_earlier+"'",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: true,
success: function (data, textStatus, xhr) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var ActivityId = results[i].ActivityId;
var CreatedOn = results[i].CreatedOn;
}
alert("number of records found :"+results.length);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
}
but its not working....it shows
"error Bad Request"
and i also tried quering with the in the url of browser with
https://avikcompany.crm5.dynamics.com/XRMServices/2011/OrganizationData.svc/TaskSet?$select=CreatedOn,ActivityId&$filter=CreatedOn ge datetime'1422342587000'(this '1422342587000' is present in result of the previously fired query).
but it also threw an error
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="ErrorPageTemplate.css" >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTTP 400 Bad Request</title>
<script src="errorPageStrings.js" language="javascript" type="text/javascript">
</script>
<script src="httpErrorPagesScripts.js" language="javascript" type="text/javascript">
</script>
</head>
<body onLoad="javascript:initHomepage(); expandCollapse('infoBlockID', true); initGoBack(); initMoreInfo('infoBlockID');">
<table width="730" cellpadding="0" cellspacing="0" border="0">
<!-- Error title -->
<tr>
<td id="infoIconAlign" width="60" align="left" valign="top" rowspan="2">
<img src="info_48.png" id="infoIcon" alt="Info icon">
</td>
<td id="mainTitleAlign" valign="middle" align="left" width="*">
<h1 id="mainTitle">The webpage cannot be found</h1>
</td>
</tr>
<tr>
<!-- This row is for HTTP status code, as well as the divider-->
<td id="http400Align" class="errorCodeAndDivider" align="right"><ID id="http400"> HTTP 400</ID>
<div class="divider"></div>
</td>
</tr>
<!-- Error Body -->
<!-- What you can do -->
<tr>
<td>
</td>
<td id="likelyCausesAlign" valign="top" align="left">
<h3 id="likelyCauses">Most likely causes:</h3>
<ul>
<li id="causeErrorInAddress">There might be a typing error in the address.</li>
<li id="causeLinkOutOfDate">If you clicked on a link, it may be out of date.</li>
</ul>
</td>
</tr>
<tr>
<td>
</td>
<td id="whatToTryAlign" valign="top" align="left">
<h2 id="whatToTry">What you can try:</h2>
</td>
</tr>
<!-- retype address -->
<tr>
<td >
</td>
<td id="retypeAddressAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<ID id="retypeAddress">Retype the address.</ID>
</td>
<tr>
</table>
</h4>
</td>
</tr>
<!-- back to previous page -->
<tr>
<td >
</td>
<td id="goBackAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<span id="goBackContainer"></span><noscript id="goBack">Go back to the previous page.</noscript>
</td>
</tr>
</table>
</h4>
</td>
</tr>
<!-- top level domain-->
<tr>
<td >
</td>
<td id="mainSiteAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<ID id="mainSite1">Go to </ID><span id="homepageContainer"><noscript id="mainSite2">the main site</noscript></span><ID id="mainSite3"> and look for the information you want.</ID>
</td>
</tr>
</table>
</h4>
</td>
</tr>
<!-- InfoBlock -->
<tr>
<td id="infoBlockAlign" align="right" valign="top">
</td>
<td id="moreInfoAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="down.png" id="infoBlockIDImage" border="0" class="actionIcon" alt="More information">
</td>
<td valign="top">
<span id="moreInfoContainer"></span>
<noscript><ID id="moreInformation">More information</ID></noscript>
</td>
</tr>
</table>
</h4>
<div id="infoBlockID" class="infoBlock">
<p id="errorExplanation">This error (HTTP 400 Bad Request) means that Internet Explorer was able to connect to the web server, but the webpage could not be found because of a problem with the address.</p>
<p id="moreInfoSeeHelp">For more information about HTTP errors, see Help.</p>
</div>
</td>
</tr>
</table>
</body>
</html>
Can any body tell me where i went wrong ?
(I am asuming the date value i mentioned is not accepeted by the crm odata service )
Or how to convert date to this format "yyyy-mm-ddThh:mm:ss.uuuZ"

You can easily get the date in that format by using toISOString();
http://jsfiddle.net/j5m97nfv/3/
var current_date = new Date().valueOf();
var week_earlier = new Date(current_date - 604800000);
var n = week_earlier.toISOString();
One problem you have in your code above is you are not constructing a new Date object. Your current_date is actually returning a date string that is not the date's representation in milliseconds. You need new Date();

Related

Group the names when age are the same in javascript

I am getting a list of members using jQuery and iterating over each of them to get a name and age. What I want to do is store the names together if they have the same age. Something like:
{
31: { John, Mary },
24: { Paul, Peter }
}
I can't seem to store them correctly.
EDIT:
This is what I have so far:
$('span.members a').each(function () {
$.ajax({
url: $(this).attr('href'),
success: function (result) {
name = $(result).find('tr td:contains("Username:")').next().text().trim();
age = $(result).find('tr td:contains("Age:")').next().text().trim();
}
});
});
EDIT:
This is the source HTML:
<table cellpadding="0" cellspacing="0" border="0" width="96%" class="box" id="testProf" style="border-spacing:0;">
<tr>
<td class="top" colspan="4">
JohnRandall
</td>
</tr>
<tr>
<td style="padding:4px" width="100" height="1" align="left">
Username:
</td>
<td style="padding:4px" height="1">
JohnRandall
</td>
<td style="padding:4px" width="130" height="1">
Add as friend
</td>
<td width="300" style="padding:0px;margin:0;overflow:hidden;" rowspan="11" valign="top"><img src="//id.crimecdn.com/0gd74.jpg" width="300" style="display: block;max-height:2000px;"></td>
</tr>
<tr class="odd">
<td style="padding:4px" align="left" height="1">
Status:
</td>
<td style="padding:4px" height="1">
<span style="color:#00ff00;" title="Online Now">•</span> <span style="color:#00ff00;">Online</span>
</td>
<td style="padding:4px" height="1">
Add as enemy
</td>
</tr>
<tr>
<td style="padding:4px" align="left" height="1">
Crew: </td>
<td height="1">
<img src="//id.crimecdn.com/o7yft.jpg" width="59" height="33" style="border:0;display: block;">
</td>
<td style="padding:4px" height="1">
Send message
</td>
</tr>
<tr class="odd">
<td style="padding:4px" align="left" height="1">
Wealth:
</td>
<td style="padding:4px" height="1">
Dangerously Healthy (?)
</td>
<td style="padding:4px" height="1">
Send money
</td>
</tr>
<tr>
<td style="padding:4px" align="left" height="1">
Age:
</td>
<td style="padding:4px" height="1">
28
</td>
<td style="padding:4px" height="1">
Send escrow
</td>
</tr>
<tr class="odd">
<td style="padding:4px" align="left" height="1">
Gender:
</td>
<td style="padding:4px" height="1">
Male
</td>
<td style="padding:4px" height="1">
Kill search
</td>
</tr>
<tr>
<td style="padding:4px" align="left" height="1">
Last Active:
</td>
<td style="padding:4px" height="1">
Just now
</td>
<td style="padding:4px" height="1">
Compare
</td>
</tr>
<tr class="odd">
<td style="padding:4px" align="left" height="1">
Date Joined:
</td>
<td style="padding:4px" height="1">
2015-12-16
</td>
<td style="padding:4px" height="1">
!--overlord2.php?id=lookup&prefill=JohnRandall-->
</td>
</tr>
<tr>
<td style="padding:4px" align="left" height="1">
Messages:
</td>
<td style="padding:4px" height="1">
2
</td>
<td style="padding:4px" height="1">
</td>
</tr>
<tr>
<td class="backdrop" style="padding: 4px;" colspan="3" height="1">
<img src="//caviar.dtmcdn.com/render/45865/12"> Edit my profile<p class="royal">Player quote</p>
</td>
</tr>
<tr>
<td colspan="3" valign="top" style="background-color:#2a2a2a !important;padding: 0 !important;">
<div style="width:480px; overflow:hidden;">
92
</div>
</td>
</tr>
Step 1 : the target datastructure :
There are two issues with your data structure :
You're forgetting to put the names between quotes. John should be "John". Mary should be "Mary". etc.
You're trying to use an object for [ "John", "Mary" ] and [ "Paul", "Peter" ], where you should be using an array.
So, the data structure you're looking for, is this :
{
31 : [ "John", "Mary" ],
24 : [ "Paul", "Peter" ]
}
Step 2 : fetching the data from the HTML input :
I suggest you make this small adjustment to your JavaScript code :
var source = [];
$('span.members a').each(function () {
$.ajax({
url: $(this).attr('href'),
success: function (result) {
source.push({
name : $(result).find('tr td:contains("Username:")').next().text().trim(),
age : $(result).find('tr td:contains("Age:")').next().text().trim()
});
}
});
});
(see also this Fiddle)
This fetches the data from your HTML input and puts it into a data structure that looks like this :
var source = [{
name : "Paul",
age : 24
}, {
name : "Mary",
age : 31
}, {
name : "Peter",
age : 24
}, {
name : "John",
age : 31
}];
Step 3 : converting to the right data structure :
Once you fetched all the data, you only need to convert your data from the source data structure to the target data structure, which is as simple as this :
var convert = function(source) {
var output = {};
for(var i = 0; i < source.length; i++) {
if(output[source[i].age]) {
output[source[i].age].push(source[i].name);
} else {
output[source[i].age] = [source[i].name];
}
}
return output;
}
(see also this Fiddle)
Putting the pieces of the puzzle together :
You have to wait with executing your convert function until all of your Ajax calls have finished.
For example, you could do something like ...
if (source.length === numberOfMembers) {
target = convert(source);
}
... right behind the source.push(...) statement.
So if you put all the pieces of the puzzle together, you should get something like this :
var source = [];
var target;
var $members = $('span.members a');
var numberOfMembers = $members.size();
var convert = function(source) {
var output = {};
for(var i = 0; i < source.length; i++) {
if(output[source[i].age]) {
output[source[i].age].push(source[i].name);
} else {
output[source[i].age] = [source[i].name];
}
}
return output;
}
$members.each(function () {
$.ajax({
url: $(this).attr('href'),
success: function (result) {
source.push({
name : $(result).find('tr td:contains("Username:")').next().text().trim(),
age : $(result).find('tr td:contains("Age:")').next().text().trim()
});
if (source.length === numberOfMembers) {
target = convert(source);
}
}
});
});
This should give you some idea of what to do:
abcArr = [["Paul", 24], ["Mary", 31], ["Peter",24],["John",31]];
var items = {}, base, key;
$.each(abcArr, function(index, val) {
key = val[1];
users = [];
if (items[key]) {
items[key].push(val[0]);
}
else {
users.push(val[0])
items[key] = users;
}
});
var outputArr = [];
$.each(items, function(key, val) {
outputArr.push([key, val]);
});
// outputArr contains the result
document.body.innerHTML = JSON.stringify(outputArr);
https://jsfiddle.net/rennomarcus/7Lvy0w1t/
I got the idea from this topic: jquery array group by

Tablesorter with ajax refresh not working with more than one

I'm using jQueryUI tabs that has a table on each page. The tables are sorted by Tablesorter 2.0.
The following code works great when I have a single table undergoing a refresh on a page. If I add a second table w/ a refresh, only the first one updates. Can someone tell me how I can get two tables to be sorted by tablesorter with ajax refreshes of the data?
The reload is run through this JS function:
$(function () {
$(".tsRefresh").tablesorter({
headers: {
'.cbsort': { sorter: 'checkbox' },
'.nosort': { sorter: false, parser: false }
},
theme : 'jui',
headerTemplate : '{content} {icon}',
widgets : ['saveSort', 'uitheme'],
widgetOptions : {
zebra : ["odd", "even"]
}
});
function getBjson() {
var Tid = $('.tsRefresh').data('id');
var Ttable = $('.tsRefresh').data('table');
var Tbody = $('.tsRefresh').find('tbody').attr('id')
$.ajax({
type: "POST",
url: "ajax.php",
data: 'table=' + Ttable +'&id=' + Tid,
success: function(output) {
document.getElementById(Tbody).innerHTML = output;
// update tablesorter cache
$(".tsRefresh").trigger("update");
},
error: function (xhr, ajaxOptions, thrownError) {
$('#messageResponse').fadeIn(500);
$('#messageResponse').addClass('ui-state-error ui-corner-all').removeClass('ui-highlight-error');
$('#messageResponse').text(xhr.status + ' ' + thrownError + ': Something went wrong - check your inputs and try again.');
}
});
}
if( $('.tsRefresh').length) {
var Ttime = $('.tsRefresh').data('time');
var timer = setInterval(getBjson, Ttime);
getBjson();
}
});
The following is the table code:
<div id="tabs-1">
<fieldset>
<table width="100%" id="issue" name="issue" class="tsRefresh" data-id="<?=$item_id?>" data-table="eq-load" data-time="10000">
<thead>
<tr class="bold">
<th class="cbsort"><input type="checkbox" class="checkall"> </th>
<th>OAN/ID</th>
<th>Category</th>
<th>Desc</th>
<th>Issued To</th>
<th>SN</th>
</tr>
</thead>
<tbody id="container1">
</tbody>
</table>
</fieldset>
</div>
<div id="tabs-2">
<fieldset>
<table width="100%" id="my-load" name="my-load" class="tsRefresh" data-id="<?=$item_id?>" data-table="eq-load-me" data-time="10000">
<thead>
<tr class="bold">
<th class="cbsort"><input type="checkbox" class="checkall"> </th>
<th>OAN/ID</th>
<th>Category</th>
<th>Desc</th>
<th>Issued To</th>
<th>SN</th>
</tr>
</thead>
<tbody id="container2">
</tbody>
</table>
</fieldset>
</div>
My PHP script (ajax.php) outputs the following to the tablesorter's table:
<tr class="dialog-hover" data-table="eq-load-item" data-id="<?=$item_id?>">
<td align="center"><input type="checkbox" id="row-<?=$item_id?>" value="<?=$item_id?>"></td>
<td align="center" valign="top"><?=$item_oan?>-<?=$item_id?></td>
<td><?=$item_cat?></td>
<td align="center" valign="top"><?=$item_desc?></td>
<td align="center" valign="top"><?=$issue_name?></td>
<td align="center" valign="top"><?=$item_serial?></td>
</tr>

$.ajax not working in chrome and firefox but is working in IE

I have the following code. It works fine in IE but not in Chrome and Firefox. There is no error displayed. It just doesn't get the value entered. Can someone help me fix the problem. Thanks in advance.
File 'main.php'
---------------
<tr>
<td width="11%" class="style171"></td>
<td width="55%" bgcolor="#A8D3FF" class="style171"><strong>APPROVE</strong></td>
<td width="16%" bgcolor="#A8D3FF" align="center"><input type="radio" name="approve" id="approve" value="1" <?php if ($approve== '1') echo "checked"; ?> /></td>
<td width="18%"></td>
</tr>
<tr>
<td width="11%" class="style171"></td>
<td class="style171" bgcolor="#A8D3FF"><strong>NOT APPROVE</strong></td>
<td bgcolor="#A8D3FF" align="center"><input type="radio" name="approve" id="approve" value="2" onClick="processForm()" <?php if ($approve== '2') echo "checked"; ?> /></td>
<td width="18%"></td>
</tr>
<tr>
<td width="11%" class="style171"></td>
<td colspan="2" align="left"><div id="div_data"></div></td>
<td width="18%"></td>
</tr>
<script type="text/javascript">
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: "value="+val,
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
File 'not_approved.php'
-----------------------
<form id="formt" name="formt" method="post" action="">
<table width="100%" border="0" align="left" cellpadding="1" cellspacing="0" bgcolor="#D8EEFE">
<tbody>
<tr>
<td colspan="3"><table width="100%" border="1" bordercolor="#33CCFF" cellspacing="0" cellpadding="1">
<tbody>
<tr class="style2">
<td align="left"><font color="#FF0000">*</font> Enter your comments here.
<table width="430" border="0">
<tr class="style2">
<td width="10" align="left" valign="top"></td>
<td width="410" colspan="2" align="left" valign="top"><textarea name="comment" id="comment" cols="45" rows="5"><?php echo $comment; ?></textarea></td>
</tr>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
</form>
Try this
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: {value:val},
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
** The data filed is changed **
You are passing data in wrong way do as below
data: "{'value':"+val+"}",
and if the value is in string then
data: "{'value':'"+val+"'}",
or
data: JSON.stringify({value:val})
Your data variable must not be in string format because its a variable name. You should do it like this:
<script type="text/javascript">
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: {
value: val,
}
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
Here your script variable val value assigned to value variable and for assigning we use colon here ':' instead of = in AJAX. In server side the catching variable must also be of same name i.e value.

How would I update table data in HTML from my Ajax call json response?

I initially display a table which has data sent from my controller.
I then make an ajax call which returns json data to update the table every minute with the new data. Currently it only updates the first row, with the last item in the json array returned by the ajax call.
I tried unique ID's for the table row but that did not work so I am confused
Here is my Code :
<script type="text/javascript">
var update_data = function() {
var data = {};
$.ajax({
url: '/Update',
dataType: 'json',
async: false,
success: function(data) {
console.log('success' + data.date );
for(var i=0; i<data.ticker.length;i++){
$("#ticker").html("<a href='/ticker?ticker="+data.ticker[i].ticker+"'>"+data.ticker[i].ticker+"</a>");
$("#totalCount").html(data.ticker[i].total_count);
$("#positiveCount").html(data.ticker[i].positive_count);
$("#negativeCount").html(data.ticker[i].negative_count);
$("#neutralCount").html(data.ticker[i].neutral_count);
$("#avgTotalCount").html(data.ticker[i].avg_total);
$("#avgPositiveCount").html(data.ticker[i].avg_positive);
$("#avgNegativeCount").html(data.ticker[i].avg_negative);
$("#avgNeutralCount").html(data.ticker[i].avg_neutral);
}
},
error: function(data) {
console.log('failure' + msg );
//need to traverse to success and if false, do something
}
});
//your jQuery ajax code
};
var interval = 1000 * 60 * .1; // where X is your every X minutes
setInterval(update_data, interval);
update_data();
</script>
<table class="table table-striped sortable" style="width: 60%; float:left;">
<td class="active countBoxHourTitle">Ticker</td>
<td class="active countBoxTitle">Total</td>
<td class="active countBoxTitle">Positive</td>
<td class="active countBoxTitle">Negative</td>
<td class="active countBoxTitle">Neutral</td>
<td class="active countBoxTitle">Avg. Total</td>
<td class="active countBoxTitle">Avg. Positive</td>
<td class="active countBoxTitle">Avg. Negative</td>
<td class="active countBoxTitle">Avg. Neutral</td>
<%var i=0%>
<% _.each(ticker, function (Tickerboard){ %>
<tr>
<%
var total_change = Math.round(((ticker[i].total_count - ticker[i].yes_total)/ticker[i].yes_total)*100)
var pos_change = Math.round(((ticker[i].positive_count - ticker[i].yes_pos)/ticker[i].yes_pos)*100)
var neg_change = Math.round(((ticker[i].negative_count - ticker[i].yes_neg)/ticker[i].yes_neg)*100)
var neut_change = Math.round(((ticker[i].neutral_count - ticker[i].yes_neut)/ticker[i].yes_neut)*100)
%>
<td class="active countBoxHour" id="ticker"><%=ticker[i].ticker%></td>
<td class="success countBox" id="totalCount"><%=ticker[i].total_count%> (<%=total_change%>%)</td>
<td class="success countBox" id="positiveCount"><%=ticker[i].positive_count%> (<%=pos_change%>%)</td>
<td class="danger countBox" id="negativeCount"><%=ticker[i].negative_count%> (<%=neg_change%>%)</td>
<td class="success countBox" id="neutralCount"><%=ticker[i].neutral_count%> (<%=neut_change%>%)</td>
<td class="success countBox" id="avgTotalCount"><%=ticker[i].avg_total%></td>
<td class="success countBox" id="avgPositiveCount"><%=ticker[i].avg_positive%></td>
<td class="danger countBox" id="avgNegativeCount"><%=ticker[i].avg_negative%></td>
<td class="success countBox" id="avgNeutralCount"><%=ticker[i].avg_neutral%></td>
</tr>
<%i++%>
<%})%>
</table>
How can i do this ?
You need to use class in place of id as id must be unique like,
<td class="active countBoxHour ticker">...</td>
<td class="success countBox totalCount">...</td>
<td class="success countBox positiveCount">...</td>
<td class="danger countBox negativeCount">...</td>
<td class="success countBox neutralCount">...</td>
<td class="success countBox avgTotalCount">...</td>
<td class="success countBox avgPositiveCount">...</td>
<td class="danger countBox avgNegativeCount">...</td>
<td class="success countBox avgNeutralCount">...</td>
And change your loop like,
for(var i=0,len=data.ticker.length; i<len;i++){
$(".ticker:eq("+i+")").html("<a href='/ticker?ticker="+data.ticker[i].ticker+"'>"+data.ticker[i].ticker+"</a>");
$(".totalCount:eq("+i+")").html(data.ticker[i].total_count);
$(".positiveCount:eq("+i+")").html(data.ticker[i].positive_count);
$(".negativeCount:eq("+i+")").html(data.ticker[i].negative_count);
$(".neutralCount:eq("+i+")").html(data.ticker[i].neutral_count);
$(".avgTotalCount:eq("+i+")").html(data.ticker[i].avg_total);
$(".avgPositiveCount:eq("+i+")").html(data.ticker[i].avg_positive);
$(".avgNegativeCount:eq("+i+")").html(data.ticker[i].avg_negative);
$(".avgNeutralCount:eq("+i+")").html(data.ticker[i].avg_neutral);
}
Only the last entry is going to be shown, because html() overwrites whatever content was in there. You need to do something more like $("#totalCount").html(data.ticker[i].total_count + $("#totalCount").html()); to append the old HTML at the end.
EDIT: Even better to use dreamweiver's suggestion: $("#totalCount").append(data.ticker[i].total_count);

Autocomplete extender for multiple textbox using Javascript

I want to apply one autocomplete extender for multiple textbox having same name attribute, For eg.
I just want to apply same autocomplete extender to all having name="txtQtyPkgs". How I can do this?
My html
<table cellspacing="0" cellpadding="0" border="0" style="" id="flex1">
<tbody>
<tr id="rowGH03013">
<td align="Left" class="sorted">
<div style="text-align: left; width: 150px;">
GH03013</div>
</td>
<td align="Left">
<div style="text-align: left; width: 150px;">
999</div>
</td>
<td align="Left">
<div style="text-align: left; width: 161px;">
<input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
id="QtyPkgs19523"></div>
</td>
<td align="Left">
<div style="text-align: left; width: 446px;">
<input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
id="Buyer19523"></div>
</td>
</tr>
<tr class="erow" id="rowGH03011">
<td align="Left" class="sorted">
<div style="text-align: left; width: 150px;">
GH03011</div>
</td>
<td align="Left">
<div style="text-align: left; width: 150px;">
999</div>
</td>
<td align="Left">
<div style="text-align: left; width: 161px;">
<input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
id="QtyPkgs19521"></div>
</td>
<td align="Left">
<div style="text-align: left; width: 446px;">
<input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
id="Buyer19521"></div>
</td>
</tr>
</tbody>
</table>
my xml data
<table>
<userid>23</userid>
<userdispname>GUJARAT PACKERS LTD</userdispname>
<usercode>GTPL</usercode>
</table>
<table>
<userid>26</userid>
<userdispname>Lipton India Limited</userdispname>
<usercode>Lipton</usercode>
</table>
<table>
<userid>27</userid>
<userdispname>TOSH LTD.</userdispname>
<usercode>ATosh</usercode>
</table>
<table>
<userid>28</userid>
<userdispname>SERVICES INDIA PVT. LTD.</userdispname>
<usercode>TSI</usercode>
</table>
<table>
<userid>29</userid>
<userdispname>Parekh Company</userdispname>
<usercode>Parekh</usercode>
</table>
<table>
<userid>30</userid>
<userdispname>SHREE BALAJI CO.</userdispname>
<usercode>Balaji</usercode>
</table>
<table>
<userid>31</userid>
<userdispname>Kesaria Company</userdispname>
<usercode>Kesaria</usercode>
</table>
my javascript
$(document).ready(function () {
AuctoCmplBuyer();
$(".auto").autocomplete({ source: [AuctoCmpData] });
});
function AuctoCmplBuyer() {
$.ajax({
type: "POST",
url: "../service/WebService.asmx/XmlData",
data: "{strData:'BuyerList'}",
contentType: "application/json; charset=UTF-8",
dataType: "xml",
success: function (msg) {
$(msg).find('Table').each(function () {
if (StrData.length != 0) {
StrData = StrData + ",";
}
StrData = '{"id":"' + $(this).find('UserID').text() + '","label":"' + $(this).find('UserDispName').text() + '","value":"' + $(this).find('UserDispName').text() + '"}';
});
}
});
AuctoCmpData = StrData;
}
Please put a common class name for all your textbox and using jQuery autocomplete you can do it.
$(".auto").autocomplete({
source: "../Ajax/AjaxGetData.ashx,
minLength: 2,
select: function(event, ui) {
$(this).val(ui.item.value);
}
});
Please refer for more.
http://jqueryui.com/demos/autocomplete/#remote
What I am doing is to make a class called auto and assign it to all of the text box. so when ever the user enters the value it will be going to the handler page (asp.net) or u can use a .php page. In that handler page I am selecting data from database using the like operator of Sql.After selecting the values just Response.Write() (in asp.net) or echo(in php please refer) to send the data.The data is send in the JSON format
[ { "id":"XYZ" , "label":"XYZ" , "value": "XYZ"}]
The above is the format of JSON
For all auto suggest you might have a lot of data.To do so you have to get the total number of results returned after the execution of the query and make a loop.Initialize a string variable with the default value as "[" to the start and append the string with {"id":"Data","label:Data","value":"data"}(this constitutes a JSON object).If it is having more than you just add a , and do looping at the end add "]" to string.
So ur array will be in the format of
[ { "id":"XYZ1" , "label":"XYZ1" , "value": "XYZ1"}, { "id":"XYZ2" , "label":"XYZ2" , "value": "XYZ2"}]
The [' denotes the starting of array and ']' denotes the end
The{` denotes the starting of object and '}' denotes the end
Pls refer JSON to know more
$(document).ready(function () {
AuctoCmplBuyer();
Auctocomplete functionality to each textbox
$(".auto").autocomplete({ source: AuctoCmpData });
});
function AuctoCmplBuyer() {
$.ajax({
type: "POST",
url: "../service/TWWebService.asmx/XmlData",
data: "{strData:'BuyerList'}",
contentType: "application/json; charset=UTF-8",
dataType: "xml",
success: function (msg) {
$(msg).find('Table').each(function () {
rowObj = new Object();
rowObj.col1 = $(this).find('UserDispName').text() + '-' + $(this).find('UserID').text();
AuctoCmpData.push(rowObj);
});
}
});
}
i am doing in this way ...i am not getting the way you said "harie"

Categories

Resources