ADD #url.action with parameter on Table cell in AJAX - javascript

I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:
$.ajax({
url: "GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (obj) {
debugger;
$tbl.empty();
$tbl.append('<tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
for (var i = 0; i < obj.length; i++) {
$tbl.append(' <tr><td> ' + obj[i].senderId + '</td><td>' + obj[i].subject + '</td><td>' + obj[i].msg + '</td><td>TESTING</td></tr>');
}
}
});
Now instead of <a href="#"> I want to add Action Method #URL.Action on that <td>. Here's my Action Method:
<a href=#Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+',receiverId='+obj[i].senderId+ })>
But it shows error, I can't use javascript variable obj[i].senderId with c# code #Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?

David is right, but a simplified way for easy understanding.
var href = #Url.Action("SingleSentShow","Home", new { msgId ="__msgID__" ,receiverId="__receiverID__" });
href = href.replace("__mgsID__",obj[i].senderId).replace("__receiverID__",obj[i].senderId);
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');
Both will work fine.
Update: As per Comment.
Move the value of href to data-href and set href to # and add a new class for script to work. And when the link is clicked we can swap the values.
$tbl.append(' <tr><td> <a href=# class=Test data-href="' + href + '">' + '... the rest of your line');
And add the below script.
$(document).on('click', '.Test', function () {
$(this).attr('href',$(this).attr('data-href'));
});

You can't mix server-side code and client-side code like that.
One option might be to put the base action URL in a JavaScript variable, and then append your query string parameters to it in JavaScript code. Something like this:
var singleSentShowURL = '#Url.Action("SingleSentShow","Home")';
This would result in something like this client-side:
var singleSentShowURL = '/Home/SingleSentShow';
Then in your loop you could use that variable to manually build the URL. Something like this:
$tbl.append(' <tr><td> <a href="' + singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId + '">' + '... the rest of your line');
You might split it into multiple lines for readability:
var href = singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId;
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');

Related

hyperlink on update button (ajax json)

It's my first time using json and I'm trying to make an update button on a table that i make with ajax json, there is a problem that i can't put id_news attribute on the tag along with the target link. I tried put it next to the target link, but it doesn't work, and even the tables doesn't show anything, is there any way to make it work?
$(document).ready(function() {
display_data_info();
function display_data_info() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url()?>/information/data_read_info',
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
var no;
var id_news;
for (i = 0; i < data.length; i++) {
no = +1;
html += '<tr>' +
'<td>' +
no +
'</td>' +
'<td>' +
data[i].news_title +
'</td>' +
'<td>' +
data[i].news_info +
'</td>' +
'<td>' +
data[i].news_status +
'</td>' +
'<td><a href="<?php echo site_url("information/display_update_info/".data[i].id_news); ?>" class="btn btn-app">' +
'<i class="fas fa-edit"></i> ' +
'</a>' +
'</td>' +
'</tr>';
}
$('#show_data_info').html(html);
}
});
}
});
[wanted to post just a comment, but haven't enough reputation yet. Perhaps a moderator can change my feedback into a comment?]
I see multiple typos and mistakes here:
In the first php part, put a ; after base_url()
You are not initializing no before you do no += 1
Instead of no += 1 you do no = +1 (which may accidentally overcome the previous error but it's probably not what you want)
In the <td><a href=.... line you are mixing up single and double quotes
In that same line, your javascript variable is inside PHP. data[i].id_news does not exist in PHP scope.
Check your web console and PHP error log, there will be several errors.

I passed product name in onclick() function using jquery? but error

output += '<td class="cart-product-edit"><i class="fa fa-plus"></i></td>';
function SaveCart(cartid) {
var URL = "<?php echo site_url();?>";
var userid = "<?php echo $this->session->userdata('userid');?>"
var data = {
userid: userid
};
$.ajax({
url: URL + 'cart/SaveCart/' + cartid,
data: data,
type: 'POST',
dataType: 'json',
success: function(result) {}
});
}
Error:(console) (bag is productname)
cart:1 Uncaught ReferenceError: bag is not defined
at HTMLAnchorElement.onclick (cart:1)
There are two problems. The first is with this line:
onclick="SaveCart(' + element.CardID + ',' + element.ProductName + ')"
Your element.ProductName is presumably a string (named, in this case Bag) and that is causing your error.
You need to surround the string elements of your onclick with quotes:
onclick="SaveCart(' + element.CardID + ', \'' + element.ProductName + '\')"
The second issue is that SaveCart is defined with only a single parameter:
function SaveCart(cartid) {
You are actually passing two parameters to it, the CardID and the ProductName.
Maybe you don't need to pass the product name at all, in which case your onclick becomes:
onclick="SaveCart(' + element.CardID + ')"
Or you need to add the second parameter to SaveCart:
function SaveCart(cartid, productName) {
From the error message it appears that the issue is because element.CardID and element.ProductName are strings, yet you have not wrapped them in quotes in the HTML output. You need to escape the quotes you wrap them in so that they don't break the syntax:
output += '<td ... onclick="SaveCart(\'' + element.CardID + '\',\'' + element.ProductName + '\')" ... </td>';
You also need to amend SaveCart to accept both arguments:
function SaveCart(cartid, productname) {
// your logic here...
}
However a much better approach would be to get rid of the outdated on* event attributes and to attach your events unobtrusively. Then you can use data attributes to store the metadata in the element. Given you're already using jQuery, it can be done like this:
var element = {
CardID: 'abc123',
ProductName: 'Lorem ipsum'
}
let output = `<td class="cart-product-edit"><i class="fa fa-plus">Click me</i></td>`;
$('table tr').append(output);
$('table').on('click', '.product-edit', function() {
let $a = $(this);
let cardId = $a.data('cardid');
let productName = $a.data('productname');
console.log(cardId, productName);
// send your AJAX here...
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table><tr></tr></table>

How to pass/generate table with parameters from one page to another

Hi i having a scenario where i am generating a dynamic table along with the dynamic button and when ever user clicks that button it has to get that row value and it has generate another dynamic table by taking this value as parameter .Till now i tried generating a dynamic table and with button and passed a parameter to that function here i stuck how to pass /accept a parameter to that function so that by using ajax call it can generate another dynamic table.
$.ajax({
type: 'GET',
url: xxxx.xxxxx.xxxxx,
data: "Id=" + clO + Name_=" + cl+ "",
success: function (resp) {
var Location = resp;
var tr;
for (var i = 0; i < Location.length; i++) {
tr = tr + "<tr>
tr = tr + "<td style='height:20px' align='right'>" + Location[i].Amount + "</td>";
tr = tr + "<td style='height:20px' align='right'>" + Location[i].Name + "</td>";
tr = tr + '<td><input type="button" class="nav_button" onclick="test(\'' + Location[i].Amount + '\',\'' + Location[i].Name + '\')"></td>';
tr = tr + "</tr>";
};
document.getElementById('d').style.display = "block";
document.getElementById('Wise').innerHTML = "<table id='rt'>" + "<thead ><tr><th style='height:20px'>Amount</th>" + "<th style='height:20px'>Name</th>""</tr></thead>"
+ tr + "<tr><td align='left' style='height:20px'><b>Total:"+ TotBills +"</b></td><td style='height:20px' align='right'><b></b></td></tr>" +
"</table>";
document.getElementById('Wise').childNodes[0].nodeValue = null;
},
error: function (e) {
window.plugins.toast.showLongBottom("error");
}
function test(value,val1,val2) {
navigator.notification.alert(value + ";" + val1 + ";" + val2);
// here i have to pass the another ajax by basing on the the onclick
}
so here in the function i have to pass the parameters and have to display in the new page and how is it possible ?
To pass data from a page to another your best bet is localStorage and SessionStorage;
SessionStorage - Similar to a cookie that expires when you close the browser. It has the same structure as the localStorage, but there is no way to change its permanence time, whenever closing will be deleted.
LocalStorage - This is similar to a cookie, but it never expires, so while there were records in the AppCache for that domain, the variable will exist (unless the user creates a routine to remove it).
Both attributes were added by HTML5. The above items called web storage. But there are other forms of local storage through HTML5, such as WebSQL database, Indexed Database (IndexDB), as well as conventional files (File Access).
Ex:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Is it what you meant ?
It's unclear what you're after, but I think I see where you're headed. From the code you included, it seems like you want something like this instead:
// This will take the user to a separate page, passing your parameters
function test(val1,val2) {
window.location.href("/UrlGoesHere?Amount=" + val1 + "&Name=" + val2);
}
Another option, based on what you've said, is to redraw the table. You could do that with something like this:
function test(val1,val2) {
$.ajax({
type: 'GET',
url: "/UrlGoesHere",
data: "Amount=" + val1 + "&Name=" + val2,
success: function (resp) {
// redraw table here
}
});
}

How to encode the url from ajax return data then append to html?

$.ajax({
url: "get_title_list.php", //server API name
type: 'POST',
dataType: 'json',
data: {id: id},
async: true,
cache: false,
success: function(response) {
if(response.length!=0)
{
$("#faq").html('');
var html = '';
$.each(response, function(index, array) {
// fi_title:標題文字, fi_content:內容文字
html+='<div class="content">'
+'<table width="100%" border="0">'
+'<tr>'
+'<td style="width:50px;vertical-align:top;"><img src="answer_icon.jpg" style="width:20px;" /></td>'
+'<td style="text-align:left;">'+ array['fi_content'] +'</td>'
+'</tr>'
+'</table>'
+'</div>';
});
$("#faq").append(html);
}
},
});
I will have content in "array['fi_content'] and in this content may have some string and with a url like below.
" Welcome to my website.Visit link. http://www.mypage.com "
In google debug mode, it will look like
<p>
Welcome to my website.Visit link.
<a target="_blank" href="http://www.mypage.com">http://www.mypage.com</a>
</p>
My question is how to encode the url before append to html?
Can I use get url by href attribute and change it then append it with string ?
If you want to make some changes to the href attribute, the easiest way would be parsing it as HTML and then change the DOM. Since you are using jQuery, you can also use its parsing.
var content = $(array['fi_content']); // parses HTML as jQuery object.
content.find("a").each(function (_, link) {
var href = link.getAttribute("href"); // Do not use .href as it contains parsed absolute URL instead.
// Do any encoding you like to href here.
link.href = href; // Set the href back to element.
});
var processedContentHtml = content.html();
// You can now concat processedContentHtml into your string.
// Ex: +'<td style="text-align:left;">'+ processedContentHtml +'</td>'
Replace array['fi_content'] to this:
array[ 'fi_content' ].replace( /<a(\s[^>]*\s|\s)href=[\"\']([^\"\']*)[\"\']([^>]*)>/ig, function( s1, url, s2 ) {
return '<a' + s1 + 'href="' + encode( url ) + '"' + s2 + '>';
} );
I don't have any idea what mean saying encode so I just pass url to function encode which you should implement by yourself.

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Categories

Resources