Insert a loading text message before a div gets populated? - javascript

I am tweaking my function below and had an issue. I'd like a loading text message to be inserted right before #project-container fills up with HTML and disappear once response has been inserted.
However, if I insert:
$('#project-container').html("my text here");
...right before:
$('#project-container').html(response);
Then, response doesn't show since the div is already populated with "my text here". Is there another method I can use?
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
$('#project-wrapper').addClass('activated');
$('#project-container').html(response); <---I want it inserted
$('.post-container').addClass('fadeInUp'); before this line.
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}

If you need a 'Loading' message, show it upon beforeSend event, and hide it on success:
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() { $('#project-container').html("Loading, Please wait"); },
success: function(response) {
$('#project-wrapper').addClass('activated');
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
See Ajax Events

You should probably add the loading message just before the AJAX call. It makes no sense to do it in the success callback, since the two operations will happen in the same cycle and chances are you'll always see just one. This should do it:
function projectShow() {
// add the initial text here
$('#project-container').html("my text here");
// add the initial class here for height issues from the comments
// $('#project-wrapper').addClass('activated');
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
$('#project-wrapper').addClass('activated');
$('#project-container').html(response); <---I want it inserted
$('.post-container').addClass('fadeInUp'); before this line.
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
As said in the comments, if you wish to keep the original text then append the response to it (either by using append(), or concatting them, or whatever method you like best).
See the both ways in action below:
function projectShow(keep) {
$('#project-container').html("my text here");
$.ajax({
type: 'POST',
cache: false,
url: 'http://hayageektest.appspot.com/cross-domain-cors/post.php',
//data: {'action': 'load-content', post_id: post_id },
success: function(response) {
//$('#project-wrapper').addClass('activated');
if (keep)
$('#project-container').append(response);
else
$('#project-container').html(response);
//$('.post-container').addClass('fadeInUp'); // before this line.
//$('.close-button').addClass('fadeOutDown');
//$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="projectShow()">Click me</button>
<button onclick="projectShow(true)">This one will keep the original! Click it. <br /></button>
<div id="project-container"></div>

Related

How to show loading icon when queries are executed in background?

I have AJAX request which runs when user click the button. I want to show loading icon during the execution of AJAX request. I used next code but it works not as I expected.
Let me try to explain the situation. When user click the button, in terminal I notice requests in the same time user don't see loading icon. When all requests are completed in terminal I see 200 OK status. Only after that I see icon but for shot time. So my question is how to show icon when queries are executed in background?
$("#btn").click(function(){
$.ajax({
url: "some url adress",
type: "post",
contentType: 'application/json; charset= utf-8',
dataType: 'json',
data: jsonData,
})
.always(function (dataOrjqXHR, textStatus, jqXHRorErrorThrown){
$('#loading-icon').fadeIn();
})
.done(function (data, textStatus, jqXHR) {
$('#loading-icon').fadeOut();
});
});
Your code in the always() handler will be executed once the request completes.
Start showing the loading icon before sending the request:
$("#btn").click(function(){
$('#loading-icon').fadeIn();
$.ajax({
url: "some url adress",
type: "post",
contentType: 'application/json; charset= utf-8',
dataType: 'json',
data: jsonData,
})
.done(function (data, textStatus, jqXHR) {
$('#loading-icon').fadeOut();
});
});
You create Simple funcetion like:
function loader() {
if ($('#dv_Loading').css('display') == 'none') {
$('#dv_Loading').fadeIn("slow");
}
else {
$('#dv_Loading').fadeOut('slow');
}
}
Use This funcation like:
$("#btn").click(function(){
loader();
$.ajax({
url: "some url adress",
type: "post",
contentType: 'application/json; charset= utf-8',
dataType: 'json',
data: jsonData,
success: function (data) {
loader();
}
});
});
Try this one
https://stackoverflow.com/questions/48611821/how-to-show-a-hidden-element-with-jquery/48611918#48611918
I hope works fine atleast for me
Similary in your case,
$("#btn").click(function(){
$.ajax({
url : "URL",
data: { data },
beforeSend: function(){
$("#loading-icon").show();
},
complete: function(){
$("#loading-icon").hide();
},
success: function (response) {
});
});
});

How prevent that an user change the input value?

I've a website with the post, and when an user comment its I send an Ajax request.
$(document).on('submit', '.theFormComment', function(e){
var data_to_send = $(this).serializeArray(); // convert form to array
data_to_send.push({name: "cs_spotale", value: $.cookie("c_spotale") });
$.ajax({
type: "POST",
url: '/post/addComment',
data: $.param(data_to_send),
dataType: 'json',
success: function(data){
console.log(data);
if(data.user_id !== data.user_to_id) {
$.ajax({
type: "POST",
url: "/notification/addNotification",
data: {
post_id: data.the_post,
user_from_id: data.user_id,
user_to_id: data.user_to_id,
action: data.action,
cs_spotale: $.cookie("c_spotale")
},
dataType: 'json',
success: function(x){
socket.emit('sendNotification', {data: data, type: x.type, image: x.image});
},
error: function(){}
});
}
$('#comment-box-'+ data.the_post).val('');
$("input[id='csrf_prot']").val(data.c);
$(data.html).prependTo("#comment-" + data.the_post);
if(data.own !== data.username){
socket.emit('notify', data.own, data.username);
}
socket.emit('updateComment', {permaRoom: data.the_post, html: data.html});
},
error: function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
I saw that if I change the input value of my hidden field "post_id", the comment goes to another "post_id". There is a way to prevent this problem? Or any other idea?

Jquery ajax post via link

I am trying to post via link. But I think there is a problem. I am not good at Javascript.
I want to send attribute and show with div.
Here is my Code :
<script type="text/javascript">
$(document).ready(function() {
$("#slidingProduct").click(function() {
var aa = $(this).attr('urun_id');
$.ajax({
url: "data.php",
dataType: "POST",
data: {
"number1": aa
},
success: function(json) {
$("#result").html(json.number1);
}
});
});
});
</script>
A
B
O
<div id="result"></div>
You can do something like this:
$(".slpd").on('click',function(){
var aa = $(this).data('urun_id');
var json={"number1":aa};
$.ajax({
url: "data.php",
type: "POST",
dataType:'JSON',
data: JSON.stringify(json),
success: function(result){
$("#result").html(result.number1);
}
});
});
As ids in DOM should be unique, you can specify similar class name to capture click event in a single go and
some modifications in html - It's good to use data-* property of html5:
A
B
O
$(document).ready(function() {
$("a").on('click', function(e) {
e.preventDefault(); // Stop redirection
var aa = $(this).attr('urun_id');
$.ajax({
url: "data.php",
type: "POST"
dataType: "JSON",
data: {
"number1": aa
},
success: function(response) {
$("#result").html(response.number1); // This depends on how you've sent response from server
}
});
});
});

Targeting the specific link that the user clicks

I have a page full of different links that each have a class of .post-link.
In the following function, I'd like the line $(this).html('loading...'); to target the specific .post-link div that is clicked. How would I go about achieving this? I feel I should create some sort of variable but I'm a bit lost. Any help would be appreciated.
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel');
var ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$(this).html('loading...'); <--line in question
},
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
Edit
Here is how my HTML is set up:
<a class="post-link"><img src="image.jpg"></a>
Using Alexander's solution, the "loading..." text shows up like this:
<a class="post-link"><img src="image.jpg">loading...</img></a>
Is there a way to make it show like this?
<a class="post-link"><span>loading...</span><img src="image.jpg"></img></a>
Of course given that I wrap the text in span tags?
Update
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel'),
ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$('<span class="loading">loading...</span>').insertBefore($(e.currentTarget).find('img'));
},
success: function(response) {
$('.loading').remove();
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
if ($(window).scrollTop() != 0) {
projectShow();
$('html, body').animate({
scrollTop : 0
},100);
} else {
projectShow();
}
});
Use
$('<span>loading...</span>').insertBefore($(e.currentTarget).find('img'));
or
$(e.currentTarget).prepend('<span>Loading</span>');
because this in beforeSend does not refer to element
You could try something like:
$('.post-link').click(function(e) {
e.preventDefault();
// set a variable as a reference to 'this'
// prefixing variables containing jquery object with a '$'
// as an easy way to spot them in your code
var $self = $(this),
post_id = $(this).attr('rel'),
ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$self.html('loading...');
// use if .post-link is a text element
$self.prepend('<span>loading...</span>')
// if your .post-link is an image
},
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
Although Alexander's answer is better as long as you don't override/re-declare the e
You may have overcomplicated it a bit. Why do it in beforeSend? Just do it like this:
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel');
var ajaxURL = site.ajaxurl;
// do it here:
$('#project-wrapper').addClass('activated');
$(this).find('img').before('<span>loading...</span>');
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
// I guess you are calling projectShow() somewhere in here
});
In browsers which support ES5 (IE >= 9), you can simply use .bind(this) to get context.
beforeSend: (function() {
$('#project-wrapper').addClass('activated');
$(this).prepend('<span>loading...</span>');
}).bind(this),
Try with this code
$(this).parent('.post-link').html('loading....');

refresh page with ajax jquery without use of reload function

I am performing delete records by using jquery ajax in php. I want to refresh that content without the use of location.reload() function. I tried this,
$("#divSettings").html(this);
but, it's not working. What's the correct logic to get updated content in div.
Thanks.
Code:
function deletePoll(postId){
$.ajax({
type: "POST",
url: "../internal_request/ir_display_polls.php",
data: {
postId: postId
},
success: function(result) {
location.reload();
//$("#divSettings").html(this);
}
});
}
You're almost there:
function deletePoll(postId){
$.ajax({
type: "POST",
url: "../internal_request/ir_display_polls.php",
data: {
postId: postId
},
success: function(result) {
$("#divSettings").html(result); // <-- result must be your html returned from ajax response
}
});
}
You just needed to set the result into your '#divSettings' element using the .html() function :
$('#divSettings').html(result);
So a full example would look like :
function deletePoll(postId){
$.ajax({
type: "POST",
url: "../internal_request/ir_display_polls.php",
data: {
postId: postId
},
success: function(result) {
//Sets your content into your div
$('#divSettings').html(result);
}
});
}
I believe you have to clear the section first and then you can attach the HTML again. Like
function deletePoll(postId){
$.ajax({
type: "POST",
url: "../internal_request/ir_display_polls.php",
data: {
postId: postId
},
success: function(result) {
//Sets your content into your div
$('#divSettings').html("");
$('#divSettings').html(result);
}
});
}
I believe this way you won't see the old content.

Categories

Resources