Why ajax request repeat? - javascript

I am trying to get the todo titles from jsonplaceholder.typicode.com JSON. I have three buttons and each botton has and id, that id is related to the json todo. When you click on a botton you see the title of that json todo.
Button 1 = jsonplaceholder.typicode.com/todos/1 Button 2 =
jsonplaceholder.typicode.com/todos/2 etc..
$('button').click(function (event) {
var id = event.target.id;
console.log(id);
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/" + id,
type: "GET"
}).done(function (data) {
$('#result').append('<div class="todo"></div>');
$.each(data, function (key, value) {
if (key == "title") {
$('.todo').append('<p>' + key + ': ' + value + '</p>');
}
});
}).fail(function (event) {
alert(event.status);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1">A</button>
<button id="2">B</button>
<button id="3">C</button>
<div id="result">
</div>
The problem is that titles repeat each time I click on a button. Why this occurs?

Why? Because you append another <div class="todo"></div> each time button is clicked and then append the content to every one that exists
You can isolate the new <div class="todo"> and only append the new content to that
var $todo = '<div class="todo"></div>'
$('#result').append($todo);
$.each(data, function(key, value) {
if (key == "title") {
$todo.append('<p>' + key + ': ' + value + '</p>');
}
});
Or empty the $('#result') before you add the new content if you don't want to see the first set by changing:
$('#result').append('<div class="todo"></div>');
To
$('#result').html('<div class="todo"></div>');

On each ajax done callback you first create a new todo div:
$('#result').append('<div class="todo"></div>');`
and after that, you add the result to all elements with a todo class:
$('.todo').append('<p>' + key + ': ' + value + '</p>');
I'd suggest removing the first line and changing the second to $('#result')

Related

Want to add delete functions for a list of date displayed

to summarize my problem ... I have made a calendar with contains the from - to date range. Now the selected dates are displayed in a div with a delete button for each. But as the id of the button is the same for all the dates ....it deletes the entire date range. I have attached the screenshot as well.
I also tried taking a loop and giving each date a div so that the Del function will work properly. but I wasn't successful. I will mention code for the same
$(document).ready(function () {
var i = 0;
$.each(between, function (key, value) {
var rest = $('#target').append($('<div id="r' + i +value+ '" class="ansbox">
</div>'));
console.log(between);
var template = '<div id="ChildTarget_' + i + '"><span>key + ":" + "' + value + '"
</span><button id="tr' + i + '" class="target">X</button></div><br></div>';
i++;
$('#target').on('click', function () {
console.log("hola");
$('#target').remove();
You should add click event for the button itself.
var template = `
<div id="ChildTarget_' + i + '">
<span>key + ":" + "' + value + '"</span>
<button id="tr' + i + '" class="deleteButton">X</button>
</div>`;
$(".deleteButton').on('click', function() {
// do deletion here
});
First of all ,
The 'X' button should have different id
$.each(between, function (key, value){
$('#results').append(key+":"+value+'<br>');
$('#results').html(between.join('<button id="result"+key+"" > X </button><br>')
here you can see i am adding key to the Button Id making it unique. Use that id to remove the value, that you dont want. Hope this helps

Adding onclick event on dynamically created HTML caused an error: Uncaught SyntaxError: Unexpected identifier

I'm using ajax to get an results from code behind, when I Get those results I'm creating an a divs. And this works fine, adding a div dynamically.
Now I Want to add on each div onclick event which should raise some method when it's clicked, so here is my full code:
<script>
function onSelectGroup(Id) {
$.ajax({
method: "GET",
url: "Product/GetProductsByGroupId",
data: { groupId: Id }
})
.done(function (response) {
$(".products").html("");
for (var i = 0; i < response.length; i++) {
//I wrote onclick = "addProduct(response[i])" to generate for each div each onclick event
let item = '<div class="col-md-3"> <div class="Product-holder" onclick="addProduct(' + response[i] + ')" id=' + response[i].ProductId + '><img class="img-responsive" src="images/maxresdefault.jpg"><p class="product-title" style="color:white;margin-top:5px;text-align:center;"> ' + response[i].Title + '</p></div></div>';
//Trying to append it to my .product class because it's parent of this divs above
$(".products").append(item);
}})};
function addProduct(product) {
console.log(product.Title);
}
</script>
But when I click on any of my generated divs I get an following error:
Uncaught SyntaxError: Unexpected identifier
I'm looking for issue for 3h allready, and I'm really stucked here..
Any kind of help would be great.
Thanks
P.S
CODE BEHIND - C # METHOD:
public ActionResult GetProductsByGroupId(int groupId)
{
var products = ProductController.GetProductsByGroupId(groupId);
if(products)
{
List<Product> productlist = new List<Product>();
foreach (var item in products)
{
Product product = new Product();
product.ProductId = Convert.ToInt32(item.Id);
product.Price = Convert.ToDecimal(item.Price);
product.Title = item.Title;
productlist.Add(product);
}
return Json(productlist, JsonRequestBehavior.AllowGet);
}
return Json(products, JsonRequestBehavior.AllowGet);
}
Remove the onclick and use delegate, you are passing an object to a function which convert response[i] to text [Object object], use data-* attributes to hold data for each object and attach an event to the div with the class product, on click of the div we'll use $(this) to reference the current clicked div and access its data attributes.
$(".products").html("");
var response = [{ProductId:4, Title:"Doe", Price: 34.89}, {ProductId:6, Title:"Jane", Price: 20.99}];
for (var i = 0; i < response.length; i++) {
//I wrote onclick = "addProduct(response[i])" to generate for each div each onclick event
let item = '<div class="col-md-3"> <div class="Product-holder product" data-price="'+ response[i].Price +'" data-title="' + response[i].Title + '" id=' + response[i].ProductId + '><img class="img-responsive" src="images/maxresdefault.jpg"><p class="product-title" style="color:white;margin-top:5px;text-align:center;"> ' + response[i].Title + '</p></div></div>';
//Trying to append it to my .product class because it's parent of this divs above
$(".products").append(item);
//console.log(item);
};
$(document).on('click', '.product', function(){
var product = {Title: $(this).data('title'), ProductId: $(this).attr('id'), Price: $(this).data('price')};
console.log(product);
// here use ajax to add this product
});
body {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="products"></div>
Take a look at the Delegate jquery method!
Description: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
So you basically need to bind the onClick event to the parent div, and pass a selector that will appear later on the child divs.
<script>
function onSelectGroup(Id) {
$.ajax(
//Do your ajax call here
).done(function (response) {
for (var i = 0; i < response.length; i++) {
let item = '<div class="event-target"></div>'
$(".products").append(item);
}})};
// Here's where the magic happens.
// We bind the event to the elements that have the 'event-target' class
//inside the element that have the 'products' class.
$('.products').on('click', '.event-target', function(){
console.log(this);
})
</script>
Warning: take care using delegate, if you use the wrong selector you can end up triggering the event for each element on the page, or even recursivelly (belive me, have made it a lot...)
Use data attributes to store any data & on click retrieve the data attribute.The code is not tested but hopefully it will work
let item = '<div class="col-md-3">' +
' <div class="Product-holder" ' +
'onclick="addProduct(this)"' +
' data-title="'+response[i].Title+'"' +
' id=' + response[i].ProductId + '>' +
'<img class="img-responsive" src="images/maxresdefault.jpg">' +
'<p class="product-title" style="color:white;margin-top:5px;text-align:center;"> ' + response[i].Title + '</p>' +
'</div>' +
'</div>';
$(".products").append(item);
function addProduct(product) {
console.log($(product).data('title'));
}
Also you need to delegate the event since they are dynamically created element
$("body").on("click",".Product-holder",function(){
console.log($(product).data('title'));
})
In this case the inline event handler that is onclick function will be redundant
Let me going to explant your code.
for (var i = 0; i < response.length; i++) {
let item = '<div class="col-md-3"> <div class="Product-holder" onclick="addProduct(' + response[i] + ')" id=' + response[i].ProductId + '><img class="img-responsive" src="images/maxresdefault.jpg"><p class="product-title" style="color:white;margin-top:5px;text-align:center;"> ' + response[i].Title + '</p></div></div>';
$(".products").append(item);
}})};
On these line of code, I saw that you have added strings to a variable.
but more exception response[i].ProductId seem like response[i] was an object.
but in Javascript you can't add an object to String by + operator, it will be return "string [object] string". What is solution for that??
Convert your object to JSON String like {"id": 123, "name": "Product name"}, that will show in html code like this onclick='addProduct({"id": 123, "name": "Product name"})' remember that onclick = ' not "

Expand a line in a table

Using the following example, a table that pulls all of the items in Parse for its particular column (I.e. if there is 20 subjects in parse, than 20 subjects would be displayed).
http://jsfiddle.net/richf/sKLxE/
Below is the code for it:
Javascript:
//message
var Message = Parse.Object.extend("Message");
var query = new Parse.Query(Message);
query.descending("createdAt");
query.find({
success: function(results) {
//alert("Successfully retrieved " );
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
(function($) {
$('#messages-table').append('<tr><td>' + object.get('currentDate') + '</td><td>' + object.get('Subject') + '</td><td>' + object.get('Message') + '</td></tr>');
})(jQuery);
//alert(object.id + ' - ' + object.get('playerName'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
HTML
<table id="messages-table">
<tr>
<th>
<h1>Date</h1></th>
<th>
<h1>Subject</h1></th>
<th><h1>Message</h1></th>
</tr>
</table>
What I am trying to achieve is the following is making each line clickable, where when someone clicks on a line then the message from the “message” column in parse is retrieved, and displayed right below the line click, and once that line is click again, that message is hidden.
This is a massive dilemma I am having, I have spent quite some time trying to resolve it.
If you need any clarification, let me know.
Add a class to the rows... and add your additional data as a hidden table row.
$('#results-table').append('<tr class="results-row"><td>' + object.get('playerName') + '</td><td>' + object.get('score') + '</td></tr><tr class="xtra"><td colspan="2">INSERT MESSAGE HERE</td></tr>');
(Note extra table row added above)
CSS: .xtra {display: none;}
Then you can easily toggle that extra row:
$(document).on('click' , '.results-row', function () {
$(this).next('.xtra').toggle();
});
DEMO HERE
First add some indicator for the element which on click will have some action.
For example:
$('#results-table').append('<tr><td class="player">'
Then add an event listener as below:
$(document).on('click' , 'td.player', function () {
alert("Clicked on" + $(this).hmtl());
});

Onclick event are not working properly

on click event in node.js is not working but simple text input work.i want that when you click on buttons( in my case two buttons) the two different event happen but it does not work. these two different events are append DOM within page. one of the button have value 'X' and other one have 'O' and i want to just append DOM with button's value. How can i do that?
this is code--->
my script is-
$(function() {
var socket = io.connect(window.location.href);
socket.on('message:server', function(data) {
$("#messages").append(
'<li style="color:red">' +
data.message + ' - ' + 'received' + ' ' + new Date() +
'</li>'
);
});
$("#message_form").on('submit', function(event) {
event.preventDefault();
var $input = $('[name="message"]')
var message = $input.val();
if (message) {
socket.emit('message:client', {message: message});
}
$("#messages").append(
'<li style="color:green">' +
message + ' - ' + 'sent' + ' ' + new Date() +
'</li>'
);
$input.val('');
});
socket.on('error', function() {
console.error(arguments)
});
});
in Body tag-
<form id="message_form" method="post">
<input name="message" placeholder="Message to send" type="text"/>
<button type="submit">Submit</button>
</form>
here at bottom in place of form i want 2 buttons which can operate this with default given fix value.
What about creating two buttons in the DOM and calling .on('click', function(){}) instead of submit ?
Like :
<button id="value1">Send value 1</button>
<button id="value2">Send value 2</button>
Then you simply set the function on click event. I added comments to your code to show what you can remove :
$("#value1").on('click', function(event) {
event.preventDefault();
// var $input = $('[name="message"]');
// You don't need fix since you send "fixed" value
var message = "Value 1" // Or whatever you want instead of $input.val();
// if (message) {
// No need of condition since you set the value
socket.emit('message:client', {message: message});
// }
$("#messages").append(
'<li style="color:green">' +
message + ' - ' + 'sent' + ' ' + new Date() +
'</li>'
);
// $input.val('');
});
You simply do the same for your button 2.
For this example, you would call :
$('#value2').on('click', function(){
// Same as value with another message value
});

how to refresh the list in jquery javascript

Hi i m having one page with one textbox named search and one search button. When i'm searching anything for the first time it's showing me the right data but when i'm searching some other things for the next time then the elements which was listed before are also appended below of that new list. Suppose i'm searching state name by k it will give me right list of karnataka, kerala. But if i start to search again by g, it will show me in output as goa,gujrat,karnataka kerala. i tried using refresh option but it still not working. This is my js code
$.each(response.state, function (i, state) {
$('#statelist').append(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
$("#statelist").listview("refresh");
and this is html
You are using .append() function. It appends whatever you append to the end of the list.
Check this link:
http://api.jquery.com/append/
Try using innerHTML property of the DOM model.
You could add
If(!('#statelist').html() == ""){
$(this).remove();
//execute rest of code that appends state list
}
Then do an else statement and execute your append code without removing()
UPDATE: a better option is to do this-
$.each(response.state, function (i, state) {
$('#statelist').html(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});

Categories

Resources