I need to remove the parent div when user click on delete. So far I have below code:
<script>
function Confirmation(message, theurl)
{
if(confirm(message)) {
$.ajax({
type: "POST",
url: theurl,
success:function(response){
//on success, hide element user wants to delete.
$(this.className).unwrap();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
}
}
</script>
<div class="row">
<div class="col-sm-6">test7</div>
<div class="col-sm-3">Advanced</div>
<div class="col-sm-3">
<a href="http://localhost/v2/index.php/hr/employee/editSkill/10">
<a href="javascript:Confirmation('Are you sure you want to delete?', 'http://localhost/v2/index.php/hr/employee/delete/1/skills/10');">
</div>
</div>
This code perform the deletion but the div still not unwrap. I also try the remove() function but still no luck.
function Confirmation(message, theurl)
{
var $this = this;
if(confirm(message)) {
$.ajax({
type: "POST",
url: theurl,
success:function(response){
//based on the structure on your DOM
$($this).parents('.row').remove();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
}
}
You should try $(this).parent().remove(this); instead of $(this.className).unwrap(); inside the Confirmation() function if you want to delete the parent tag of button which you just clicked.
<script>
function Confirmation(elem, msg) {
if(confirm('Are you sure you want to delete?')){
$.post(elem.href)
.done(function(data){
$(elem).parents(".row").remove();
}).fail(function(data){
alert(data);
});
}
}
</script>
<div class="row">
<div class="col-sm-6">test7</div>
<div class="col-sm-3">Advanced</div>
<div class="col-sm-3">
<a href="http://localhost/v2/index.php/hr/employee/editSkill/10">
<a onclick="Confirmation(this, 'Are you sure you want to delete?'); return false;" href="http://localhost/v2/index.php/hr/employee/delete/1/skills/10">
</div>
Edited: now includes fail case.
Edited 2: includes use of function;
try this
$('body').on('click', '.buttonremove', function() {
$(this).parents("div:first").remove();
});
this inside the ajax success does not refers to the tag. You should store a reference of this initially and use the reference of the inside ajax success to do perform remove operation.
<div class="row">
<div class="col-sm-6">MySQL</div>
<div class="col-sm-3">Advanced</div>
<div class="col-sm-3">
<a href="http://localhost/v2/index.php/hr/employee/editSkill/3">
EDIT
</a>
<a class="delete" href="javascript:void(0)">
DELETE
</a>
</div>
</div>
<hr>
<div class="row">
<div class="col-sm-6">MySQL</div>
<div class="col-sm-3">Advanced</div>
<div class="col-sm-3">
<a href="http://localhost/v2/index.php/hr/employee/editSkill/3">
EDIT
</a>
<a class="delete" href="javascript:void(0)">
DELETE
</a>
</div>
</div>
<hr>
$(".delete").click(function(e){
var self = this;
var didConfirm = confirm('Are you sure you want to delete?', 'http://localhost/v2/index.php/hr/employee/delete/1/skills/2');
if (didConfirm == true) {
$.ajax({
type: "POST",
url: tourl,
success:function(response){
//on success, hide element user wants to delete.
$(self).parent().parent().next('hr').remove()
$(self).parent().parent().remove();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
}
});
I changed the approach. Assigned a class to delete and added a click listener to it. Show the confirmation alert inside it and make ajax call etc., I hope this approach would work for you.
FIDDLE
First of all i don't get why you are passing the message "Are you sure you want to delete?" as an argument. There are really better ways to do this, But as for now i will just correct your code and I am not 100% sure if the this pointer will work.
change this statement
$(this.className).unwrap();
to
$(this).parent().remove();
if you want to remove the div with class="row"
change the statement to
$(this).parent().parent().remove();
Related
To start I'm still learning javascript and AJAX so feel free to say everything that you want :)
I really don't get why this is happening: I have an Ajax function working very well, but if I post html content to call it again the AJAX function won't work in the content that it previously posted.
So here's the html code:
<div id="left-content">
<a class="clickme" value="1"> Option 1</a>
</div>
And this is my function
(function($) {
$('.clickme').click(function() {
$.ajax({
url: options.ajaxurl,
method: "POST",
data: {
"action": "filter",
"selection": $(this).attr('value')
},
beforeSend: function() {
$('#left-content').html("Loading...");
},
success: function(data) {
let html=``;
html+=`<a class="clickme" value="1">
Option 1 again
</a>`:
$("#left-content").html(html);
},
error: function(error) {
console.log(error)
}
})
})
})(jQuery);
So what I get after clicking Option 1 is
<div id="left-content">
<a class="clickme" value="1"> Option 1 again</a>
</div>
But if I click this it won't work now :( .
I think I see the problem:
In the data property of your ajax object you set selection as
selection": $(this).attr('value')
the anchor tag does not have a value attribute, it has val. Rename val to value and it should work
<a class="clickme" value="1"> Option 1 again</a>
I wan't to replace a section from div in my index view with new data that I get from partial View. I get a correct responce, which I see in firebug. For now I only display on success an alert window, that says it's working. Bellow is my Ajax code and a part of response which i get(20 list-group items inside an ul). So do I have to write for every div javascript code just like in my view or is there another option? Maybe some examples please?
Regards!
<script>
function testAjax() {
debugger;
$.ajax({
url: "#Url.Content("~/Controller/MyAction")",
data: "searchString=search",
type: "Post",
beforeSend: function () {
//Code for before send whatever you have to do.
},
success: function (data) {
alert("It's Working!");
},
error: function (response) {
//Your code when error ocure
alert(response.responseText);
},
failure: function (response) {
//your code for failure
alert(response.responseText);
}
})
}
</script>
my response:
<ul class="list-group infinite-scroll">
<li class="list-group-item col-md-6">
<div class="noo-event-featured-item grow">
<div class="sc-event-content">
<h3>text</h3>
<div class="bottom">
<div class="create-date">
<span>
date
</span>
</div>
</div>
</div>
<div class="sc-event-item">
<div class="event-thumbnail">
<a href="link" >
<img src="image link">
</a>
<div class="sc-meta">
<span class="sc-date"><i class="fa fa-clock-o"></i><span> text</span></span>
<span class="sc-address">
<i class="fa fa-map-marker" style="padding-left: 3px;"></i>Place<span class="tribe-address">
<span class="tribe-street-address">Street</span><span class="tribe-delimiter"
>, </span>
<span class="tribe-locality">Country</span>
</span>
</span>
</div>
</div>
</div>
</div>
</li>
</ul>
Thank you all, I have figured it out. You have to use a dot before divid $(".divid").replaceWith(data);
If your response its a html code(in plain text) you can try use something like this in your success function:
$('yourDiv').html(data);//replace child nodes
I am working on a bootsrap3 template, which is Ajax based.
My index file has a leftside menu and a conent block middle of the page, every time I click on a subelement of this left menu, an Ajax laod will put the page content in this block(ajax-content).*
Any time I call any page, my URL normally looks something like this /index.php#page-one.php, except when the page contains form submission.
The Problem happens when I add an action attribute (acion="page-one.php") to my form tag.
After the form submission my URL turns to /page-one.php ;
consequently I get a white page containing the page-one.php elements whitout any CSS styling and of course no index-file's elements.
What is the correct and best way to come a cross this issue?
index.php:
<body>
<!--Start Container-->
<div id="main" class="container-fluid">
<div class="row">
<div id="sidebar-left" class="col-xs-2 col-sm-2">
<ul class="nav main-menu">
<li class="dropdown">
<a id="configuration" href="#" class="dropdown-toggle">
<i class="fa fa-gears"></i>
<span class="hidden-xs">Menu-element</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="page-one.php">Menu-Subelement-one</a></li>
<li><a class="ajax-link" href="page-wo.php">Menu-Subelement-two</a></li>
</ul>
</li>
</ul> <!-- end of main-menu-->
</div>
<!--Start Content-->
<div id="content" class="col-xs-12 col-sm-10">
<div class="preloader">
<img src="img.gif" class="loader" alt="preloader"/>
</div>
<!--inside this div a short description/introduction(simple text inside a <p> tag) about the Menu-element will be shown-->
<div id="content-header"></div>
<!--inside this div the page content of the Menu-subelement will be shown-->
<div id="ajax-content"></div>
</div>
<!--End Content-->
</div>
</div>
<!--End Container-->
<script src="plugins/jquery/jquery-2.1.0.min.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="plugin/jquery.form.js"></script>
<script src="js/script.js"></script>
And here is my script.js:
//
// Function for load content from url and put in $('.ajax-content') block
//
function LoadAjaxContent(url){
$('.preloader').show();
$.ajax({
mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
url: url,
type: 'GET',
success: function(data) {
$('#ajax-content').html(data);
$('.preloader').hide();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
dataType: "html",
async: false
});
}
//////////////////////////////////////////////////////
document.ready
//////////////////////////////////////////////////////
$(document).ready(function () {
var ajax_url = location.hash.replace(/^#/, '');
if (ajax_url.length < 1) {
ajax_url = 'home.php';
}
LoadAjaxContent(ajax_url);
$('.main-menu').on('click', 'a', function (e) {
var parents = $(this).parents('li');
var li = $(this).closest('li.dropdown');
var another_items = $('.main-menu li').not(parents);
another_items.find('a').removeClass('active');
another_items.find('a').removeClass('active-parent');
if ($(this).hasClass('dropdown-toggle') || $(this).closest('li').find('ul').length == 0) {
$(this).addClass('active-parent');
var current = $(this).next();
if (current.is(':visible')) {
li.find("ul.dropdown-menu").slideUp('fast');
li.find("ul.dropdown-menu a").removeClass('active')
}
else {
another_items.find("ul.dropdown-menu").slideUp('fast');
current.slideDown('fast');
}
}
else {
if (li.find('a.dropdown-toggle').hasClass('active-parent')) {
var pre = $(this).closest('ul.dropdown-menu');
pre.find("li.dropdown").not($(this).closest('li')).find('ul.dropdown-menu').slideUp('fast');
}
}
if ($(this).hasClass('active') == false) {
$(this).parents("ul.dropdown-menu").find('a').removeClass('active');
$(this).addClass('active')
}
if ($(this).hasClass('ajax-link')) {
e.preventDefault();
if ($(this).hasClass('add-full')) {
$('#content').addClass('full-content');
}
else {
$('#content').removeClass('full-content');
}
var url = $(this).attr('href');
window.location.hash = url;
LoadAjaxContent(url);
}
if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
$('#formSubmit').ajaxForm();
});
page-one.php:
<!--some php code here-->
<form class="validateForm" id="formSubmit" action="page-one.php" method="get">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" />
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-8">
<button type="submit" class="btn btn-primary btn-label-left">
<span><i class="fa fa-save"></i> Save</span>
</button>
</div>
</div>
</form>
Thanks!
I had the same issue to solve for the intranet I work on.
For me, the good way to do this is to avoid using submit method and use instead an input button with a js function to send the form data.
In my case, I did this:
<!-- At the top of my webpage -->
<script language='Javascript'>
function loadingAjax(div_id,user,date1,date2)
{
$("#"+div_id).html('<br><center><img src="images/loading.gif"><br><br><font color="#006699" face="arial" size="4"><b>Loading data<br>VPlease wait ...</b></font></center>');
$.ajax({
type: "POST",
url: "activities.php?USER="+user+"&DATE1="+date1+"&DATE2="+date2,
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
<!-- And here is my form -->
<form id='date_form'>
<input type='text' id='user'><input type='text' id='date1'><input type='text' id='date2'>
<input type='button' onclick="loadingAjax('myDiv',document.getElementById('user').value,document.getElementById('date1').value,document.getElementById('date2').value);">
</form>
This allow to send your form in a separate DIV without having to show to everyone your URL.
MORE: you can even use this function to manage your left side menu selection so that your URL would stay '/index.php' all the time.
Hope this help
Regards
Nico
How do you want to submit the form, using ajax?
If you want to use ajax, you should cancel the default action like you do with your links using e.preventDefault();. Post the javascript that handles the form submit if you need help with that.
If you want to post to page-one.php without using ajax, you could add a header() redirect after the php code that processes the form to redirect to the page that you would like to show after the form gets submitted.
As you are loading content by ajax,
You can post content to page-one.php and redirect user to it's previous page. But it will be difficult manage and show error, success, notification message like form validation errors etc.
Another and I think best solution is to use ajax form submission
I have a show/hide for messages which is working. There is a subject and message. I need it to work so that only onClick of the title will the message display. At the moment when I click on the title of the message, it opens the message, but when the message is open, if I click on the message, it hides. As I'm going to be having some links within the message, this doesn't work. I only need onclick of the title to show and hide the message.
HTML/PHP CODE:
<div id="note_container">
<div id='empty_msg' style="display:none;">You do not currently have any notifications in your <span id='box_type'>INBOX</span></div>
<!-- Content -->
<?
if(!empty($notes)):
foreach($notes as $box_type=>$notes_array):
if(!empty($notes_array)):
foreach($notes_array as $note):
$envelope_icon = ($note['opened']==1)?'icon_opened.jpg':'icon_closed.jpg';
?>
<div id="note_<?=$note['note_id']?>" class='hdr_active <?=$box_type?>_item'>
<input type="checkbox" name="notes_chk" value="<?=$note['note_id']?>" class="notes_chk" style="float:right;"/></label>
<div style='display:inline-block;' id='note_<?=$note['note_id']?>' class="note new_note hide">
<img src="images/buttons/<?=$envelope_icon?>" id='note_indicator_<?=$note['note_id']?>' class="note_indicator" width="20" height="19" />
<?=$note['subject']?>
<div id='note_details_<?=$note['note_id']?>' class="details" style="display: none">
<p><?=$note['message']?></p>
</div>
</div>
</div>
<?
endforeach;
endif;
endforeach;
endif;
?>
</div><!-- END NOTE CONTAINER -->
JQuery CODE
$(".note").click(function(){
// get the search values
var id = $(this).attr('id')
var id_array = id.split('_')
var note_num = id_array[1]
if($(this).hasClass('hide'))
{
$(this).removeClass('hide').addClass('show')
$("#note_details_"+note_num).slideDown()
if($(this).hasClass('new_note')){
var notes = [note_num]
$(this).removeClass('new_note')
$("#note_indicator_"+note_num).attr("src","images/buttons/icon_opened.jpg");
$.ajax({
type: "POST",
url: "ajax-redirect.php",
data: { type: 'markRead', notes: notes, page:'ajax.php' }
}).done(function(data) {
$(".notes_chk").removeAttr('checked')
if(data!=1)
{
alert("failed to update the system")
$("#note_indicator_"+note_num).attr("src","images/buttons/icon_closed.jpg");
}
})
}
}
else
{
$(this).removeClass('show').addClass('hide')
$("#note_details_"+note_num).slideUp()
}
})
$('#check-all').click(function(){
$("input:checkbox").attr('checked', true);
});
$('#uncheck-all').click(function(){
$("input:checkbox").attr('checked', false);
});
})
Please read jQuery documentation! For this case you can use native jQuery method toggle
$("div.note").click(function(){
$(this).toggle(); // or some other selector
});
or if .note is link
$("div.note").click(function(e){
e.preventDefault();
$(".your_block").toggle(); // or some other selector
});
Because div with the note class is the parent of the message any events on its children will bubble up to it so you need to prevent that with event.stopPropagation().
I can't test this code(i dont have the raw HTML to do so) but it should represent what needs to be done:
$(".note").children().click(function(e) {
e.stopPropagation();
});
You need to bind a click event to the children of the div with the note class and prevent it from bubbling up.
I'm trying to make a individual dropdown container like of that on the nopnav of the google, well everything runs ok, exept the fact that i would like to deactivate the activated class of the trigger event when i click on to hide the container!
Inserted the page where are the links where will be triggered to push up the container, and the second page is the content of the container, where i put in one script to hide the container and the second one to "tabfy" the menu with the jquery tools tabs.
Here's the code:
$(function () {
"use strict";
$(".user-link").click(function (e) {
e.preventDefault();
if ($(".user-link").hasClass("#buser-box")) {
$(".user-link").removeClass("#buser-box");
} else {
$('#buser-box').show('fast');
$(".user-link").addClass("active");
}
$.ajax({
url: "conta-box/conta-home.html",
cache: false,
dataType: "html",
success: function (data) {
$("#buser-box").html(data);
if (!$(this).hasClass("#buser-box")) {
$("#buser-box").removeClass("#buser-box");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
});
});
HTML of the Index:
<div class="tabs-global">
<ul id="nav">
<li class="user-link" title="Conta"><a class="user-box"></a></li>
<li class="loja-link" title="Loja"><a class="loja-box"></a></li>
<li class="ava-link" title="Avaliação"><a class="ava-box"></a></li>
</ul>
</div>
<div id="buser-box"></div>
<div id="loja-box"></div>
<div id="ava-box"></div>
HTML of the container-content:
<div class="topbar">
<span class="box-close" onclick="box.close();"></span>
</div>
<div id="menu-box">
<h2>
<span class="icones-conta"></span><span class="texto">Conta</span></h2>
<ul id="conta-tabs">
<li class="current">Configuração</li>
<li>Localização</li>
<li>Compras</li>
</ul>
</div>
<div id="conta-container"></div>
<script type="text/javascript" src="./js/jquery.tools.min.js"></script>
<script type="text/javascript">
$(".box-close").click(function () {
$("#buser-box").hide("fast");
});
</script>
If you use any Jquery property that refers to class, you then need to use a class.
For example:
if ($(".user-link").hasClass("#buser-box")) {
$(".user-link").removeClass("#buser-box");
}
Should Be:
if ($(".user-link").hasClass("buser-box")) {
$(".user-link").removeClass("buser-box");
}
Also you could try a click function for showing and a click function
for hiding:
// hide your dropdown menu by default
$('#myMenuContainer').addClass('closed').hide();
$('.mylink').click(function(showMenu){
//display your drop down menu
if($('#myMenuContainer').hasClass('closed')) {
$('#myMenuContainer').show().addClass('open').removeClass('closed');
}
});
$('.mylink').click(function(showMenu){
//hide your drop down menu
if($('#myMenuContainer').hasClass('open')) {
$('#myMenuContainer').removeClass('open').addClass('closed').hide();
}
});