Comment reply not display properly by JS - javascript

For prevent the refresh of the page after submitting the form I want to add return false;
Also have default browser behavior problem to refresh this page.
But if I add return false; or e.preventDefault(); reply of any comment show duplicate under only last/top/new comment AND after a refresh Its show original comment. not only that delete comment show loader continuously.
Now I think my problem either my html structure or JavaScript.
HTML of index.php:
<div class="content"><comment>
<div class="post'.$id.'">
//here main comment goes on
</div>
<div class="reply'.$id.'" id="replynext"><ul>
//here reply goes on
</ul></div>
<comment></div>
HTML of Reply.php:
<div class="reply'.$id.'" id="replynext"><ul>
//new reply goes here
</ul></div>
JS for reply without return false;:
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
function updateReplybox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
$.ajax({
type: "POST", url: "reply.php", data: "action=update&tutid="+ tutid,
complete: function(data){
var RID = $(this).attr('class').replace('reply','');
$(".reply"+RID).append(data.responseText);
$(".reply"+RID).fadeIn(2000);
}
});
}
//on submit reply
$(".repfrm").click(function(){
error.fadeOut();
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$(".loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author="+ author + "&replycom="+ replycom + "&url="+ url + "&img="+ img + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
$(".reply"+RID).append(data.responseText);
updateReplybox();
//reactivate the send button
}
});
error_message();
//we prevent the refresh of the page after submitting the form
});

Related

AJAX call not working on EJS multiple forms (works just on the first form)

I have a like button on multiple posts, in EJS. Problem is, when I am clicking the first like button, the form sends and updates the View accordingly.
When I click the other buttons they all seem to send and update the first form, and they also update the first button adding the 'active' class to it.
I tried deleting the IDs and adding classes, still same result.
My guess is there is a fault in my AJAX or HTML structure because form is updating the database with no problem.
HTML:
<form id='like' action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST">
<% if (blogposts[i].liked == false) {%>
<div id='likeBtn' onclick="Like()" class="wrapperHearts">
<svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
</div><%}%>
<% if (blogposts[i].liked == true) {%>
<div id='likeBtn' onclick="Like()" class="wrapperHearts active">
<svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
</div><%}%>
</form>
AJAX:
let likeButton = document.querySelector('.wrapperHearts');
let frm = $('#like');
function Like(){ frm.submit()}
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData(this);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log("success");
console.log(data)
if (data.liked == false){
likeButton.classList.add('active')
$("#likesNumber").text(data.likes +1 + ' ' + 'Likes')
}
else{
likeButton.classList.remove('active')
$("#likesNumber").text(data.likes -1 + ' ' + 'Likes')
}
},
error: function(request, status, error) {
console.log("error")
}
});
});
In the form I am using method-override.
I have assigned the EJS dynamic ID to the rendered forms, and then I have created a function which triggered on event, gets the ID of the specific form and assigns it into the AJAX call.
HTML
<form class="likeForm" id="like<%=[i]%>" action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST" onsubmit="postData(event, this.id)">
More details
var elem = $('#'+id)[0]; // I took the HTML form element in order to assign it to the new form data as seen below
var formData = new FormData(elem)
var fullDiv = $('#'+id)
var likeButton = fullDiv.find('.wrapperHearts')
var likesNumber = fullDiv.find('.likesNumber')
//Used the find() method in order to find the specific element that I want to be updated in real time.
AJAX
function postData(event, id) {
event.preventDefault(event)
var elem = $('#'+id)[0];
var fullDiv = $('#'+id)
var likeButton = fullDiv.find('.wrapperHearts')
var likesNumber = fullDiv.find('.likesNumber')
var currentUserId = <%-JSON.stringify(currentUser._id)%>
console.log(currentUserId)
var formData = new FormData(elem)
console.log(likeButton)
console.log(likesNumber)
$.ajax({
async: true,
type: elem.getAttribute("method"),
url: elem.getAttribute("action"),
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if(!data.userLikes.includes(currentUserId)){
likeButton.addClass('active')
likesNumber[0].innerHTML = data.likes + 1 + ' ' + 'Likes'
}
else{
likeButton.removeClass('active')
likesNumber[0].innerHTML = data.likes - 1 + ' ' + 'Likes'
}
}
})
}

Only add data to ajax call if it isnt a null value

I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});

How do I exit the click function?

So with this example I have form with a hidden field and a button called ban user. When the ban user button is clicked, it submits the value in the hidden field and sends the ajax request to a java servlet. If it is successful, the user is banned and the button is changed to "unban user". The problem is when I click the button once and ban a user and I try to click it again to unban, I'm still inside the click event for the ban user and I get the alert "Are you sure you want to ban the user with the id of ...?". How do I exit the click event to make sure when the button is clicked a second time, it starts at the beginning of the function and not inside the click function? I have tried using 'return;' as you can see below but that doesn't work.
$(document).delegate('form', 'click', function() {
var $form = $(this);
var id = $form.attr('id');
var formIdTrim = id.substring(0,7);
if(formIdTrim === "banUser") {
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(7);
var dataString = $form.serialize();
var userID = null;
userID = $("input#ban"+ trimmed).val();
$("#banButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to ban the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserBan",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#banUser'+trimmed).attr('id','unbanUser'+trimmed);
$('#ban'+trimmed).attr('id','unban'+trimmed);
$('#banButton'+trimmed).attr('value',' UnBan User ');
$('#banButton'+trimmed).attr('name','unbanButton'+trimmed);
$('#banButton'+trimmed).attr('id','unbanButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
else if(formIdTrim === "unbanUs") {
//Stops the submit request
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(9);
var dataString = $form.serialize();
var userID = null;
userID = $("input#unban"+ trimmed).val();
$("#unbanButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to UNBAN the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserUnban",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#unbanUser'+trimmed).attr('id','banUser'+trimmed);
$('#unban'+trimmed).attr('id','ban'+trimmed);
$('#unbanButton'+trimmed).attr('value',' Ban User ');
$('#unbanButton'+trimmed).attr('name','banButton'+trimmed);
$('#unbanButton'+trimmed).attr('id','banButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
});
Try with:
$("#banButton"+ trimmed).off('click').on('click', (function(e){......
I had similar problem and this was solution

HTML5 Form Submit

I am trying to get a form to submit an action to an ip address without open the ip address.
So, when I hit the submit button I want it to send the post command to the ip (in this case 192.168.0.1) and just refresh the current page.
<div data-role="main" class="ui-content">
<form method="POST" action="http://192.168.0.1/">
<input type="submit" name="parser" value="thisguy"/>
</form>
</div>
My script that runs on submit:
<script src="http://ajax.googleapis.com/ajax/liubs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data - {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
return false;
});
</script>
Right now it submits the post and tries to open 192.168.0.1 as a webpage. Can someone help me out either by providing code with an explanation or pointing me to the command?
Any help is appreciated.
You need to prevent the default action (using e.preventDefault())
$('form.ajax').on('submit', function(e) {
e.preventDefault(); // Prevent default submit action (that is, redirecting)
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
return false;
});
Well, you can refresh the page after the POST is done in success method
success: function(response) {
window.location.reload();
}
Also do not forget to disable the form default behavior with
$('form.ajax').on('submit', function(event) {
event.preventDefault();
.
.
});
See documentation for more info
To enable debugging, you should wrap the whole submit handler in a try/catch because without it, errors will cause the default handler to submit the form, masking the errors. After the try/catch you can return false, so the page stays put.
<script src="http://ajax.googleapis.com/ajax/liubs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$('form.ajax').on('submit', function() {
try {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data - {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
}
catch (err) {
console.log( 'submit handler error: ' + err.message );
}
return false;
});
</script>
You just had couple of typo, like - instead of = and extra :, else your code is fine, below is working example.
$(function(){
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
alert('posted')
}
});
});
return false;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div data-role="main" class="ui-content">
<form method="POST" action="http://192.168.0.1/" class="ajax">
<input type="submit" name="parser" value="thisguy"/>
</form>
</div>
My script that runs on submit:
I have done correction to your code.
<script language="javascript" type="text/javascript">
$('form').on('submit', function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {}
});
});
return false;
});
</script>

How can i prevent page from jumping to bottom?

The page is jumping to the bottom when the submit button is pushed on the contact form. I think this is caused by js. When you want to try it, push the link below, next contact, fill in the form and press "verstuur"
http://expertlemmer.nl/PC-laptop-reparatie-Lemmer/
javascript:
$('form#contactForm button.submit').on('click', function() {
$('#image-loader').fadeIn();
var contactFname = $('#contactForm #contactFname').val();
var contactLname = $('#contactForm #contactLname').val();
var contactStraat = $('#contactForm #contactStraat').val();
var contactPostcode = $('#contactForm #contactPostcode').val();
var contactTel = $('#contactForm #contactTel').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactFname=' + contactFname + '&contactLname=' + contactLname +
'&contactEmail=' + contactEmail + '&contactSubject=' + contactSubject +
'&contactStraat=' + contactStraat + '&contactPostcode=' + contactPostcode +
'&contactTel=' + contactTel + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
Hello i was on your webpage. And you are using in your script :
$('form#contactForm button.submit').on('click', function() {
e.preventDefault();
// and so on
The problem is that, you do not pass the e in the function. You have to use it like this :
$('form#contactForm button.submit').on('click', function(e) {
e.preventDefault();
// and so on
Then it will prevent the form from refreshing the page. I am just guessing that you want to send the form through ajax.
Your form has no "ACTION" attribute, this means it's posting to the current URL. The current URL has an anchor : #contact, this means you'll jump straight to the contact part.
See what you get when you go into this link and scroll down(Scroll, don't click contact), you'll jump to the review section.
http://expertlemmer.nl/PC-laptop-reparatie-Lemmer/#journal
Long story short, Put an action tag on your form :)

Categories