I have a like system in my website. Each message has a Like button and a counter next to it.
Now when someone clicks the Like button it should immediately change to 1, and if another user clicks the same message it would change to 2 and so on for each individual message.
I created the AJAX functions required to do this, but I am using document.getElementById which only retrieves the first instance found and views the response from the ajax request.
How can I make it so that it is viewed for each individual message?
Here is my AJAX requests:
jQuery(document).ready(function($){
$('.msg-icon').on('click', function(e){
e.preventDefault();
var reply_id = $(this).find('input[name="replymsg"]').val();
var request = reply(reply_id);
request.done(function() {
checkLikes(reply_id);
});
});
});
function reply(reply_id) {
return $.ajax({
data: reply_id,
type: "post",
url: "replyfavorite.php?replymsg="+reply_id,
});
}
function checkLikes(reply_id) {
return $.ajax({
data: { reply: reply_id },
type: "get",
url: "checkLikes.php?reply=" + reply_id,
success: function(data) {
document.getElementById('likesCount').innerHTML = data; //what can i change here to make the data go to each clicked button?
}
});
}
here is my html button that users click for each message:
<a href="" class="msg-icon" >
<i class="fas fa-heart fa-lg" id="favBtn" style="color: #e74f4e !important;" >
<span id="likesCount"><?php echo $row3['likes_count'] ?>
</span></i></a>
the code is working fine my only problem is with how to let the response go to the clicked message button only.
As you noticed, ID should be unique. Instead of using document.getElementById('likesCount').innerHTML = data;
use the data-* attribute
I.e:
<span data-id="536">12</span>
than inside the jQuery success do like:
success: function(data) {
$(`[data-id="${reply_id}"]`).text(data)
}
and such will update any number of data-id="" elements on the page with the newest likes count.
PS: if you want to make your counts "live" - instead of using AJAX which is one roundtrip-only (request → response), you could use https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
By using Web Sockets you're making sure an initial handshake is made between any client and your server and than small packets are shared between the two - for multiple clients simultaneously. That way you don't need to have recurring AJAX intervals - and all your guests will see the likes change value "automagically".
Since you are using jquery, why not use $("#likesCount").each(function(){ . . . . .. }); to loop through each item, an inside the each portion you do your ajax request to look for the current value, maybe using $.post() or $.get(), depending on your api.
Update: (Improving my answer)
I understand about the uniqueness of the id of an element in a document.
What I really wanted to say is that you may want change the approach on how to look/search for the details to include inside each span. There you can identify the span objects by grouping them using a Class or a custom attribute, then iterate them using the $.each function. There is no single way to accomplish things, this is just an idea on how to update each element with the correct content.
Related
I made a JavaScript code that I’m building to make a shopping cart, but this code is run even if I don’t click it:
function addProduct(prodId) {
var sessionDivId = document.getElementById(prodId);
if (prodId) {
sessionDivId.innerHTML = '<?= $_SESSION['product_id_1']+=1 ?>';
}
}
<div onclick="addProduct('testSession1');">ADD</div>
<div id="testSession1"></div>
Everytime I refresh the website it adds 1 to session testSession1 even if I don’t click the button “ADD”.
Your PHP logic will be run on the server before the user loads the page. To add a product, you will need to store it somehwere else (since the PHP has no longer any control to put +=1 to the cart).
I would make an AJAX request to post a product id to the user shopping cart:
function addProduct(prodId) {
// using jQuery for simplicity of writing
$.ajax({
type: "POST",
url: "/cart/item/" + prodId, // or other backend API endpoint
success: displayNiceUserMessage()
});
}
And of course some error handling in case something goes wrong.
Update
I saw that you did not want to use Ajax. Just so you know, it doesn't need to be any more complex than the code I wrote above. Then in the backend you just add +1 to the session if any user makes a POST request to that url.
But if you do not want ajax, you will need to reload the page when clicking the add button. Like was said in the comments, put a form of type post around the add button (and with a good url to make your server know that it was an added item event that took place), and make the add button a submit type. Then no javascript is needed at all.
I have a simple table with records and each of them has a btn with data-id attribute to run the confirmation dialog:
#foreach (var dog in Model)
{
<tr>
<td>#dog.Name</td>
<td>#dog.Age</td>
<td>Delete</td>
</tr>
}
After clicking the delete btn, this code is running :
$('.deleteBtn').on('click', function () {
$.ajax({
url: '#Url.Action("DeleteConfirm", "Home")',
data: {
id : $(this).attr('data-id')
},
success: function(data)
{
$('#myModal').empty().html(data).modal('show');
}
});
});
As you can see, its Ajax request to my Action in HomeController. It returns PartialView that is loaded to my Bootstrap dialog:
<div class="modal fade" id="myModal">
</div>
After showing the dialog, the user can click confirm to delete the row via button with class saveBtn. Thats what happens after I click it :
$('#myModal').on('click', '.saveBtn', function () {
var numer = $(this).attr('data-id');
$.ajax({
url: '#Url.Action("DeleteDog", "Home")',
type: 'POST',
dataType: 'JSON',
data: {
id: numer
},
success: function (data)
{
if (data = 'true')
$('a[data-id=' + numer + ']').closest('tr').remove();
}
});
});
So as you can see there is another Ajax (POST this time) request to delete the row.
So here is my question. Is this approach good practice? I'm not sure because in order to delete a row i have to send 2 ajax request (to load confirm dialog, and delete after confirm). Can anyone experience developer comment this code and say whether im doing it good or bad? I would be grateful.
It's always a good idea to challenge whether or not you could do things more effectively (as you have here.) So, let's think about it...
The Question:
Is it a good approach to send to two ajax requests - one to load a partial view and the second to post a delete request from the partial - for a single "user action"?
The Answer:
Maybe.
Why?
Based your example, if your goal is to simply confirm with the user whether or not they want to "Delete Dog ID: foo?" You can absolutely do that without making a trip to the server for a partial view. Presumably, in your first ajax call - $(this).attr('data-id'); - is the dog's Id. You already have it!
In most circumstances, when you make a get request with an identifier, like /dogs/id?='foo' you're using foo to access some additional information about the object from a persistent data store. Like, for example, the dog's owners, similar dog breeds, last visit to the vet, etc.
If additional information about the dog (owners, other dogs, vet) is an important part of deciding whether or not to delete the dog AND there's a good reason not to load it when the page loads intially then it totally makes sense to issue two ajax calls.
It could also make sense to issue two ajax calls just to get the partial view html, even if you don't need additional "dog" data, if you simply don't want the "parent" page to be to big (hence, slowing it's loading time.)
Ultimately, though if you're not retrieving additional data, and there's no specific reason to load additional html, it's probably best in this case to just update the modal dialog using javascript/jquery:
Example fiddle
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
I have a modal window that has a lot of new dynamic elements (inputs, buttons, etc.). I want to see if a certain element(or in this case, and input) gets created and if it does, then change its value.
The scenario is that if I make an ajax request for populating data, and as the user browses the modal window I can reuse some of that data. When the input field I'm looking for gets created, I can just put the value of the ajax call I made previously.
I have tried: $("#myinput_id").val(sellerData['id']);
obviously the above wont work because the element doesn't exists, yet. I'm also trying to avoid new ajax calls for the same data :/
Any thoughts?
$( "#add").bind('click', function() {
$.ajax({
url: '/seller/get',
type: 'POST',
success: function(response) {
sellerData = jQuery.parseJSON(response);
//other code here
//this doesn't work
$("#myinput_id").val(sellerData['id']);
}
});
});
Then the above gets triggers. The input field doesn't exist yet. How can I make it "look for it" if in the future the input field gets created?
Try using .length http://api.jquery.com/length/
if($("#myinput_id").length) //There is at least one element selected
//Do something
a bit confusing question you are saying u want to populate the data and your are using POST
It was suggested that I try to explain my problem with no code so here it goes. I have a webpage that lists a bunch of links with project names as seen in this jsfiddle. What I want to do next is display a second webpage after a project link is clicked by a user. The second webpage would need to make a second ajax request like in this Second page jsfiddle to get new information to display a project summary, citations and names for that particular project. The part that's killing me is the ajax request for the second page currently has a number 504216b6e4b04b508bfd333b in the url which means it will only use that project for the second page to display summary, citations and names. I need that ajax request to take a variable for any id number. However to compound the problem the id number comes from a user clicking a link on the first page. So my problem is getting the value of the id once a link is clicked and putting it into the ajax request for the next page. I have all the work done for what the pages will display but I can't get the value from the one file to the next. Any help is appreciated, Thanks.
wouldn't let me save without putting some code so this is just the bare bones,
// The ajax request is in another file but it works good
promise.done(function (json) {
// Make some links
// Which link was clicked? I need to see some id please
$('#sbItems a').on('click', function (e) {
e.preventDefault();
// Do stuff to find the id for the link the user clicked
// Assign the id to a variable that I can use in the next ajax request
// that is called in a seperate file
testId = json.items[itemId].id;
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
second file has,
// Need to somehow, someway get the testId variable that holds the id
// into this file
var url = 'https://www.sciencebase.gov/catalog/item/ + THE TESTID + ?format=
jsonp&fields=relationships,title,body,contacts';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
complete: onComplete,
success: function(json) {
// Display some stuff based off this url
}
});
If you're trying to get a number from the first page and into the second page when you click a link that takes you to the second page so you can use it in the second page ajax call, then there are several options:
Attach the value onto the URL when requesting the second page as a search parameter like this: http://www.sample.com/mypage?id=504216b6e4b04b508bfd333b. The in the second page, parse that id value out of the URL and use it for your ajax call. This is the safest of these three options because it works properly even if the user has multiple windows open clicking on different pages in your site.
When clicking on the link in the first page, store the id value as a cookie. In the second page, retrieve the id from the cookie.
Same as option 2, but store the value in local storage.