C# send table cell data from one page to another - javascript

I have two pages customer.aspx and customer_detail.aspc, each with their corresponding code behind files. The objective is being able to send a particular table cells's value from customer to customer_detail. For example, the following javascript renders the table dynamically onto customer.aspx based on the BindTable method in customer.aspx.cs file.
customer.aspx:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "customer.aspx/BindCustomer",
data: "{}",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.d.length; i++) {
$("#customer_table").append("<tr><td>"+'<a id = "anchor" href="customer_individual.aspx">' + data.d[i].customer_name +'</a>'+ "</td><td>" + data.d[i].customer_id +"</td><td>" + data.d[i].total_value + "</td><td>" + data.d[i].created_date + "</td></tr>");
}
},
error: function(result) {
alert("Error");
}
});
});
The BindCustomer function above is a WebMethod written in customer.aspx.cs, which returns a customer array object, customer[], which is bound to the customer_table. Notice that, in the above I have a href within the first td element of the table, which redirects the page to the customer_detail.aspx.
The objective is to be able to send say a customer_name value upon clicking the link to the customer_detail.aspx.cs, so that I can query the customer object which I store separately, with the name and populate the page accordingly. What would be the best method to accomplish this? Any suggestions as to how to proceed will be greatly helpful!

The easiest way is to format a link to customer_detail.aspx with the data you want to pass in the querystring like this (it looks very similar to what you're already doing.)
Link
When customer_detail.aspx loads, you retrieve the value from the querystring.
In your Page_Load event in customer_detail.aspx
var customerName = Request["customerName"];
You could be more particular and say Request.Querystring["customerName"] but on this page you probably don't care whether the value was passed in the querystring or a form field. Request["customerName"] covers both.

Related

Why am I getting a '$' is not defined when running an AJAX query?

Possibly a dumb question, but I have a page where I'm trying to load list data into a customer table to display as a front-end. I'm retrieving this list from a SharePoint list using an AJAX call in a Javascript function, however when I'm using this function my console returns a SCRIPT5009: '$' is not defined error. Previously, I've used an AJAX call successfully using very similar code, but to return a single item from the list using the list ID to search for a specific item, and I've run the query successfully directly from the URL that returns the data I'm after - I'm just not sure what's happening with this one.
function getIncidents(){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$select=Title,Id,Priority,IncidentStart,IncidentStatus,IncidentTitle,UpdateResolution",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
var dResponse = data.d.results;
var results = document.getElementById('Results');
results.innerHTML += "<tr><td>Incident<br>Reference</td><td style='width:20px'></td><td>Priority</td><td style='width:20px;'></td><td>Start Time</td><td style='width:20px'></td><td style='width:170px'>Issue</td><td style='width:20px'></td><td style='width:170px'>Latest Update</td><td style='width:20px'></td></tr>";
for(var obj in dResponse){
results.innerHTML += "<tr style='font-size:10pt'><td>"+dResponse[obj].Title + "</td><td></td><td>" + dResponse[obj].Priority + "</td><td></td><td>" + dResponse[obj].IncidentStart + "</td><td></td><td>" + dResponse[obj].IncidentTitle + "</td><td></td><td>" + dResponse[obj].UpdateResolution + "</td></tr>";
}
}
});
}
Previous example where I have this call working:
function getIncident() {
var listName="Incident List";
var incidentID = $("#incidentReference").val();
if(incidentID!=""){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$filter=Title eq '" + incidentID + "'&$select=Title,Id,SystemOrService,Priority,IncidentStatus,IncidentTitle,UpdateResolution,IncidentStart,ImpactedArea,IncidentEnd",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
if(data.d.results.length>0){
var item=data.d.results[0];
$("#systemImpacted").val(item.SystemOrService);
$("#incidentPriority").val(item.Priority);
$("#incidentState").val(item.IncidentStatus);
$("#incidentTitle").val(item.IncidentTitle);
$("#incidentUpdate").val(item.UpdateResolution);
$("#startTime").val(item.IncidentStart);
$("#impactedAreas").val(item.ImpactedArea.results);
$("#endTime").val(item.IncidentEnd);
updateImpact();
getStartTime();
getEndTime();
actionsFormat();
}
},
error: function (data) {
alert("Incident Reference incorrect or not found");
}
});
}
}
The issue is that jQuery ($) is not yet loaded to the page. If you used it before, this means that loading is already setup, so you don't need to add more references to the jQuery.
In most of the cases, when you working with jQuery, you will subscribe on DOM event ready event and do your code there.
So, all you need is to find the
$(document).ready( ...
statement and insert your code there.
If you want to separate your code from already existed, you may write your own $(document).ready subscription.
If you will not find this $(document).ready function, you can search in html for the reference to the jQuery, and insert your script after it. But, than you need to be sure, that reference doesn't include async or defer attribute.
As mentioned in comments, if you decide to add your own subscription, you also need to place it after jQuery reference, because it will not work, if $ isn't available.

How to refresh a table inside a div tag using ajax php

I have an ajax table click event that gets database data according to the clicked name from the first table and display the second table with employee information. The problem now is that the employee information data only pile up in the second table, I want to refresh the second table every name that the user clicked. By the way the second table is inside a div tag.
Here is my ajax code:
function putThis(control){
var getid = control.innerText;
var first = $("#from[name=from]").val();
var second = $("#to[name=to]").val();
$.ajax({
type:'POST',
url: 'testtable.php',
data: {id: getid,from: first,to: second},
cache: false,
global: false,
success:function(data)
{
$("#result").append(data);
alert("Success: " + getid + " " + first + " to " + second);
}
});
}
If I am reading your question properly (and correct me if I am not), you want to replace the contents of the element rather than append the data to the element.
This can be accomplished with your code by changing this line :
$("#result").append(data);
To this :
$("#result").html(data);
append will put data at the end of the element before the closing tag, while html will consume the element with the data you are inserting.
In your code as I can see you want to click on user name from left panel and call ajax for his/her information from database .
But as you are appending that information to div and this append call append the data a the end of the div instead you can call $("#result").html(data);.
So final ajax call will be-
$.ajax({
type:'POST',
url: 'testtable.php',
data: {id: getid,from: first,to: second},
cache: false,
global: false,
success:function(data)
{
$("#result").html(data);
alert("Success: " + getid + " " + first + " to " + second);
}
});
if still issue persists you can do following steps -
1. check any error in console tab in firebug.
2. if ajax is failing at any point .

Passing data that is coming from a server, from one page to another in javascript without using forms

I do not have much grip on javascript and having problemswith it.
My data is coming from a server and the user when clicks on an item is redirected to a new page which has that items all details. The problem is when a user clicks on an item,how to send the data from one page to the next.
No php is used. javascript ajax jquery used and data coming from json
this is format and when user clicks on play button a new age should be displayed where the data is to be shown to user.
Template={"Big_Display_Template": '{{#items}}<input type="hidden" name="guid" value="{{id}}"><div class="hero"
style="background-image:url({{videoStillURL}})"><div class="hero-content"><br>
<h2>{{name}}</h2> <p>{{shortDescription}}</p> <div class="hero-links"><a href="Watch_Live.html"
onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});">
Play<span class="genericon genericon-play"> </span></a></div>
<div class="hero-links-fav"><a href="#">Favourite<span class="genericon genericon-fav">
</span></a></div></div></div>{{/items}}'
}
This is my function PassDataToNextPage()
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
$.ajax({
url: url,
type: 'POST',
data: 'name=' + name + '&guid=' + guid + '&shortDescription=' + Description,
success: function(result) {
dataUrl=data;
}
});
return window.location+"/"+dataUrl;
}
I know this is wrong but how to make it right? thanks a lot in advance
The problem lies in the return window.location+"/"+dataUrl; line: the redirect should be done inside the success function because it will be called when the request is completed:
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
$.ajax({
url: url,
type: 'POST',
data: 'name=' + name + '&guid=' + guid + '&shortDescription=' + Description,
success: function(result) {
dataUrl = data;
window.location = window.location + "/" + dataUrl;
}
});
}
In the template you must add return false in the onclick attribute to avoid the browser following the link interrupting your handler:
<a href="Watch_Live.html" onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});return false">
You can pass key:value data via url GET parameters.
For example: if you want to pass data to this page: Watch_Live.html, you can do something like:
<button>Pass data</button>
To parse the parametesr in the other page, read this SO answer to a similar question.
https://stackoverflow.com/a/901144/4440845
Look like you want to pass data and go to the next page with the data, you don't need ajax to achieve. Simply:
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
window.location.href = url + '?name=' + name + '&guid=' + guid + '&shortDescription=' + Description;
}
Comment:
You can use:
< a onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});">Play< /a>
The click event will be handled by the function PassDataToNextPage in onclick.
Assuming you use PHP in your next page, you can fetch the data
$name = $_GET['name'];
$guid = $_GET['guid'];
$shortDesc = $_GET['shortDescription'];

Web forms delete button with bootstrap outside the form

I've got an issue. I want to create a delete button that will erase a record from database. As long as I know how to do everything with database, I have NO IDEA how to manage with the button. I use javaScript to create a table and fill it with records. HALP!
function CreateATableFromDataBase() {
var deserializedData = '<%=serializedList %>';
deserializedData = JSON.parse(deserializedData);
for (var i = 0; i < deserializedData.length; i++) {
document.write(
"<tr>" +
"<th scope=\"row\">" + i.toString() + "</th>" +
"<th>" + deserializedData[i]["Name"] + "</th>" +
"<th>" + deserializedData[i]["Where"] + "</th>" +
"<th>" + deserializedData[i]["Destination"] + "</th>" +
"<th><button type=\"button\" class=\"btn btn-default btn-primary\">Delete</button></th>" +
"</tr>"
);
}
}
I have a button yet I have no idea how to assign a method to it. Moreover, I've been thinking about routes.
I use Web Forms.
The way to do this that comes to mind if you don't want to use normal ASP.NET Web Forms form and buttons is to use AJAX (jQuery makes it easier) and ASP.NET Web Methods.
You will need a way of identifying your buttons and passing some sort of identifier such as your database primary key column value (presumably you have all sorts of security as this could be dangerous).
I would change your button line to something like this:
"<th>Delete</th>" +
(Note: you have btn-default and btn-primary classes applied, but there should be only one or the other)
I have added btn-delete as a class so all of these buttons can be identified and the click event tracked. I also added a rel attribute with the database identifier - this will have to be changed to whatever you use.
You could then add some JavaScript to handle clicking of these buttons and the AJAX request:
<script type = "text/javascript">
$(function () {
$(".btn-delete").click(function () {
$.ajax({
type: "POST",
url: "MyPage.aspx/Delete",
data: '{id: ' + $(this).attr("rel") + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
alert("Deleted");
},
failure: function() {
alert("Failure");
}
});
});
});
</script>
Note that it picks up the rel attribute and passes that as a paramater to the Web Method (below). It shows an alert box to indicate the status of the request.
You would need to make sure you are including jQuery before this script, of course.
Then in your ASP.NET page code behind you can create a Web Method to handle the AJAX request:
[System.Web.Services.WebMethod]
public static void Delete(int id)
{
//Code to delete from database
//If error return an exception or change method to return some value
// for error which you can show to the user
}
For further examples see http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx as I copied a bit of code from there for my answer.

Elasticsearch how search in multiple fields

I am using elasticsearch 1.2.1 and I want to do a search from javascript with several fields, for instance, by title and content.
My code is:
var data = { q: 'title: test};
$.ajax({
data: data,
url: http://localhost:9200/_search,
type: 'GET',
success: function (data) {
$.each(data.hits.hits, function(position,hit) {
$("#<portlet:namespace/>search-pattern").append( '<li>' + hit._source.title + '</li>' );
});
}
});
But in addition to search for a title also want to look for the content field.
What should be the value for the attribute data in order to search not only by the field 'title' but also by the field 'content'?
Someone can help me?
Thanks in advance
Try to use Request Body Search, specify the conditions using Query DSL

Categories