Refreshing Data Div inside Ajax request - javascript

I am trying to create a profile picture editor with a dropdown having two options:
Update your Profile Picture
If there is any profile picture it will show Delete options otherwise it will hide this options
template code:
<div class="dropdown-menu">
<a class="dropdown-item"><input name="input_file" type="file" id="profile-pic-upload" style="display: none;" />
<label for="profile-pic-upload">Upload Profile Picture</label>
</a>
{% if user_profile.profile_pic %}
<a class="dropdown-item delete" href="javascript:" style="font-size : 14px;">Delete</a>
{% endif %}
</div>
JS code:
$(".delete").click(function () {
$('.loading').show();
var url = "{% url 'user-profile-image-delete' %}";
$.ajax({
type: 'POST',
url: url,
data: $("#new_form").serialize(),
cache: false,
success: function (data, status) {
$('#imagePreview').css('background-image', 'url('+'{% static 'assets/img/user-64x.png' %}'+')');
if (data['status'] == "success") {
}
else {
toastr.error(data.msg);
}
}
});
});
$("#profile-pic-upload").change(function () {
var input_detail = this;
var data = new FormData();
var file = this.files[0];
data.append("file", file);
$.ajax({
type: 'POST',
data: data,
contentType: false,
processData: false,
url: $("#profile-file-upload").data('action'),
cache: false,
success: function (data, status) {
if (data['status'] == true) {
toastr.success(data.msg);
var randomId = new Date().getTime();
$('#imagePreview').css('background-image', 'url(' + data.profile_pic + '?random=' + randomId + ')');
}
else {
toastr.error(data.msg);
}
}
});
});
But I am facing one issue: even if I click the delete option the dropdown is not refreshing and it still shows an option for deleting it. It only goes once I refresh the page.
Same way if there is no profile picture it only shows Upload Profile pic. If I update an image the dropdown will not shows the delete option. To see this I need to refresh the page.
How to avoid page reload to refresh dropdown contents?

I understand your problem. You can easily solve this issue in your ajax call success.
What you need to do is just simple hide and show using jquery or javascript.
Lets say user already has a profile pic and the person clicks on delete option and ajax call is success then you should hide the delete option. (you can also remove it but later you will have to create it via javascript)
$(".delete").click(function () {
$('.loading').show();
var url = "{% url 'user-profile-image-delete' %}";
$.ajax({
type: 'POST',
url: url,
data: $("#new_form").serialize(),
cache: false,
success: function (data, status) {
$('#imagePreview').css('background-image', 'url('+'{% static 'assets/img/user-64x.png' %}'+')');
if (data['status'] == "success") {
//$(".delete").hide(); // this will hide your delete option
//Instead of hiding we are now removing the button then generating the button dynamically via javascript.
$(".delete").remove();
// But note one thing if we use class then it will hide/delete all elements with class of delete. so it's better to use id for unique elements.
}
else {
toastr.error(data.msg);
}
}
});
});
For the other case where there is no profile pic and the user updates profile pic then you should create a dropdown menu and append it to the dropdown.
$("#profile-pic-upload").change(function () {
var input_detail = this;
var data = new FormData();
var file = this.files[0];
data.append("file", file);
$.ajax({
type: 'POST',
data: data,
contentType: false,
processData: false,
url: $("#profile-file-upload").data('action'),
cache: false,
success: function (data, status) {
if (data['status'] == true) {
toastr.success(data.msg);
$(".delete").remove();
let dropdown_menu_item = '<a class="dropdown-item delete" href="javascript:" style="font-size : 14px;">Delete</a>'
$('.dropdown-menu').append(dropdown_menu_item);
var randomId = new Date().getTime();
$('#imagePreview').css('background-image', 'url(' + data.profile_pic + '?random=' + randomId + ')');
}
else {
toastr.error(data.msg);
}
}
});
});
this should work but i think you should handle that show or hide dropdown using javascript by checking first if the profile pic is updated if there then show delete button else hide the delete button and when user updates profile pic then show delete button.

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'
}
}
})
}

Change ajax default alert box style

Is there a way I could change the default ajax alert box? I currently have the code below, that deletes a user and reloads the current page. It works, but I would like to add some styling to the alert box that it triggers before the user is actually deleted.
function deleteUser(id) {
var action = confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
I tried changing the confirm to
function deleteUser(id) {
var action = bootstrap.confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
This displayed nothing.
You cannot style the custom confirmation box. It varies from browser to browser. If you want something custom you can build out one yourself using HTML and CSS. For example attach click events for yes button and for a no button and based on that you can make the delete

Updating Like Button without Refreshing The Page

Here's my Like button,
<a class="wst-click update_data" wst-href="{% url 'data:like' content.id %}" href="{% url 'data:like' content.id %}" >{{ data.likes.count }} Like</a>
This is what I'm doing for 'Like' functionality,
$('.wst-click').click(function(e){
e.preventDefault();
var this_ = $(this);
var wstURL = this_.attr('wst-href');
$.ajax({
url: wstURL,
method: 'GET',
data: {},
success: function (data) {
$('.update_data').text(data);
}
})
});
So, when I press the Like button instead of Returning the number of new Likes, it's returning the raw html code of entire webpage. How can I fix that?
It's working perfectly alright. I have added dummy example here.
<a class="wst-click update_data" wst-href="data/like/10" href="data/like/10" >11 Like</a>
$('.wst-click').click(function(e){
e.preventDefault();
var this_ = $(this);
var wstURL = this_.attr('wst-href');
$('.update_data').text('12 Like');
/*$.ajax({
url: wstURL,
method: 'GET',
success: function (data) {
var like_text = $(data).find('.update_data').html();
$('.update_data').html(like_text);
}
});*/
});
JSFiddle

Pass the link on blur function instead of clicking another link

I want to pass the link on textbox blur function.
Jquery code
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a> */* this is the link for get the profile details*/*
<script type ="text/javascript">
$('#getCandidate').text('Get Profile') // Sets text for email.
.attr('href', '#');
$("#Email").blur(function () {
$('#checkEmail').trigger('click');
//$('#checkEmail').trigger('GetCandidateDetail?validateEmail=' + $('#Email').val());
$('#getCandidate').text('Get Profile')
.attr('href', 'GetCandidateDetail?validateEmail=' + $('#Email').val());
});
$(document).ready(function () {
$('#checkEmail').click(function () {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
Html code
<%: Html.TextBox("Email",Model.Email, new {#title="Enter the Candidate Email Id"})%>
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a>
In the above code when I type the email id in textbox it triggers email id is registered or not. Then I give one more link getdetails. If I click that link then the profile will come by using the link GetCandidateDetail?validateEmail=' + $('#Email').val()).
But Now I want when I type the email id in textbox, if exists means it will load the link GetCandidateDetail?validateEmail=' + $('#Email').val())automatically otherwise false. How to do this? Help me to come out this issue?
You can do just like this:
$(document).ready(function() {
$("#Email").on('blur', function() {
// Check mail on blur
var email = $(this).val();
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: {validateEmail:email},
success: function(data) {
// handle your response
}
});
});
});
function verify() {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
return false;
});
}
$("#Email").blur(function(){verify();)
$("#checkEmail").click(function(){verify()})
thats it !!

Load jQuery Dialog with cascading dropdowns from server

I have a jQuery dialog that needs to be opened and populated with data from a database. The dialog has in it drop downs that when in a "new" mode (not editing for re-saving) cascade.
How can I load the dialog with the values from the database, while at the same time causing the cascading to happen.
I have tied using the onfocus event of the dialog when the dialog is in "edit" mode, but the focus hit every time an element gets focus. Didn't work without being sneaky with the editing mode.
I have tried opening the dialog and using jQuery to set the dropdown, which works, but then the cascading does work.
For the cascading I am using .change on the the different dropdowns.
Not sure if the code is going to help, but will post some to itterate the jQuery functionality I am using.
The question is: How do I open a dialog, load dropdowns with information from the server and have the .change functionality work?
$('#collectDD').change(function(){
// first change the item drop down list
var collection = $('#collectDD').val();
data = "coll=" + collection + "&action=getItems&func=";
$('#addCollection').text(collection);
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
$('#itemDD').empty();
$("#itemDD").html(html);
// now update the function collection dropdown
data = "coll=" + collection + "&action=getFunction";
}
});
Collection DD HTML
<select id="collectDD" name="collectionDD">
<option>Select Collection</option>
<option>Option1</option>
</select>
This doesn't exactly match up with your tag names, and I made a little change to the data string, but I think it's in line with what you're looking for
<div id="dialogbox">
<select id="s1"></select>
<select id="s2"></select>
<select id="s3"></select>
</div>
<script type="text/javascript">
$(document).ready( function() {
$( "#dialogbox" ).dialog({
open: function(event, ui) {
var s1 = $("#s1").empty();
var s2 = $("#s2").empty();
var s3 = $("#s3").empty();
s1[0].enabled = false;
s2[0].enabled = false;
s3[0].enabled = false;
//load first dropdown from the database
var data = "coll=dropdown1&val=&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s1.html(html);
s1[0].enabled = true;
}
});
//load the second DD when the first changes
s1.change( function() {
s2[0].enabled = false; //disable until after ajax load
s3[0].enabled = false;
data = "coll=dropdown2&val=" + s1.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s2.empty().html(html);
s2[0].enabled = true;
}
});
});
s2.change( function() {
if (s2[0].enabled) { //test for enabled to prevent some unnessecary loads
s3[0].enabled = false;
data = "coll=dropdown3&val=" + s2.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s3.empty().html(html);
s3[0].enabled = true;
}
});
}
});
}
});
});
</script>
UPDATE
Here is an example with change functions in their own functions
<div id="dialogbox">
<select id="s1"></select>
<select id="s2"></select>
<select id="s3"></select>
</div>
<script type="text/javascript">
var s1, s2, s3, data;
$(document).ready( function() {
s1 = $("#s1").empty();
s2 = $("#s2").empty();
s3 = $("#s3").empty();
$( "#dialogbox" ).dialog({
open: function(event, ui) {
s1[0].enabled = false;
s2[0].enabled = false;
s3[0].enabled = false;
//load first dropdown from the database
data = "coll=dropdown1&val=&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s1.html(html);
s1[0].enabled = true;
}
});
//load the second DD when the first changes
s1.change( changeDD1 );
//load the third DD when the second changes
s2.change( changeDD2 );
}
});
});
function changeDD1() {
s2[0].enabled = false; //disable until after ajax load
s3[0].enabled = false;
data = "coll=dropdown2&val=" + s1.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s2.empty().html(html);
s2[0].enabled = true;
}
});
}
function changeDD2() {
if (s2[0].enabled) { //test for enabled to prevent some unnessecary loads
s3[0].enabled = false;
data = "coll=dropdown3&val=" + s2.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s3.empty().html(html);
s3[0].enabled = true;
}
});
}
}
</script>

Categories