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.
Related
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.
I'm trying to save google's API search results in a Mysql database in localhost.
My problem
I'm using a for loop to show every possible result from book research, such as "Harry Potter".
I do this with AJAX and then I cycle the results.
The main problem is that if I want to save one of the results, what is saved is just the last one because every variable is overwritten during every cycle.
Here is the code, saveBook.php is just a .php file where I do an insert into query.
$.ajax({
url:"https://www.googleapis.com/books/v1/volumes?q=" + search,
dataType: "json",
type: 'GET',
success: function(data){
for(i=0; i < data.items.length; i++)
{
title = $( '<p> ' + data.items[i].volumeInfo.title + '</p>');
author = $('<p> ' + data.items[i].volumeInfo.authors + '</p>');
img = $('<img><a href=' + data.items[i].volumeInfo.infoLink +
'><br></br><button>Read More</button></a>' );
url= data.items[i].volumeInfo.imageLinks.thumbnail;
save = $('<br><button onclick="save()">Save</button></br>
</br>');
img.attr('src',url);
title.appendTo("#result");
author.appendTo("#result");
img.appendTo("#result");
save.appendTo("#result");
}
},
});
}
}
function save(){
$.ajax({
type:'POST',
data: {
url: url,
title: title,
author: author,
},
url: "saveBook.php",
success: function(data){
alert("Success!");
location.replace("home.php");
}
})}
Another problem is:
how should I use this JSON
data: {
url: url,
title: title,
author: author,
},
to actually return a string with title and author, because url is correctly saved.
I've had some time to think over your project. While I'm not sure of all of your project requirements, a fundamental pursuit should be to minimize the calls to the api. For this reason, let your users search via a standard (non-ajax) search input/form and load the api results into the html with php, then use your ajax call to allow multiple save calls from a single load of search results (if that makes sense for your project). Basically, I suppose I am discouraging the auto-reload after saving a single item; otherwise you can avoid ajax again.
Also, as far as I know authors is an array, so you'll need to join/implode the values into a single string.
foreach (json_decode($apijson, true) as $item) {
echo '<div class="book">';
// your other elements in the row
echo "<button onclick=\"save('" ,
htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars($item['volumeInfo']['title'], ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars(implode(', ', $item['volumeInfo']['authors']), ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars($item['volumeInfo']['imageLinks']['thumbnail'], ENT_QUOTES, 'UTF-8') , "');\">Save</button>";
echo '</div>';
}
Then these parameters can be directly fed to your ajax function.
Be sure to validate and use sensible data sanitizing techniques and use a prepared statement when you INSERT.
You can return a success message from your ajax, and then hide() the saved row/book.
You can return a vague (not exact) error message if the insert did not make an "affected row".
Problem solved thanks to #mickmackusa. I have declared the variable "save" as a global array and, then, I have passed every string with a proper escape. Now it's working fine! Thank you very much.
save[i] = $('<button onclick="save((\'' + data.items[i].volumeInfo.authors + '\'),(\'' + data.items[i].volumeInfo.title + '\'),(\'' + data.items[i].volumeInfo.infoLink + '\'))">Save</button><br><br>')
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.
I am trying to pass objs array to a function in Laravel controller using ajax. I am not recieving any data after the post.
<script>
var itemCount = 0;
var objs=[];
$(document).ready(function(){
var temp_objs=[];
$( "#add_button" ).click(function() {
var html = "";
var obj = {
"ROW_ID": itemCount,
"STREET_ADDRESS": $("#street_address").val(),
"CITY": $("#city").val(),
"ZIP": $("#zip").val()
}
// add object
objs.push(JSON.stringify(obj));
itemCount++;
// dynamically create rows in the table
html = "<tr id='tr" + itemCount + "'><td>" + obj['STREET_ADDRESS'] + "</td> <td>" + obj['CITY'] + " </td> <td>" + obj['ZIP'] + " </td><td><input type='button' id='" + itemCount + "' value='remove'></td> </tr>";
//add to the table
$("#multiple_table").append(html)
// The remove button click
$("#" + itemCount).click(function () {
var buttonId = $(this).attr("id");
//write the logic for removing from the array
$("#tr" + buttonId).remove();
});
});
$("#submit").click(function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address',
type: 'POST',
dataType:'json',
contentType: 'application/json',
data: objs
});
});
});
</script>
In my controller function is like this
public function search_address(){
$data = json_decode($_POST['data'], true);
print_r($data);
}
I guess that I am having a problem with the url in ajax and I am not sure how a controller's url is obtained.
Thank you
Can you change:
$data = json_decode($_POST['data'], true);
to:
$data = json_decode(Input::get('data'));
and make sure you have: use Input; above your class extends Controller
See if that works.
Edit: Also make sure your routes (in the Controllers folder) are correct.
You should console.log() your javascript by placing the following in you ajax post:
error : function(e){
console.log(e);
}
You can then see what errors you are getting in your browsers' developers tools panel.
You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:
$("#submit").on('click', function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
type: 'POST',
data: {'data': objs, '_token' : '<?=csrf_token()?>'},
success : function(data){
// Do what you want with your data on success
},
error : function(e){
console.log(e);
}
});
});
Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing (AngularJS is also popular), but you can easily do something like:
<input type="hidden" id="_token" value="{{ csrf_token() }}" />
in your HTML, then pull this value from inside your ajax request:
data: {'data': objs, '_token' : $('#_token').val()}
EDIT
I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:
Route::post('/searchAddress', 'YourController#search_address');
Then use:
url: /searchAddress
in your ajax request.
Please look at the ajax code below, As you can see, i have managed to make a button display in each table row, which is great, the issue is each button will only link ti the dataurl, I'm really needing to make it so that each button will link off to a different place, But only is the event is still available. E.g. if a row disappears i need the button to disappear? So the Increment feature wouldn't work.
Thanks
Sam
Heres the ajax code
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link for seatwave',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.TicketGroups.length; i++) {
var section = json.results.TicketGroups[i].TicketTypeName;
var no = json.results.TicketGroups[i].Qty;
var price = json.results.TicketGroups[i].
Price;
var button =
"<button class='btn btn-info' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tr><td>seatwave</td><td>" + section +
"</td><td>N/A</td><td>N/A</td><td>" + no +
"</td><td>£"+price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".btn.btn-info").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
you are selecting all buttons every iteration of the for loop;
//this line selects all elements with classes .btn.btn-info
$("#tableid").find(".btn.btn-info")
therefore once its done all your buttons will have the link of the last created button.
it would be easier if instead of the line:
var button = "<button class='btn btn-info' data-url='LINK'>Click Here</button>";
you would wrap the button with a jQuery object, and attach the click handler to it:
var button = $("<button class='btn btn-info' data-url='LINK'>Click Here</button>");
button.click(function() {
location.href = $(this).attr("data-url");
});
and when you add the button to the dom you can do it this way:
//this will retrieve the html element from the jquery object
"</td><td>" + button[0] + "</td></tr>"
I don't know if I got you right, but I think you want to set the value of your data-url='LINK' attribute.
For example you can set it right away in your String, like so:
var link = isEventAvailable ? json.results.getLink() : undefined;
var button = link ? "<button class='btn btn-info' data-url='" + link + "Click Here</button>" : return "whatever action";
So the above checks whether the event is available or not, if so you get the link from wherever you want, if not set it to a falsy value, js often uses undefined for this. Now set your button string to button only if link has been set otherwise to whatever you want.
Another route:
var button = "<button class='btn btn-info' data-url='LINK'>Click Here</button>";
button.attributes.getNamedItem("data-url").value = link;
This is nasty but verbose enough so that you can check it out in the APIs:
Element.attributes
NamedNodeMap
And then see the Attribute Object