jQuery delete and fade - ajax

Im using jQuery to delete and fade the item container. This code will delete and fade div class box2. what i want to do this to fade div class box1. without changing the delete link to box1.
if anyone can point me out how to do this, highly appropriated. thanks in advace.
<div class="box1">
<div class="box2">
x
</div>
</div>
JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('#load').hide();
});
$(function () {
$(".delete").click(function () {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id=' + id;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function () {
commentContainer.slideUp('slow', function () {
$(this).remove();
});
$('#load').fadeOut();
}
});
return false;
});
});
</script>

Try this code :
$(function() {
$('#load').hide();
$('.delete').click(function(){
$('#load').fadeIn();
$(this).parent().slideUp('slow', function () {
$('.delete').appendTo('.box1')
$(this).remove();
$('#load').fadeOut();
});
return false;
})
})

If you change it to var commentContainer = $(this).parent().parent();. It will now target .box1. You can then unwrap .box2 :
commentContainer.slideUp('slow', function() {
$('.box2').unwrap();
$(this).remove();
});

I believe you want
var commentContainer = $(this).parent().parent();
to get to .box1 and not .box2 Does that solve the problem?
Just a couple of comments though. A valid id should start with an alphabetic character. The digit '1' is not valid. 'a1' would be better, or just 'a'. Also use the ajax callback done rather than success as it is currently deprecated.

Related

does not capture a class in ajax

I'm having trouble changing a class with ajax, it works with the boton class but not with the boton_clic_sin class, please, someone who can help me. Thank you
$(document).ready(function() {
$('.btnguardar').on('click', function(e) {
e.preventDefault();
var $container = $(this).closest(".container");
var id_oferta = $container.find(".id_oferta").val();
var url_img = $container.find(".url_img").val();
var $boton = $(this).closest('.boton');
var $boton_clic_sin = $(this).closest('.boton_clic_sin');
$.ajax({
type: "POST",
url: "app/ofertasguardadasController.php",
data: {
id_oferta,
url_img},
success: function(r) {
if (r==1) {
$('.aviso').empty();
$('.aviso').append('Se agrego a la lista Ver lista').fadeIn("fast");
$('.aviso').fadeOut(7000);
$boton.addClass('deshabilita');
$boton.attr('disabled', 'disabled');
$boton_clic_sin.addClass('.habilita');
$('.lista').html("Ver lista").fadeIn("slow");
$('.title_lista').html("Agregado a la lista").fadeIn("slow");
}
}
});
});
});
Html
<span class="boton_clic_sin">♥</span>
<button id="btnguardar" class="boton btnguardar">♥</button>
If your span is located just before your button you can use prev() to get that element and use toggleClass to add or remove the added class.
Demo Code(I have removed some code which was not needed ) :
$('.btnguardar').on('click', function(e) {
//find button prev element ->span
var $boton_clic_sin = $(this).prev();
//use toggle to add or remove class
$boton_clic_sin.toggleClass('habilita');
});
.habilita {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="boton_clic_sin">♥</span>
<button id="btnguardar" class="boton btnguardar">♥</button>
You can change a class to your span element by using this $('.boton_clic_sin').addClass('habilita'); and $('.boton_clic_sin').removeClass('habilita');
Instead of doing this stuff var $boton_clic_sin = $(this).closest('.boton_clic_sin');, and a toggleClass
e.g.
$('.btnguardar').bind('click', function(e) {
if($('.boton_clic_sin').hasClass('habilita')){
$('.boton_clic_sin').removeClass('habilita');
}else{
$('.boton_clic_sin').addClass('habilita');
}
});
.habilita{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="boton_clic_sin">♥</span>
<button id="btnguardar" class="boton btnguardar">♥</button>

I'm trying to automatically reload a div after some seconds but it doesn't work in Chrome

Here is the Main code. Please check it. what is making this conflict.
<script type="text/javascript">
$(document).ready(function ()
{
setInterval(function()
{
$.get("ajax_files/manage_friend_requests.php", function (result)
{
$('#all_friends_requests').html(result); // This is the div i am reloading again and again after some seconds.
});
}, 9000);
});
</script>
You should be safer with something like this:
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: "GET",
url: "ajax_files/manage_friend_requests.php"
}).done(function(result) {
var $friends_requests = $('#all_friends_requests');
if ($friends_requests.length > 0) {
console.log('Received: '+result);
$friends_requests.html(result);
console.log('UPDATED friends requests');
} else {
console.log('CANNOT access friends requests container');
}
});
}, 9000);
});
Depending on what the console will display, you will probably put the issue in evidence.

jQuery ajax - outputting files from an ajax request

is it possible to output a file as a response from a ajax call?
i've wrote a function for outputting zip files using an ajax call, this is the code:
<script type="text/javascript">
$(document).ready(function () {
$(".ziplink").click(function (e) {
e.preventDefault();
var url = $(this).attr('href');
var spinner = $(this).parent().children(".spinnerbox");
spinner.show();
$.ajax({
url:url,
type:"GET",
dataType:"application/x-zip-compressed",
success:function (data) {
console.log('success');
spinner.hide();
},
error:function () {
console.log('ko');
spinner.hide();
}
});
});
});
</script>
now, from the firebug console everything is ook, but i dont have file output. what is missing?
Although this is fully functional in the non-ajax way (a simple link to the action), i'd like to have the spinner animation while server process the request.
thanx - LuKe
$(".ziplink").click(function (e) {
e.preventDefault();
var _self = $(this);
$('.spinner').show();
$.ajax({
type : 'HEAD',
url : _self.attr('href'),
complete : function(){
$('.spinner').hide();
var _tmp = $('<iframe />')
.attr('src', _self.attr('href'))
.hide()
.appendTo(_self)
setTimeout(function(){
_tmp.remove();
},5000);
}
});
});
Demo http://jsfiddle.net/4sMsr/3/

subpage loaded through ajax is killing jquery functionality

I'm working on a site, http://teneo.telegraphbranding.com/, and I am hoping to load the pages via ajax so that the sidebar and its animation remain consistent.
When the 'About' link is clicked I need it to load about2.php via a jquery ajax function. But I'm not having any luck. When I can get the page to load via ajax it kills all the jquery functionality on the page. From what I've read I think I need to call the jquery upon successful completion of the ajax call.
I've tried everything it seems and can't get it work. What I need is about2.php to load when the link is clicked and the jquery to dynamically size the divs, like it does on the homepage.
I tried this, but it won't even load the page:
//Dropdown
$(document).ready(function () {
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
var url = 'about2.php'
$.get(url, function(data) {
//anything in this block runs after the ajax call
var missionWrap = $('#mission-wrap');
var w = $(window);
w.on('load resize',function() {
missionWrap.css({ width:w.width(), height:w.height()});
});
var missionContent = $('#mission-content');
var w = $(window);
w.on('load resize',function() {
missionContent.css({ width:w.width() - 205 });
});
});
});
});
});
And then this loads the page, but kills all the jQuery associated with it:
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
$('#index-wrap').load('/about2.php');
});
});
Thank you very much.
I also tried this and it just broke everything:
$(document).ready(function () {
var dropDown = $('.dropdown');
$('h3.about').on('click', function () {
dropDown.slideDown('fast', function () {
$.ajax({
type: 'GET',
url: 'about2.php',
success: function () {
var missionWrap = $('#mission-wrap');
var w = $(window);
w.on('load resize', function () {
missionWrap.css({
width: w.width(),
height: w.height()
});
});
var missionContent = $('#mission-content');
var w = $(window);
w.on('load resize', function () {
missionContent.css({
width: w.width() - 205
});
});
};
});
});
});
});
This should work.
function resize_me () {
var w = $(window);
var missionWrap = $('#mission-wrap');
var missionContent = $('#mission-content');
missionWrap.css({ width:w.width(), height:w.height()});
missionContent.css({ width:w.width() - 205 });
}
//Dropdown
$(document).ready(function () {
$(window).on('load resize', function () {
resize_me();
});
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
var url = 'about2.php'
$.get(url, function(data) {
resize_me();
});
});
});
}
I believe that the problem was that the load event that you were attaching to the window object was not being triggered by the successful load of the $.get.
This is a rough outline of how to structure your application to handle this correctly.
Assuming your HTML looks something like this:
<html>
...
<div id="index-wrap">
<!-- this is the reloadable part -->
...
</div>
...
</html>
You need to refactor all the jQuery enhancements to the elements inside #index-wrap to be in a function you can call after a reload:
function enhance(root) {
$('#some-button-or-whatever', root).on('click', ...);
}
(I.e. look up all the elements under the root element that was loaded using AJAX.)
You need to call this function when the page is first loaded, as well as after the AJAX call in the completion callback:
$('#index-wrap').load('/foo.php', function() {
enhance(this);
});
You can also potentially get rid of some of this using delegated ("live") events, but it's best to hit the jQuery documentation on how those work.
As for events bound to window or DOM elements which aren't loaded dynamically, you shouldn't need to rebind them at all based on which subpage is loaded, just check which of your elements loaded is in a handler that you set up once:
$(window).on('load resize', function() {
var $missionContent = $('#missionContent');
if ($missionContent.length) {
$missionContent.css(...);
}
});

$.submit form and replace div using ajax has strange jquery behaviour on the new partialview

I think the problem is with jQuery, i don't know for sure.
Let me explain the situation.
Screenshot 1
I fill in the partialView and click on submit.
The submit is a jQuery event handler with the following code:
_CreateOrEdit.cshtml
<script type="text/javascript">
$(document).ready(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
});
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
$.post(action, serializedForm, function (data) {
$("#main-content").html(data);
});
return false;
});
</script>
This all works fine on the first-run.
Then when i submit the form when it is invalid (Screenshot 1),
[HttpPost]
public ActionResult Create(Client client)
{
if (ModelState.IsValid)
{
context.Clients.Add(client);
context.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(client);
}
Then it tries to redisplay the same form again (Controller Client, Action Create), but something isn't triggered right (Screenshot 2). The layout is wrong (buttons still hidden), the tabs aren't working (javascript), ...
Worst of all, i don't get any error in Firebug, Chrome Console, ...
Does anyone have an idea what could be the problem, because i really haven't got a clue what's happening. It seems to me that nothing has changed, but it did :s
Fyi, an equivalant for the post function is :
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
request.done(function (msg) {
$("#log").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
Before submit, everything loads fine
After submit, same form is called. jQuery isn't working anymore and form is getting bricked (i think this is "side" behaviour from the jQuery breaking)
Edit: (on request)
Here is the partialView in full
_CreateOrEdit.cshtml doesn't contain any javascript for now, the result is the same, so i only posted Create.cshtml.
Create.shtml
#model BillingSoftwareOnline.Domain.Entities.Client
<div class="container_12 clearfix leading">
<div class="grid_12">
#using (Html.BeginForm("Create", "Client", FormMethod.Post, new { #class="form has-validation", id="CreateOrEditSubmit"}))
{
#Html.Partial("_CreateOrEdit", Model)
<div class="form-action clearfix">
<button class="button" type="submit">
OK</button>
<button class="button" type="reset">
Reset</button>
</div>
}
</div>
</div>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.itextclear.js")"> </script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.uniform.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.tools.min.js")"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
});
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
// $.post(action, serializedForm, function (data) {
// $("#main-content").html(data);
// });
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
return false;
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
</script>
Since this markup is returned as a partial, you need to reinitialize your javascript.
This is hacky, but try putting your script in the partial view, instead of _CreateOrEdit.cshtml, and see if that works.
Update
After seeing the cshtml, it looks like it is not working because $(document).ready() has already executed, before the ajax load. Try this instead:
$(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
// $.post(action, serializedForm, function (data) {
// $("#main-content").html(data);
// });
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
return false;
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
});
Add the following instructions to the end of your ajax callback, so that the styling is applied after the form has been injected to the DOM:
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
$(".tabs > ul").tabs("section > section");

Resources