Changes done in ajax success not loading in page without refreshing - javascript

I have an ajax block in javascript, which does a few operations, and then changes a text box in my page.
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
var content_id = "count_" + count_id;
var votes = $(content_id ).val();
$(upvotes_id).html(votes);
//window.location.reload();
}
});
The content value is reflected only after I refresh the page. I tried setting cache parameter as false and alse the same in ajaxSetup when document is ready. Still the changes arent getting reflected. Please help.

It looks like your return variable 'data' isn't being referenced in the success function. As pointed out elsewhere, also missing an id or class reference. Try this (or any other relevant variables):
var content_id = "#count_" + data.count_id;

add hash to get value like
var votes = $('#'+content_id ).val();

i think you forgot add "#" before the id
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
var content_id = "count_" + count_id;
var votes = $('#'+content_id ).val(); // add hash for id or . for class
$(upvotes_id).html(votes);
//window.location.reload();
}
});

I am assuming upvotes_id is either id or class. Use $("#upvotes_id").html(votes) or $(".upvotes_id").html(votes) instead.same in the case of "content_id" .

I can see few issues with your code like- no '#' for referring an element.
corrections:
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
**var content_id = "#count_" + count_id;**
var votes = $(content_id ).val();
$(upvotes_id).html(votes);
//window.location.reload();
}
});
Also you have not mentioned how you are getting upvotes_id. Use # there too. You are not using the response returned in success method. Is it intended?

Related

(this).parent().find not working for getting response in ajax call

$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?

loading gif with ajax request

$(".content-short").click(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
success: function(response){
$(".content-full").html(response);
$('.loadingmessage').hide();
}
});
});
//collegeselect.php// is for loading data from database, //.loadingmessage// is for gif
when i am using this for the first time it displays gif,but the gif is not displayed after the 1st click as the data retrieved is already available in content-full from previous ajax request,
how to display it on every click on content short class?
That happens because you are replacing the actual content with loading GIF image with your response.
So, when you click first time it displayed and after the ajax call sucess as per the code you have replaced the content of .content-full and there is no GIF available then.
Solution : To resolve either send the same image tag with response or Move the loader image out side the .content-full.
Add beforeSend : function() before success in your request.
try
$(".content-short").live(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
beforeSend : function()
{
$('.loadingmessage').show();
},
success: function(response){
$(".content-full").html(response);
$('.loadingmessage').hide();
}
});
});
From the comments, I gather that the img is within the .content-full container. The problem is that the img is removed when ajax succeeds since you're doing $(".content-full").html(). One way to fix it is to move the img out of the container. Another way is to store a reference to the img and add it back along with the response via .append() or .prepend() as below.
$(".content-short").click(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
success: function(response) {
var $content = $(".content-full");
var $loaderImg = $content.find('.loadingmessage').hide();
$content.html(response).prepend($loaderImg);
}
});
});
Here is a demo mimicking the behaviour thru setTimeout.

AJAX request for many links

I'm new to jQuery AJAX. I want to build bookmarking system something like Twitter do (favorites). I have a lot of links. So it's not useful to write AJAX request for each link. That's why I want use just one request script for all links.
Let's say I have the links something link this:
<i class="icon-star-empty"></i>
<i class="icon-star"></i>
<i class="icon-star-empty"></i>
So I want to write AJAX request that do something like this when user clicks to one of those URLs.
if (class="icon-star-empty"){
ajaxURL = "/insertBoomark"
} else{
//it means class=icon-start
ajaxURL = "/deleteBookmark"
}
$.ajax({
url: ajaxURL,
type: "POST",
data: {id : linkID}, // I don't know how to get linkID too :(
success: if class was icon-star empty then change it to icon-star-empty else change it to icon-star
});
I know that is not correct syntax.
How can I solve this problem? Please help :(
Thanks in advance.
$("i").on("click", function() {
if ( $(this).hasClass("icon-star-empty") ){
ajaxURL = "/insertBoomark"
} else{
//it means class=icon-start
ajaxURL = "/deleteBookmark"
}
var linkID = $(this).parent().prop("id");
var obj = $(this);
$.ajax({
url: ajaxURL,
type: "POST",
data: {id : linkID},
success: function() {
obj.hasClass("icon-star") ? obj.removeClass("icon-star").addClass("icon-star-empty") : obj.removeClass("icon-star-empty").addClass("icon-star");
}
});
})
You can also use the href attribute and just prevent the default action from the jquery event.
html
javascript
$(function(){
$(document).on('click','a',function(e){
e.preventDefault(); //prevent default click action
var $this = $(this); // keeps "this" accessable
var ajaxURL = $this.attr('href'); // get the url from the "a" tag
$.ajax({
url: ajaxURL,
type: "POST",
data: {id : linkID},
success: function() {
if($this.hasClass("icon-star"))
$this.removeClass("icon-star").addClass("icon-star-empty");
else
$this.removeClass("icon-star-empty").addClass("icon-star");
}
});
});
});
$('a').click(function(){
var _ajaxURL,
_self = $(this);
if($(this).hasClass('icon-star-empty')){
_ajaxUrl = "/insertBookmark";
}else{
_ajaxUrl = "/deleteBookmark";
}
$.ajax({
url: _ajaxUrl,
type: 'POST',
data: {id : $(this).prop('id')},
success: {
//I have no idea what you want to do right here.
}
});
});
Okay, first, class is a reserved name in javascript.
Secondly, if you're doing it with a jQuery.click function, then you can just do $(this).attr('id') to get the id.
Also, for the success part, you seem to be confused about javascript's function syntax. What exactly are you trying to do?

Ajax (this) not working

When attempting to access the '.box' class of the $container, using (this) inside of the ajax call doesn't work.
$container.on(
"click",
".box",
function(event){
var description;
if($(this)[0].style.width == '70%'){
$(this).find(".resultData").fadeOut('slow');
$(this).css('width', '18%');
}else{
$.ajax({
url:'scripts/php/fetchResultsData.php',
data: {action:value},
type: 'post',
dataType: 'json',
success: function(data){
description = data[0];
$(this).css('width', '70%');
$(this).append("\
<div class='resultData'>\
<div class='resultName'>" + $(this).find("p").html() + "</div>\
<div class='resultDesc'>" + description +"</div>\
</div>");
/*alert($(this).find("p").html());*/
}
})
}
$container.masonry('reload');
}
);
In case it's not clear what I'm trying to do, I'm attempting to change the css of dynamic elements. But for example,
$(this).css('width','70%');
Isn't adjusting the css at all. If I move it outside the ajax,success section, it works, but then I'm unable to get 'description'.
You're close. 'this' in the context you are using it, refers to the ajax request rather than the thing that issued the event. To fix this, store a copy of this before making the ajax request:
}else{
var me = this;
$.ajax({
...
success: function(data){
description = data[0];
$(me).css('width', '70%');
Just add this to your $.ajax call...
context: this,
...and it'll work.
$.ajax({
context: this, // <-- right here
url:'scripts/php/fetchResultsData.php',
data: {action:value},
type: 'post',
dataType: 'json',
success: function(data) { // ...

the id of the element won't change in jquery?

i.e.
$("#savenew").live('click', function(e) {
var user=<?php echo $user?>;
$.ajax({
type: "POST",
url: "actions/sub.php",
data:{user: user} ,
success: function(){
$('#savenew').html('<span>Unsubscribe</span>');
$(this).attr('id', 'clean'); // this my problem my problem
}
});
});
the id after the ajax request, is not changing from savenew to clean, but the html is perfectly fine, so i know the ajax request is working. what do u thiunk the problem is?
You just need to save the context (via the context option for $.ajax()) so this still refers to #savenew, like this:
$("#savenew").live('click', function(e) {
var user=<?php echo $user?>;
$.ajax({
context: this, //add this!
type: "POST",
url: "actions/sub.php",
data:{user: user} ,
success: function(){
$(this).attr('id', 'clean').html('<span>Unsubscribe</span>');
}
});
});
Also note that this allows you to chain and clean things up a bit.
$(this) inside success: function(){ does not refer to $('#savenew').
As you do in the line above, you need to reference it by id:
$('#savenew').attr('id', 'clean');

Categories