How can we confirm the deletion of an array element result of an ajax call?
I have an array :
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data)
{
$('#treeview').treeview({
data: data
});
}
});
In my recursive.php I have this code:
$arr = array(
'text' => '<img src="img/pdf.png">'.$sub_data["n_doc"].'
'
);
In this <a href, I need to confirm before deleting.
in delete.php i have:
$sql = mysqli_query($conn, ' DELETE FROM saisie WHERE code = "'.$doc.'" ') or die (mysqli_error());
Make another ajax call in the success function:
$(document).ready(function(){
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data)
{
$(document).on('click', '.btn_supp', function(){
if(confirm("do you want to delete this file?")){
$.ajax({
url: "delete.php",
method:"POST",
dataType: "json",
success: function(data)
{
alert("deleted");
});
}
});
}
});
$('#treeview').treeview({
data: data,
selectedBackColor: 'rgb(211,211,211)',
selectedColor: '#4A4A49',
enableLinks:true,
collapsedall: true
});
}
});`
The easiest method of accomplishing displaying a confirmation when AJAX adds to the DOM, would be to bind a delegated event listener in your view's DOMReady function.
Since jQuery binds event handlers during the DOMReady state, it will not bind additional elements in the ajax.success function, unless the response includes javascript and the dataType is 'script' or you parse the data variable from the success function and an event is manually added.
This assumes an element with an id="treeview", already exists.
<script type="text/javascript">
jQuery(function($) {
$(document).on('click', 'a[href^="delete.php"]', function(e) {
return window.confirm('Are you sure you want to delete this file?');
});
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data) {
$('#treeview').treeview({
data: data,
selectedBackColor: 'rgb(211,211,211)',
selectedColor: '#4A4A49',
enableLinks:true,
collapsedall: true
});
}
});
});
</script>
<div id="treeview"></div>
This works by telling jQuery to monitor all of the clicks inside of the #treeview element, for a triggering element of <a href="delete.php">. Specifically href^="delete.php" means an <a> element, with an href that begins with delete.php. If one is found, the callback function is executed and the confirmation dialog is displayed.
If you add a class attribute to your recursive.php anchor element, you can replace a[href^="delete.php"] with a.classname.
Example https://jsfiddle.net/ub1hw9tn/
$arr = array(
'text' => '<img src="img/pdf.png"><a class="delete" href="delete.php?doc='.$sub_data["code"].'" target="_blank">'.$sub_data["n_doc"].'</a>'
);
Then in your javascript
$(document).on('click', 'a.delete', function(e) {
if (!window.confirm('Are you sure you want to delete this file?')) {
e.preventDefault();
}
});
Related
I made an ajax request to get the name of each button I click...
Then I want to put everything in that url into "#Container".(url define a page that has some codes)
It works for me at the first time...but for the other times I have to reload the page to show me the details of each button and it doesn't show me details of other buttons that clicked after first desired button..
$(function () {
$('button').click(function () {
var data= $(this).val();
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {
data: data
},
success: function (data) {
$('#container').html(data);
}
});
});
});
What should I do?
Is there something preventing of running the ajax for next times ?
Try with $(document).on('click', instead of $('button').click like below
$(function () {
$(document).on('click','button',function () {
var data= $(this).val();
alert(data);
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);}
});
});
});
You will need to re-bind ajax event because of its re-rendering DOM after an ajax request completes. All those elements under #container are not virtual part of DOM and your click event only works for pre-existed elements.
Try this
Wrap ajax event in a separate function
function ajaxEvent(data){
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);
clickEvent(); //note this function attachment I added below
}
});
}
You can wrap your click event into a function
function clickEvent(){
$('button').off('click');
$('button').on('click',function(){
ajaxEvent($(this).val());
});
}
Now js looks like
<script>
$(function(){
clickEvent();
});
function ajaxEvent(data){
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);
}
});
}
function clickEvent(){
$('button').off('click');
$('button').on('click',function(){
ajaxEvent($(this).val());
});
}
</script>
Also I see you are passing ajax data as $('button').val() which is not correct. Use a input type text if you want to send a data to server.
I am trying to create a simple shopping cart using AJAX and PHP.
Everything works as it should BUT 1 thing doesn't work all the time and it seems that it fails to execute. (it works 3 times out of 5).
to explain this issue please take a look at the code bellow:
jQuery(document).ready(function() {
//////////////////////LETS RUN OUR ADD TO CART FEATURE USING AJAX //////////////
$(function(){
$('.form1').on('submit', function(e){
$( "#preloader" ).fadeIn( 850 );
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: $(this).attr('action'),
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$( "#preloader" ).fadeOut( 850 );
}
});
});
});
//////////////////////LETS RUN LOAD THE cart-header.php ON PAGE LOAD USING AJAX //////////////
$(document).ready(function () {
function load1() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data2) {
$('#headerCart').html($(data2));
//setTimeout(load2, 500);
}
});
}
load1();
});
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS RUN OUR DELETE FROM CART FEATURE USING AJAX //////////////
$(document).on('submit', '.delForm', function(dleItem){
// prevent native form submission here
dleItem.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS GET THE QUANTITY OF CURRENT ITEMS ADDED IN THE CART USING AJAX/////////////
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart.php",
//url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data) {
$('.item_count').html($(data).find('#total').text());
//$('#headerCart').html($(data));
setTimeout(load, 1000);
}
});
}
load();
});
I have commented the code so you can see the parts of the code and what they do.
the issue is this part:
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
As I mentioned above, this code works fine but it only works when it wants to as if it has mind of its own!
could someone please advise on this issue?
Thanks in advance.
I'm having some trouble with my jquery ajax code.
I have 2 functions, one that will submit a value and other that will update the values in real time.. At least that's what it is supposed to do. :P
So, I have a list that is created throught some PHP code:
<div id="votos">
<ul class="yourvotes">Your votes: 0</ul>
<li class="votesofothers">
User Votes: (0)</br>
User2 Votes: (0)</br>
</li>
</ul>
</div>
And then I have a Ajax call to update the database when one of the links is pressed:
$(function(){
$('.votar').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "votar.php",
data: "id="+elem.attr('iduser'),
dataType:"json",
success: function() {
window.location.reload(true);
}
});
$(document).ajaxStop(function(){
window.location.reload();
});
return false;
});
});
And this would be the code to update the values that appear in "real-time":
function mostrarvotos() {
$('#votos').load('votos.php');
setTimeout('mostrarvotos()',1000);
}
mostrarvotos();
(I originally wanted to update each of the user votes instead of updating the whole div but I couldn't manage to do it.)
So my problem is that when I add the "mostrarvotos()" function to my code the links stop working and just add a # to the url, but if I remove it everything works fine.. If you could help me with this I would greatly appreciate.
That's because you are not prevent the link's original action. The click handler won't catch the event when you refreshed the content with an AJAX request. Try document.on instead of your current handler:
$(document).on('click','.votar',function(e){
e.preventDefault(); //Prevent the default action
var elem = $(this);
$.ajax({
type: "GET",
url: "votar.php",
data: "id="+elem.attr('iduser'),
dataType:"json",
success: function() {
window.location.reload(true);
}
});
$(document).ajaxStop(function(){
window.location.reload();
});
return false;
});
Also note the preventDefault which prevents the defauls link action (the # in your address bar).
You need to delegate your click function because you are adding those links dynamically.
So do something like:
$(function () {
// delegate your dynamically loaded links
$('#votos').on('click', '.votor', function () {
var elem = $(this);
$.ajax({
type: "GET",
url: "votar.php",
data: "id=" + elem.attr('iduser'),
dataType: "json",
success: function () {
window.location.reload(true);
}
});
$(document).ajaxStop(function () {
window.location.reload();
});
return false;
});
});
I have a page with 2 divs..each div have to call an ajax function on load. However, after I open either one of the divs, the ajax of the other div will not work.
*#div_remove lets the user delete a user from the system and display the existing ones in another div within #div_remove thru ajax.
#div_logs displays all transactions done in the system and displays them on another div within #div_logs through ajax.*
Here is the jQuery code:
$("#remove_admin").on("click",function(){
$("#light").fadeIn("slow");
$("#div_remove").slideDown("slow");
showtable();
event.preventDefault();
$("#btnRemove").click(function(){
var text = $.ajax ({
type: "GET",
url: "delUserProcess.php?keyword="+$("#txtRemove").val()+"&table=users&field=username",
async: false,
}).responseText;
alert(text);
showtable();
event.preventDefault();
});
});
//VIEW USER LOGS
$("#logs").on("click",function(){
$("#light").fadeIn("slow");
$("#div_logs").slideDown("slow");
showLogs();
event.preventDefault();
});
$("#txtUser").on("keyup",function(){
showLogs();
event.preventDefault();
});
$(".date").on("change",function(){
showLogs();
event.preventDefault();
});
});
function showtable(){
$.ajaxSetup ({
cache: false
});
$.ajax({
type: "GET",
url: "showAdmin.php",
async: false,
success:function(text){
$("#tblUsers").html(text);
}
});
}
function showLogs(){
$.ajaxSetup ({
cache: false
});
var cBy = $("#txtUser").val();
var sDate = $("#startDate").val();
var eDate = $("#endDate").val();
$.ajax({
type: "GET",
url: "showLogs.php?sDate="+sDate+"&eDate="+eDate+"&createdBy="+cBy,
async: false,
success: function(text){
$("#tblHistory").html(text);
}
});
}`
the original code used .click(), .keyup() and .change().. I already tried using .live() and .on() but it is still not working. please help.
You need to bind the events under the showLogs file.
Because whenever you call the delete or other events, it replace the html with the updated one. and the events lots it existance. So you need to call them in the showLogs file.
I am trying to create a post using Ajax and jQuery.
But it isn't working. It just refreshes the current page.
HTML :
<form name="update_text_post" action="" id="update_text_post" method="post">
<textarea name="textbox" class="textbox" maxlength="600"></textarea>
<input type="submit" name="submit" value="Update" class="update_post_submit">
</form>
jQuery :
$('#update_text_post').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function (html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
return false
});
The e.preventDefault(); is not working aswell.. it actually is not even performing the MYSQL query . Seems like it is not even sending the form or targeting the post_ajax2.php file.
You need to use .preventDefault() to stop the default form submit behavior with page reload.
$(function() {
$('#update_text_post').submit(function(e) {
e.preventDefault(); // e.preventDefault() for prevent form submisson with page reload
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
function afterSuccess() {
$('#update_text_post').resetForm(); // reset form
close_box();
}
// 1. you missed $ here, so it will not be a dom ready callback.
// your case is just define a function, and without executing it.
$(function () {
$('#update_text_post').submit(function (e) {
// 2. you need to prevent the default submit event.
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function (html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
function afterSuccess() {
$('#update_text_post').resetForm(); // reset form
close_box();
}
You have to stop the default behavior of the submit button (form posting).Otherwise the form will be submitted again and you will see the page loading again ( you won't notice the change ajax brought to your page- some partial page updates ). You can use the preventDefault function to do this.
$(function(){
$('#update_text_post').submit(function(e) {
e.preventDefault(); // prevent the default submit behaviour
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html)
{
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
Add return false.
$('#update_text_post').submit(function(e) {
$.ajax({
...
})
return false;
});
Clicking on a submit button does just that - it submits the form. If you want to replace the form submission with an AJAX POST request, you'll need to stop the form from also being submitted (and the page therefore reloading), by preventing the default behaviour of that event.
You can do this by calling return false; at the end of the callback function bound to the submit event handler, or by passing a reference to the event to the callback function and calling e.preventDefault() (where e refers to the event).
The key difference between the two methods is that return false, in a jQuery callback function, will also prevent the event from bubbling. In this case, that's not really a big deal.
You have to call e.preventDefault(); in your function to prevent the form submit.
$('#update_text_post').submit(function(e) {
// prevent form submit
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html)
{
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});