passing variable value to href argument - javascript

I'm sure this is an easy one but I'm really stuck here..
This is the code
<td id="id"></td>
<td id="sku"></td>
<td id="name"></td>
<td id="type"></td>
<td id="price"></td>
<td id="shipping"></td>
<td id="description"></td>
<td id="image"></td>
<td>
<a href="/update-user?id=" </a>
</td>
<td>
<a class="btn border delete" data-id= > </a>
</td>
I need to pass the value that's gonna be in the id="id" to the href id and data-id
The table is populated by this function here
var i = 0;
function next(){
i++;
var value = $.ajax({
type: "get",
url: "http://localhost:3000/api/users",
dataType: 'json'
}).done(function (users) {
console.log(users[i]);
$('#id').text(users[i]._id)
$('#sku').text(users[i].sku)
$('#name').text(users[i].name)
$('#type').text(users[i].type)
$('#price').text(users[i].price)
$('#shipping').text(users[i].shipping)
$('#description').text(users[i].description)
$('#image').html("<img src='"+users[i].image+"'/>")
});
return value.responseJSON;
}
Many thanks everyone!

Is this what u mean? 🕶
Only when there is 1 link on the page this will work, would advice you to use a class or id for the targeting. Like the way we did for .delete. Else every a href will be changed.
var i = 0;
function next(){
i++;
var value = $.ajax({
type: "get",
url: "http://localhost:3000/api/users",
dataType: 'json'
}).done(function (users) {
console.log(users[i]);
var uID = users[i]._id;
$('#id').text(users[i]._id)
$('#sku').text(users[i].sku)
$('#name').text(users[i].name)
$('#type').text(users[i].type)
$('#price').text(users[i].price)
$('#shipping').text(users[i].shipping)
$('#description').text(users[i].description)
$('#image').html("<img src='"+users[i].image+"'/>")
$('a').attr("href", "/update-user?id="+uID)
$('.delete').attr('data-id', uID)
});
return value.responseJSON;
}
<td id="id"></td>
<td id="sku"></td>
<td id="name"></td>
<td id="type"></td>
<td id="price"></td>
<td id="shipping"></td>
<td id="description"></td>
<td id="image"></td>
<td>
<a href="/update-user?id=" </a>
</td>
<td>
<a class="btn border delete" data-id= > </a>
</td>

Give the anchor a class.
<td>
<a class="link" href="/update-user?id=" </a>
</td>
then you can access it and updates its href
`$("#table tr").eq(i).find(".link").attr('href', '/update-user?id=' + users[i]._id);
You can do similarly with the data-id attribute of the delete button.

Related

Get <td> value from its button using php and html

If I have this:
<td name="id1">First</td> <button>btn1</button>
<td name="id2">Second</td> <button>btn2</button>
<td name="id3">Third</td> <button>btn3</button>
<td name="id4">Fourth</td> <button>btn4</button>
I want if I click (btn1) the form send to my controller and then I can have (id2)
the ids generated by database so I don't know what is the number, how can I get the number by clicking the same side button?
Instead of using name, use ID
<td id="id1">First</td> <button>btn1</button>
<td id="id2">Second</td> <button>btn2</button>
<td id="id3">Third</td> <button>btn3</button>
<td id="id4">Fourth</td> <button>btn4</button>
Then use JavaScript like so:
document.getElementById('id1').innerHTML; // this is the value
or
document.getElementById('id1').id; // this is the value
or
document.getElementById('id1').value; // this is the value
To make the button work:
<td id="id1">First</td> <button id='btn1' onclick="handleButton(this);">btn1</button>
<td id="id2">Second</td> <button id='btn2'onclick="handleButton(this);">btn2</button>
<td id="id3">Third</td> <button id='btn3'onclick="handleButton(this);">btn3</button>
<td id="id4">Fourth</td> <button id='btn4'onclick="handleButton(this);">btn4</button>
The JavaScript function:
function handleButton(obj) {
alert('You clicked: ' + obj.id);
}

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

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();

$.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);

AJAX: add new row to table or remove using AJAX

This is the logic:
I input something to form, and the form is AJAX live search. after I found value, I click on add button and it creates new row in existing table / tbody.
<table class="standard">
<thead>
<tr>
<td colspan="2">
Start Input barcode / Product Name
</td>
<td colspan="4">
<input type="text" size="90" value="" placeholder="Barcode / Product Name">
</td>
<td>
<button class="tambah"><i class="icon-plus"></i> Add</button>
</td>
</tr>
<tr>
<td>
No.
</td>
<td>
Kode Barang
</td>
<td>
Nama Barang
</td>
<td>
Qty
</td>
<td>
Harga
</td>
<td>
Disc %
</td>
<td>
Total
</td>
</tr>
</thead>
<tbody>
<!-- when button add is click that will add <tr></tr> here -->
</tbody>
</table>
can i do that? if so, how?
Fiddle Example: http://jsfiddle.net/anggagewor/cauPH/
You can find the pseudo code below.
$('#button_id').on('click', function(e) {
$.ajax({
url : yourUrl,
type : 'GET',
dataType : 'json',
success : function(data) {
$('#table_id tbody').append("<tr><td>" + data.column1 + "</td><td>" + data.column2 + "</td><td>" + data.column3 + "</td></tr>");
},
error : function() {
console.log('error');
}
});
});
Try this
var scntDiv = $('#p_scents');
var i = $('#p_scents tr').size() + 1;
$('#addScnt').click(function() {
scntDiv.append('<tr><td><select name="type" id="type"><option value="Debit">Debit</option><option value="Credit">Credit</option></select></td><td><select name="accounts" id="accounts"><option value="">SELECT</option><option value="One">One</option><option value="Two">Two</option></select></td><td><input type="text" name="debit_amount" id="debit_amount"/></td><td><input type="text" name="credit_amount" id="credit_amount"/></td><td>Remove</td></tr>');
i++;
return false;
});
//Remove button
$(document).on('click', '#remScnt', function() {
if (i > 2) {
$(this).closest('tr').remove();
i--;
}
return false;
});​
Here's a working example, including remove row functionality: DEMO.
$("<tr><td>.....content...<td><a class='remove'>remove</a>").appendTo("#tableid tbody").find('.remove').click(function () {
$(this).parent().parent().remove();
});
In your ajax response you can do this
$("#myTable > tbody").append('<tr><td>my data</td><td>more data</td></tr>');
'#myTable' will be replaced by your table id or class and <td>my data</td><td>more data</td> will be replaced by your content

Categories

Resources