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
Related
Hello my masters,
I want to update (link_name, link_address, link_type). Link_type with tag in HTML page feed. I know many code exist in internet about CURD but I don’t know why my code don’t execute correctly. There is some problem that I mention in following, maybe long so first of all apologize.
First part: fetching data from DB with Ajax. In editlink.blade.php
try {
for(var count=0; count < data.length; count++)
{
html +='<tr >';
html +='<td contenteditable class="column_name" data-column_name="link_name" data-id="'+data[count].id+'">'+data[count].name+'</td>';
html += '<td contenteditable class="column_name" data-column_name="link_add" data-id="'+data[count].id+'">'+data[count].Address+'</td>';
html += '<td contenteditable class="column_name" data-column_name="link_type" data-id="'+data[count].id+'">' +
'<select id="opttypes" value="'+data[count].id+'">' +
'<option id="opt1"'+ check_selected1(data[count].type)+' value="1"'+' >'+d1+'</option>' +
'<option id="opt2"'+ check_selected2(data[count].type)+' value="2"'+' >'+d2+'</option>' +
'<option id="opt3"'+ check_selected3(data[count].type)+' value="3"'+' >'+d3+'</option>' +
'<option id="opt4"'+ check_selected4(data[count].type)+' value="4"'+' >'+d4+'</option>' +
'</select>' +
'</td>';
html += '<td><button type="button" class="btn btn-danger btn-xs delete" id="'+data[count].id+'">Delete</button>' +
'<button type="button" class="btn btn-success btn-xs edite" id="'+data[count].id+"_"+count+'">Update</button></td></tr>';
}
$('tbody').html(html);
}// end try
catch (e) {
document.getElementById("demo").innerHTML = "error accrue in fetch form DB ";
}
Description first part:
1) Data is backed variable from Ajax, that include weblinks table in DB.
2) Spread count in edit button use to refer row in table and then fetch content of cell.
Second part: java code of edit button in editlink.blad.php
$(document).on('click', '.edite', function(){
var allid=$(this).attr("id").split("_");// try to access id of data and number of row in HTML table
var id2=allid[0];// fetch ID of data in DB
var countRow=Number(allid[1])+2;// calculate detected row that user clicked.
var link_name = document.getElementById("html_table").rows[countRow].cells.item(0);// gets links name
var link_add =document.getElementById("html_table").rows[countRow].cells.item(1);// gets link address
var link_type=$("#link_type :selected").val();// gets which option user clicked.
if(link_name != '' && link_add != '' && link_type!='' )
{
if(!confirm("Do you want to edit this row")) {
return false;
}
try
{
$.ajax({
url:"{{ route('weblink.update_data') }}",
method:"POST",
data:{link_name:link_name, link_add:link_add, link_type2:link_type, id:id, _token:_token},
success: function(data){ // What to do if we succeed
if(data == "success")
$('#message').html(data);
},
error: function(data){
alert('Error'+data);
}
})
}
catch (e) {
$('#message').html("<div class='alert alert-danger'>error in receiving data from Ajax </div>");
}
}// end if check empty box
else {
$('#message').html("<div class='alert alert-danger'>Both Fields are required</div>");
}
});
Description this part
1) When I click update button option tag showed -1 that refer the first option which isn’t useful. I use this code for add button work correctly but I don’t know why in this function doesn’t work.
Third part: Function in controller
function update_data(Request $request)
{
if($request->ajax())
{
weblink::where('id', $request->id)->update([
'name' => '$request->link_name',
'Address'=>'$request->link_add',
type=>'$request->link_type2'
]);
echo '<div class="alert alert-success">Data Updated</div>';
}
}
Description this part
1) Weblink is model
Fourth part: web.php for update
Route::post('/weblink/update_data', 'weblinksController#update_data')->name('weblink.update_data');
Excuse me every one, I know my code is boring. If possible help me.If every one like please give me your mail I will send all of my code completely(View, Controller and web).
Best regards.
I've set up an Ajax request to the Ebay API using Jquery, which works while I have a search term/keyword hardcoded, but I cannot figure out how to write the code to make my (bootstrap) button trigger the Ajax request using the search form input. I've tried various things to no avail. I'm completely new to this and this is my first time making an Ajax request and using JQuery so hopefully this makes sense.
Jquery:
$(document).ready(function() {
url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=rare soul 45"; //This would get deleted?
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
HTML:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I'm a bit surprised you managed to get an ajax request running but you struggle with registering a click event handler. :) but here we go...
$('form[role="search"]').submit(function(ev) {
ev.preventDefault();
// get the input value with:
var searchstring = $('input[type="text"]', this).val();
// your ajax request, using the variable above
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=" + searchstring;
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
It looks like you are making that ajax call upon document ready which is not really what you want. You want to make that call upon a button press event. So I would do this.
Put that ajax call into a function that you can call
Give the button an id
On document ready, use jquery to attach an event handler to the element with the id in step 2 above that triggers a call to your function mentioned in step 1 above.
Then, don't forget to extract the value in the field from the event and place it into the called ajax function as a parameter.
Given your current HTML, you can call a click event on your submit button like this...
$('button[type="submit"]).on('click', function(event) {
/*
since the button is of type "submit",
prevent the default behavior. Which,
in this case, is to submit the form.
*/
event.preventDefault();
//Check your browser's console to see what this is
console.dir(event);
//insert AJAX code here
});
This code uses the jQuery .on() method to capture the given event, 'click', on a given element $('button[type="submit"]'). Once this event has been captured, you can access it as event, or name of your choice, within the function.
This event object contains information regarding the event itself. It can be quite daunting at first, but I encourage you to look through a console.dir(event); call. More specifically, e.currentTarget/e.target, and view to get a sense of what is going on. From there you can look into what the difference is between some things that seem the same and get as familiar with it as you'd like.
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.
I'm trying to submit a rails form using jQuery (Which I know little about) and have had success in setting up a form to submit on clicking the submit button and run a callback(I believe this is the correct terminology?), but I would also like to make it work when just hitting enter.
As it stands, hitting enter will submit data to the database but will not run the commands to append the div or clear the text field. How could I make this happen so it works the same for the enter key as it does the submit button? I've tried to wrap the code inside a function that will run when enter is hit but having no luck!
function runScript(e) {
if (e.keyCode == 13) {
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
}
I tried that with no luck.
My current, button-working, JS file:
var scrollToBottom = function(anim){
var myDiv = $(".wrap");
myDiv.animate({ scrollTop: myDiv[0].scrollHeight - myDiv.height() }, anim);
};
$(document).ready(function(){
scrollToBottom(0)
//JS to POST form
$('.submit').click(function() {
var valuesToSubmit = $('.msgform').serialize();
$.ajax({
type: 'POST',
url: window.location.href + '/messages', //sumbits it to the given url of the form
data: valuesToSubmit,// { chat_id, <%= #chat.id %> },
dataType: "JSON", // you want a difference between normal and ajax-calls
})
.done(refresherFunc)
.fail(function(){
alert("Error sending message. It would be nice to make this a flash error.");
});
return false; // prevents normal behaviour
})
});
var refresherFunc = function(json) {
// Get debugging goodies.
console.log(json);
// Set variables with JSON object data
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
Catch your form submit event with jQuery's submit() function and return false inside it. This function will be called any way you submit the form (clicking on submit button or pressing enter key). Returning false will prevent the browser from completing the form sumbittion which lets you do whatever you want with it.
See example: http://jsfiddle.net/vgk4wu46/
I'm quite new to webdevelopment and AJAX and I'm facing a little issue there. Basically, I have a form on my webpage. When I submit this form, it makes an AJAX call to my controller, send me the data I want back, and change the html content of the page.
JS code :
$(document).ready(function() {
$("#mydiv table tbody td").click(function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$('#myform').submit(function()
{
try {
var host = $("#host").val();
var port = $("#port").val();
var username = $("#username").val();
var password = $("#password").val();
var database = $("#database").val();
$.ajax({
type: "POST",
url: "/management/connectDatabase",
dataType: "JSON",
data: "host="+host+"&port="+port+"&username="+username+"&password="+password+"&database="+database,
cache: false,
success:
function(data){
$('#mydiv').html(show_tables(data));
},
});
return false;
}
catch(e){
console.debug(e);
}
});
});
function show_tables(data)
{
var html = '<div id="mydiv">';
html += '<table class="display" id="example">';
html += '<thead><tr><th>Tables</th></tr></thead><tbody>';
for (var tablesCount = 0; tablesCount < data.tables.length; tablesCount++){
html += '<tr class=gradeA id="trtest">';
html += '<td id="tdtest">' + data.tables[tablesCount] + '</td>';
html += '</tr>';
}
html += '</tbody></table>';
html += '</div>';
return html;
}
When I submit the form, the HTML is generating right, and I can see my content. But, I can't click on any entries of the <table>. Moreover, when I want to see the sourcecode of my page, it doesn't displays me the table, but still my form, even if it has still been validated.
Could someone explain me what I do wrong here ?
Depending on which jQuery version you're using, you need to either bind the click event using jQuery.delegate or jQuery.on in order for things to work with dynamically added DOM elements.
Edit: as pointed out by Geert Jaminon, you have to use the selector parameter of the on function. This works for me.
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() + "My TR is:" + $(this).parent("tr").html());
});
.live() is replaced by .on() in the newer jQuery versions.
http://jsfiddle.net/ZqYgv/
you need to bind the click event handler after the rendering of the elements, since they weren't in place when you made the binding.
If you insert data dynamically, you need to add the click event after the data has been inserted.
http://codepen.io/thomassnielsen/pen/FEKDg
$.post('ajax/test.html', function(data) {
$('.result').html(data);
// Add .click code here
});