How to execute JAVA code from JS in JSP - javascript

I'm working with Java Web at Netbeans 8.1, actually I'm working with AJAX in the proyect and this issue stops me:
This is my JS function in JSP:
$("#formAddFundo").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr('action');
var status = 0;
if (document.getElementById("chkFundo").checked)
var status = 1;
/* Send the data using post with element id name and name2*/
var posting = $.post(url, {
hIdFundo: $('#hIdFundo').val(),
txtNombre: $('#txtNombre').val(),
status: status,
btnAddGrid: $('#btnAddGrid').val()
});
/* Alerts the results */
posting.done(function(data) {
$.get('addFundo', function(responseJson) {
var t = $('#dt_basic').DataTable();
t.clear();
$.each(responseJson, function(index, objeto) { // Iterate over the JSON array.
var estado;
if (objeto.status === 1) {
estado = "Activo";
} else {
estado = "No activo";
}
t.row.add([
objeto.idfundo,
objeto.nombre,
estado,
"<i class=\"btn btn-secondary fa fa-pencil\" onclick=\"update('" + objeto.nombre + "', '" + objeto.idfundo + "', '" + objeto.status + "');\"></i></a><a><i class=\"btn btn-secondary fa fa-trash-o\" onclick=\"borrar('" + objeto.nombre + "', '" + objeto.idfundo + "');\"></i></a>"
]).draw(false);
});
$('#alerta').html("<div class='alert alert-warning'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Atención!</strong> " + <%= session.getAttribute("Respuesta") %> +" </strong></div>");
});
limpiar();
});
});
This is my servlet where JS goes to get response:
String json = new Gson().toJson(listaFundos);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
request.getSession().setAttribute("Respuesta", resp);
Now. I need to print a HTML at (#alerta) in JSP without page refresh when POST method ends his function with Json. Session variables and scripplets only executes once at page refresh, not for further executions..
$('#alerta').html("<div class='alert alert-warning'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Atención!</strong> " + <%= session.getAttribute("Respuesta") %> +" </strong></div>");

Related

visual studio with javascript debugging showing different behaviour while running directly and by running in debug mode

in javascript visual studio database programming, i am fashing very unusual behaviour of program execution.
i have javascript code like this:
<script type="text/javascript">
function GetValue6(id1, id2, id3) {
var user = {};
user.Username = $("[id*='" + id1 + "']").val();
user.Password = $("[id*='" + id2 + "']").val();
alert(user.Username);
$.ajax({
type: "POST",
url: '<%= ResolveUrl("Default.aspx/SaveUser") %>',
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
},
error: function () { alert("There was an error."); }
});
return false;
}
</script>
and code behind file like this:
child.Text = "<input type='text' id='" + TextGUID1 + "' value='" + rows[i]
["Area"].ToString() + "'/>
<input type='text' id='" + TextGUID2 + "' value='" + rows[i]
["Area"].ToString() + "'/>
<input type = 'button' id='" + ButtonGUID3 + "' onclick=\"GetValue6('" +
TextGUID1 + "','" + TextGUID2 + "','" + ButtonGUID3 + "')\" value='Save'
/>
public static void SaveUser(User user)
{
string constr =
ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Users2
VALUES(#Username, #Password)"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Username", user.Username);
cmd.Parameters.AddWithValue("#Password", user.Password);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
There is a very strange behaviour that i am facing, when i run above code by clicking "Save" button then i face error alert message "There was an error.". But when i run the program in debugging mode and press F10(Step over new function call) then i get the alert message "User has been added successfully." and user gets insert in the corresponding table. moreover one strange thing is that when e get the error message "There was an error.", even then the corresponding user get inserted into the table successfully.
please guide me where i am wrong and how can i get the username gets inserted with the proper successful message.
When you run the script onclick, also you make and a post back - here, try to return false to avoid the post back - write this
onclick=\"GetValue6(....); return false;\"
or this
onclick=\"return GetValue6(....);\"
because inside the GetValue6 you return false.
And when you make debug, the program waits/hold the post back because of the debug step by step - that's why its success.

Extend Div smoothly without lagging

On button click, I am fetching data from database using codeigniter and a div is being appended with the fetched data. Problem is that while the data is of high volume, it takes time and the webpage is lagging. What should I do to resolve this issue?
My code is given below.
$("#get_spare_list").click(function() {
$("body").css("cursor", "progress");
var ht = "";
$.ajax({
url: "<?php echo base_url('Spare/get_all_spare_json'); ?>",
type: 'POST',
dataType: 'json',
data: {"param1": 'value1'},
})
.done(function(data) {
var no = 1;
var ht = "<table class='table'><thead><tr><th>No</th><th>Name</th><th>Code</th><th>Min qty</th><th>uni</th><th>Group</th><th>Sub Category</th><th>Part Number</th><th>Location</th><th>Image</th><th >Tyre</th><th>Back</th></tr></thead>";
$.each(data, function(key, val) {
ht +="<tr>"+"<td>"+no+"</td>"+"<td>"+val.name+"</td>"+"<td>"+val.code+"</td>"+"<td>"+val.min_qty+"</td>"+"<td>"+val.unit+"</td>"+"<td>"+val.group+"</td><td>"+val.sub_category+"</td><td>"+val.part_number+"</td><td>"+val.location+"</td>";
if (val.image) {
ht += "<td><a target='_blank' href='"+"<?php echo base_url('../uploads/'); ?>/"+val.image+"'><button class='fa fa-picture-o'></button></a></td>";
}else{
ht += "<td></td>";
}
ht +="<td>"+val.tyre+"</td>";
ht += "<td>";
if (val.reusable == 1) {
ht +="yes";
}else{
ht+="no";
};
ht += "</td>";
ht += "<td><button class='btn edit btn-info btn-xs' data-toggle='modal' data-target='#editModel' data-id='"+val.id+"' data-name='"+val.name+"' data-code='"+val.code+"' data-min_qty='"+val.min_qty+"' data-unit='"+val.unit+"' data-group='"+val.group+"' data-sub_category='"+val.sub_category+"' data-part_number='"+val.part_number+"' data-location='"+val.location+"' data-tyre_number='"+val.tyre+"' data-back='"+val.reusable+"'><span class='fa fa-edit'></span></button></td>";
ht += "</tr>";
no++;
});
$("#js_res").append(ht);
$("body").css("cursor", "default");
})
.fail(function() {
alert("error");
$("body").css("cursor", "default");
});
});
jQuery should append data to the div smoothly without lagging and hanging of web page.
When the browser receives a response, the callback function passed to .done() is added to JavaScript's event loop queue.
While the data is being processed, it blocks JavaScript's event loop to process further tasks. Even the stuff like handling mouse input is blocked meanwhile. If the data being processed is too big, this becomes more observable to the end user.
You can divide the data retrieved into chunks and push them to the event loop separately by calling setTimeout() on them. Source: Cooperation part of You Don't Know JS: Async & Performance
Here is how it can work for your code below, the callback function passed to .done() and a helper function:
function(data) {
var ht = "<table class='table'><thead><tr><th>No</th><th>Name</th><th>Code</th><th>Min qty</th><th>uni</th><th>Group</th><th>Sub Category</th><th>Part Number</th><th>Location</th><th>Image</th><th >Tyre</th><th>Back</th></tr></thead>";
$("#js_res").append(ht);
processData(data, 1);
$("body").css("cursor", "default");
}
function processData(data, no) {
var chunk = data.splice(0, 100);
var ht = "";
$.each(chunk, function(key, val) {
ht +="<tr>"+"<td>"+no+"</td>"+"<td>"+val.name+"</td>"+"<td>"+val.code+"</td>"+"<td>"+val.min_qty+"</td>"+"<td>"+val.unit+"</td>"+"<td>"+val.group+"</td><td>"+val.sub_category+"</td><td>"+val.part_number+"</td><td>"+val.location+"</td>";
if (val.image) {
ht += "<td><a target='_blank' href='"+"<?php echo base_url('../uploads/'); ?>/"+val.image+"'><button class='fa fa-picture-o'></button></a></td>";
}else{
ht += "<td></td>";
}
ht +="<td>"+val.tyre+"</td>";
ht += "<td>";
if (val.reusable == 1) {
ht +="yes";
}else{
ht+="no";
};
ht += "</td>";
ht += "<td><button class='btn edit btn-info btn-xs' data-toggle='modal' data-target='#editModel' data-id='"+val.id+"' data-name='"+val.name+"' data-code='"+val.code+"' data-min_qty='"+val.min_qty+"' data-unit='"+val.unit+"' data-group='"+val.group+"' data-sub_category='"+val.sub_category+"' data-part_number='"+val.part_number+"' data-location='"+val.location+"' data-tyre_number='"+val.tyre+"' data-back='"+val.reusable+"'><span class='fa fa-edit'></span></button></td>";
ht += "</tr>";
no++;
});
$("#js_res").append(ht);
if (data.length > 0) {
setTimeout(function(){
processData(data, no);
}, 0);
}
}
Another solution would be to use a web worker for handling the creation of these table rows.
A web worker can't edit the DOM but you can pass the data to the web worker. The worker can then create the html string and pass it back to the main JS thread which can then append it.
var myWorker = new Worker('create-table.js');
// after successful ajax call, hand data over to worker
myWorker.postMessage(data);
console.log('Message posted to worker');
inside the create-table.js we can then specify our worker:
onmessage = function(e) {
console.log('Message received from main script');
/*
This is just an example from mdn documentation
Obviously you should recreate your logic for creating your <tr> here
*/
var workerResult = 'Result: ' + (e.data[0]);
console.log('Posting message back to main script');
postMessage(workerResult);
}
In the main js file you can then react to the result of the worker like this:
myWorker.onmessage = function(e) {
$("#js_res").append(e.data)
console.log('Message received from worker');
}

Fix Youtube api data pagination v3

I got a so far as good working youtube api data v3 search script but i was so in trouble with this script since days i think im blind it works and paginates everytime 2 entries. But there must be a failure in the js or html code should be easy but i cant figure out please help me. Demo Link is aviable under
Artist search Battle Rap Net Youtube Search
This is the Code so far i used please take a look at the demo link to understand the problem.
The Js Code:
var nextPageToken, prevPageToken;
var firstPage=true;
$(document).ready(function()
{
$('#searchbutton').click(function()
{
// Called automatically when JavaScript client library is loaded.
// alert('i am clicked');
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
// Called automatically when YouTube API interface is loaded .
// Called automatically with the response of the YouTube API request.
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page"+nextPageToken+"</button></div>");
});
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page "+prevPageToken+"</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page "+nextPageToken+"</button></div>");
$('#nextPageButton').click(function()
{
// alert('i am clicked');
console.log(nextPageToken);
searchYouTubeApi(nextPageToken);
});
$('#prevPageButton').click(function()
{
// alert('i am clicked');
console.log(prevPageToken);
searchYouTubeApi(prevPageToken);
});
});
function onYouTubeApiLoad()
{
// See to get a key for your own applications.
gapi.client.setApiKey('MYAPICODE');
searchYouTubeApi();
}
function searchYouTubeApi(PageToken)
{
var searchText= $('#searchtext').val();
//$('#response').append("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
$('#response').replaceWith("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
// Use the JavaScript client library to create a search.list() API call to Youtube's "Search" resource
var request = gapi.client.youtube.search.list(
{
part: 'snippet',
q:searchText,
maxResults:2,
pageToken:PageToken
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
// $('#response').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page return from request execute method is: "+nextPageToken+"</button></div>");
}
function onSearchResponse(response)
{
var responseString = JSON.stringify(response, '', 2);
var resultCount = response.pageInfo.totalResults;
nextPageToken=response.nextPageToken;
prevPageToken=response.prevPageToken;
// document.getElementById('response').innerHTML += responseString;
//$('#response').append("<div id=count><b>Found "+resultCount+" Results.</b></div>");
$('#count').replaceWith("<div id=count><b>Found "+resultCount+" Results.</b></div>");
//$('#searching').append("<div id=length><b>Length "+response.items.length+" </b></div>");
for (var i=0; i<response.items.length;i++)
{
//store each JSON value in a variable
var publishedAt=response.items[i].snippet.publishedAt;
var channelId=response.items[i].snippet.channelId;
var title=response.items[i].snippet.title;
var description=response.items[i].snippet.description;
var thumbnails_default=response.items[i].snippet.thumbnails.default.url;
var thumbnails_medium=response.items[i].snippet.thumbnails.medium.url;
var thumbnails_high=response.items[i].snippet.thumbnails.high.url;
var channelTitle=response.items[i].snippet.channelTitle;
var liveBroadcastContent=response.items[i].snippet.liveBroadcastContent;
var videoID=response.items[i].id.videoId;
//var firstPage=true;
// console.log(thumbnails_default);
//A HTTP call to this URL with videoID will give all XML info of that video:
//http://gdata.youtube.com/feeds/api/videos?q=videoID
// console.log(videoID);
//replace the first search button with a 'more' button
//$('button').replaceWith("<button type='button' id=More"+i+">More...</button>");
if(firstPage===true)
{
//print the stored variables in a div element
$('#snipp').append("<div id=T><b>Title:</b> "+title+"</div><div id=C><b>Channel ID: </b>"+channelId+"</div><div id=D><b>Description </b>"+description+"</div><div id=P><b>Published on: </b>"+publishedAt+"</div><div id=CT><b>Channel Title: </b>"+channelTitle+"</div><a id=linktoVid href='http://www.youtube.com/watch?v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
}
else
{
$('#T').replaceWith("<div id=T><b>Title:</b> "+title+"</div>");
$('#C').replaceWith("<div id=C><b>Channel ID: </b>"+channelId+"</div>");
$('#D').replaceWith("<div id=D><b>Description </b>"+description+"</div>");
$('#P').replaceWith("<div id=P><b>Published on: </b>"+publishedAt+"</div>");
$('#CT').replaceWith("<div id=CT><b>Channel Title: </b>"+channelTitle+"</div>");
$('#linktoVid').replaceWith("<a id=linktoVid href='http://www.youtube.com/watch v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
}
// $('#snipp').append("<div id=C"+i+">Channle ID: "+channelId+"</div><br/>");
//link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=76TlUlPZQfQ&feature=youtube_gdata'/>
}
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
// return nextPageToken;
firstPage=false;
}
The HTML:
<body>
<div id="search">
<input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
</pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp">
<div id=T0
</div>
<br/><br/><br/>
</body>
After create a jsfiddle with your code, I could check the pagination is working correctly.
The problem you're facing lies in your HTML code (most specific: in how you're building your HTML code).
My humble advice is that "instead of using append", re-creates the HTML that renders the current page.
Also, just after all controls loaded in the screen, the "prevPageButton" and "nextPageButton" buttons shows undefined.
For this situation, change these lines:
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
For this:
if (prevPageToken == undefined) {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page</button></div>");
} else {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
}
if (nextPageToken == undefined) {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
} else {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
}
After a few modifications, you can check here the updated and working jsfiddle.
The tl;dr version is as follows:
Logic for build the HTML code was replaced for set a variable that (in the for-loop) builds the HTML code.
At the end of the loop, the HTML is added directly to the div container called "snipp".
Removed other HTML unneccesary code.
This is the modified code:
HTML:
<div id="search">
<input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
</pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp"></div>
JS:
function onSearchResponse(response) {
var responseString = JSON.stringify(response, '', 2);
var resultCount = response.pageInfo.totalResults;
nextPageToken = response.nextPageToken;
prevPageToken = response.prevPageToken;
$('#count').replaceWith("<div id=count><b>Found " + resultCount + " Results.</b></div>");
// This variable will save the HTML code in construction.
var HTML_CONTENT = "";
for (var i = 0; i < response.items.length; i++) {
//store each JSON value in a variable
var publishedAt = response.items[i].snippet.publishedAt;
var channelId = response.items[i].snippet.channelId;
var title = response.items[i].snippet.title;
var description = response.items[i].snippet.description;
var thumbnails_default = response.items[i].snippet.thumbnails.default.url;
var thumbnails_medium = response.items[i].snippet.thumbnails.medium.url;
var thumbnails_high = response.items[i].snippet.thumbnails.high.url;
var channelTitle = response.items[i].snippet.channelTitle;
var liveBroadcastContent = response.items[i].snippet.liveBroadcastContent;
var videoID = response.items[i].id.videoId;
// Buld the HTML to render at the current page.
HTML_CONTENT += "<div id='video_item'> " +
" <div id=T><b>Title:</b>" + title + "</div> " +
" <div id=C><b>Channel ID: </b>" + channelId + "</div> " +
" <div id=D><b>Description </b>" + description + "</div> " +
" <div id=P><b>Published on: </b>" + publishedAt + "</div> " +
" <div id=CT><b>Channel Title: </b>" + channelTitle + "</div> " +
" <a id='linktoVid' href='http://www.youtube.com/watch?v=" + videoID + "'><img id='imgTD' src='" + thumbnails_default + "' /></a><br/><br/><a id='linktoVid1' href='http://www.youtube.com/watch?v=" + videoID + "'><video id='vidTD' width=\"320\" height=\"240\" controls poster='" + thumbnails_default + "'><source src='http://www.youtube.com/watch?v=" + videoID + "'>Your browser does not support the video tag.</video></a><br/><br/> " +
"</div>";
}
// Post all HTML generated code (built in the previous for-loop).
document.getElementById('snipp').innerHTML = HTML_CONTENT;
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
// return nextPageToken;
firstPage = false;
}

disappears in page refresh and closing the browser- webstorage

I am using web storage
but when I refresh the page I don't see the submitted values in the browser...
do you know why...
providing my code below
http://codepen.io/anon/pen/mPBQxX
$('.stored').keyup(function() {
localStorage[$(this).attr('name')] = $(this).val();
});
You are clearing LocalStorage after each submission at the end of the onSubmit callback. Maybe clear the form values instead of clearing the Storage.
$('#localStorageTest').submit(function(e) {
e.preventDefault();
var email = $('#email').val();
var name = $('#name').val();
var message = $('#message').val();
var div = "<div><span>" + name + "</span><span >" + email + "</span><span>" + message + "</span><input type='button' value='Edit' name='editHistory'><input type='button' value='Delete' name='deleteHistory'></div>"; //add your data in span, p, input..
//alert(div);
$('.gettingValues').append(div); //apendd the div
$('#localStorageTest')[0].reset(); //clear the form
localStorage.clear(); >>>>>>>>>> RESETTING HERE >>>>>>>>>>>>>>>>>>>>>
});

How to pass a variable in ajax append function (into html element with razor)?

I need to pass the Id of a object into a html element (razor part), but it doesn't recognize it. Look like the Id is not in its scope, or something. Is there a way to pass the value into the razor part of my html element in the append function?
$.ajax({
data: data,
url: url + "?searchTerm=" + data
}).success(function (response) {
console.log(response);
var table = $('#companyTable');
var tBody = table.children('tbody');
tBody.html("");
var textbox = document.getElementById("searchBar");
textbox.value = "";
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\"location.href='#Url.Action("Edit", "Company", new { #id = response.CompanyId })'\"> Edit</button></p>" +
"</td></tr>"
);
table.removeClass("hidden");
var originalTable = $('#originalTable');
originalTable.remove();
}).error(function (response) {
console.log(response);
});
}
Thank you.
I do those things this way:
+ "<p><button onclick=\"location.href='#(Url.Action("Edit", "Company"))?id=" + response.CompanyId + "'\">Edit</button>"
You are totally missing the concept of server-side rendering and browser execution. Consider this example, your server renders your js code, and just leaves all work to browser, then browser stars to execute Ajax request somehow(button click), when Ajax completed - you have a response value, but this value exists only inside browser context, so it doesn't make sense to pass value into razor, as it already done its work while rendering your file
Now, what to do? The simplest solution would be to hardcore Url of company edit by yourself, as razor simply doesn't know anything what's happening client-side, example:
location.href="/company/1/edit" //where 1 is id from Ajax request
The easiest complete solution is
public ActionResult WhateverMethod()
{
// ....
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
response.Url = Url.Action("Edit", "Company", new { #id = response.CompanyId });
// ....
}
And
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>"
+ response.CompanyIdNumber + "</td><td>"
+ response.CompanyTaxNumber + "</td><td>"
+ "<p><button onclick=\"location.href='" + response.Url + "'\"> Edit</button></p>"
+ "</td></tr>");
Calling a Razor methods in JavaScript is going to cause you nothing but grief.
response.CompanyId is considered as string , so try by concatenating it as below
var a="location.href='#Url.Action("Edit", "Company", new{#id='"+response.CompanyId+"'})'"
response.CompanyId ( "<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\""+a +"\"> Edit</button></p>" + "</td></tr>")

Categories