I wish to replace values in each div class with my ajax result but i cannot seem to append my table result to the individual div class during the loop. I know somehow the $(this).append(table) is placed wrongly because it is not outside of the ajax request. How can i modify this to get the effect i wanted?
my script is as such:
$('.developer_badgesarea').each(function(){
// get the div class value to perform ajax
var player_id = $(this).html();
var table;
// if condition to conduct ajax
if(player_id != 'None'){
$.ajax({
// ajax stuff here
success: function(result){
//table created here
$(this).append(table);
}
});
}
});
Issue is your "this" reference inside the ajax success function. It references the callback function, instead of the dom element you are intending it to be referenced.
$('.developer_badgesarea').each(function(){
// element reference to your div, that you'll access inside your ajax call
var elm = $(this);
// get the div class value to perform ajax
var player_id = elm.html();
var table;
// if condition to conduct ajax
if(player_id != 'None'){
$.ajax({
// ajax stuff here
success: function(result){
//table created here
elm.append(table);
}
});
}
});
Related
I am doing an ajax call and replacing the response inside a div class. At the first ajax call the response is replaced inside the class properly but 2nd time I got the data from response but the response in not replacing the data inside the class.
I am trying the below way.
$(document).on('click', '#approveallusers', function(){
var checked_ids = []
$("#UserList").find('input[type=checkbox]').each(function () {
var $this = $(this);
if($this.is(":checked") && $this.hasClass('selectbox')){
checked_ids.push($this.attr("userid"));
}
});
$.ajax({
url : '/approve-website-users',
method : 'POST',
data : JSON.stringify({'checked_ids':checked_ids}),
contentType : "application/json",
success : function(data) {
if(data.status == 'success') {
alert(data.res)
$('.users').replaceWith(data.res);
}
}
});
})
here data.res is an html element and its rendering from the server side.
Thanks..
.replaceWith will replace the div including html tags so there won't be any class users.
see this for more info:
http://api.jquery.com/replacewith/#replaceWith-function
maybe you need .innerHTML or .html
check here: http://api.jquery.com/html/#html-htmlString
On my page I want the user to be able to mouseover a td element, have the page make an Ajax call to the server, and then append a title attribute to the td to serve as a tooltip for the remainder of the time the user is on the page.
The information the page needs to retrieve is very basic so there's nothing too complicated about this... however I cannot get the code to append the data I receive from the Ajax call onto the td element.
Jquery/Ajax
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '#Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title'));
});
Unfortunately I can see, in the console, the 'ajax' entry, followed by the exact value I'm expecting for the data object, but undefined appears as the value for the td title attribute from the final console.log statement (end of the mouseover).
HTML/Razor
<td class="ChannelCodeDesc">
#Html.DisplayFor(model => model.displayForPaging[i].ChannelCode)
#Html.HiddenFor(model => model.displayForPaging[i].ChannelCode)
</td>
Ajax Controller Method
public JsonResult GetDesc(string channel)
{
var description = (from c in db.Channel
where c.ChannelCode.Equals(channel)
select c.ChannelLongDescription).FirstOrDefault();
return Json(description, JsonRequestBehavior.AllowGet);
}
The problem is that the this object in the success function is not the td element. By default the context of the jquery ajax callbacks is set as an object representing the ajax options. However you can change that using the context option:
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '#Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
context: this, //make sure "this" inside the success callback is the td element
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title')); });
I am assuming that the data returned by Ajax is valid....
the $(this) within success does not refer to the td anymore.
do this outside the ajax call:
var me = $(this);
Then in your success code do this:
me.attr('title', data);
The final console.log statement shows undefined because it occurs before the AJAX request is complete (because AJAX requests are Asynchronous).
Also, a td can't have a title attribute, might need to look at a different option:
how to apply style to 'title' attribute of 'td' tag
And others have stated, can't use $this inside the ajax success function like that.
I am using following JavaScript code inside a page. The problem is that the code gets executed for the first time and fetches data from from elements.
During the subsequent calls, the changed data in the form elements is not available to this function as it uses data from its maiden call.
$(document).ready(function() {
$('<textarea id="message-clone"></textarea>').insertAfter("#form-message-compose");
var saveDraft = function () {
var originalStriped = $("#wysiwyg").val().replace(/(<([^>]+)>)/ig,"");
if((originalStriped.length) > 10) {
var input = $("<input>").attr("type", "hidden").attr("id", "savedraft")
.attr("name", "submit").val("savedraft");
$.ajax({
type: "POST",
url: $("#form-message-compose").attr("action"),
data: $("#form-message-compose").append(input).serialize(),
success: function(result){
var result = JSON.parse(result);
$("#subject").val(result.message_subject);
$('input[name="draft"]').val(1);
$("#id").val(result.message_id);
var flash = '<div id="flash" class="alert alert-success"><a data-dismiss="alert" class="close">×</a><strong>Yay!</strong> Message Auto saved to drafts!</div>';
$("#page-title").append(flash);
$("#flash").fadeOut(3000, function() { $(this).remove(); });
$("#savedraft").remove();
$("#message-clone").val($("#wysiwyg").val().replace(/(<([^>]+)>)/ig,""));
}
});
}
}
setInterval(saveDraft(), 2000);
});
The problem here is that for the first time, the function fetches correct data from input element #wysiwyg but during the subsequent, it doesnot update the data from the call $('#wysiwyg').val() which results in single execution of the code inside if block.
Kindly guide, where I am doing wrong.
setInterval(saveDraft(), 2000);
should be
setInterval(saveDraft, 2000);
The first argument of setInterval should be a function. You are not passing a function, what you're doing is executing saveDraft and passing the result as an argument.
The issue was with the Tiny MCE I was using. So instead of trying to get the value of texte area by
var originalStriped = $("#wysiwyg").val().replace(/(<([^>]+)>)/ig,"");
I had to use the tinyMCE method to fetch the text
var originalStriped = tinyMCE.get("wysiwyg").getContent({format : "text"});
Another problem with TinyMCE is that it doesnot update the data in textarea on an AJAX call, which otherwise, it does on form submit. So I had to call the trigger the save on tinyMCE manually by calling
tinyMCE.triggerSave();
And then firing the AJAX request with form data.
I use the jquery .load function to load a divs(left) from a other page inside a div(page_content) on the current page but when i use the load function to load a other div(right) in page_content it overwrites everyting inside the div(page_content).
And i just want it to be added to the div.
here is my code:
function load(){
$('#page_content').load('test.php .left');}
function load2(){
$('#page_content').load('test2.php .right');
}
You can use the callback function to convert two call to single call and get the .left and right content in the call to assign to your element with id page_content,
$('#page_content').load('test.php', function(result){
leftContent = $(result).find('.left').html();
leftRight = $(result).find('.right').html();
$(this).html($(leftContent + leftRight ).find('')
});
try this instead
function load(){ $('#page_content').load('test.php .left');}
$.ajax({
url: 'test2.php .right',
success: function(data) {
$('#page_content').append(data);
}
});
In my html page, I have a select with some options.
When selecting an option, an ajax call is fired passing the option's value to a php script, which returns an html fragment (another select) with a certain id that is appended to the page.
When the user selects another option from the first select, the event is fired again, the ajax call is executed and another html fragment (with the same id) gets appended to the page.
I want that, if the event is fired a second time, the appended element is removed form the page before appending the new one.
At the moment I'm using this code:
$(document).ready(function() {
$("#id_serie").change(function() { //#id_serie is the if of the first select
if ($("#id_subserie_label")) { //#id_subserie_label is the id of the html element returned by the ajax call
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
This is not working though, the html element returned by the second ajax call is appended after the element returned from the first call (because the element with id #id_subserie_label is not in the page when the script is loaded?).
How can I achieve what I need?
You're very close.
Just change if ($("#id_subserie_label")) to if ($("#id_subserie_label").length):
$(document).ready(function() {
$("#id_serie").change(function() {
if ($("#id_subserie_label").length) { // <=== change this line
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
See The jQuery FAQ: How do I test whether an element exists?.
This is because, as Ivo points out:
$("#id_subserie_label") is an object, and objects always evaluate to true.
As per Andy E's comment, you can simplify your code to this, if you don't need the console.log() call:
$(document).ready(function() {
$("#id_serie").change(function() {
$("#id_subserie_label").empty().remove();
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});