Hi I am developing data deleting page with checkbox and button. After deletion, I'd like to display the message either the transaction is successful or not. Most of the time the message shows correctly, but sometimes the page reload doesn't happen and the message won't show until manually reloaded.
Now if it's not certain if the page is reloaded, is there any other way to show the message from the controller?
Here's the code:
(index.ctp)
<script type="text/javascript">
$(document).ready( function() {
$("#btn").click(function() {
var ids = '';
$('input[type="checkbox"]').each(function(){
if(this.checked){
ids = ids.concat(this.id).concat(',');
}else{
jAlert("Please choose items to delete");
}
});
if (ids != ''){
jConfirm('Delete?', 'Confirm',function(r){
if(r==true){
ht = $.ajax({
url: 'items/delete/'.concat(ids),
type: "POST",
contentType: "application/json; charset=utf-8",
});
location.reload(true);
}
});
}
});
});
</script>
(controller.php#function delete())
$this->Session->setFlash(__('Deleted!, true));
$this->redirect(array('action'=>'index'));
CakePHP's session flash is usually pretty reliable.
Perhaps your browser is not reliably doing a hard refresh with location.reload(true). Try window.location = window.location.href + "?nocache=" + new Date().getTime() to manually clear the cache and see if that helps at all.
Related
i am new to coding and i am writing project for teach me self about PHP social site. In post loading ajax call page number are not updating in start of recall and sometime same result are show again and again. my be add some delay in js script? please help me. Thanks
first part is post class which load post from database and second part is js script.
i check the code again all are fine but i need to delay or reduce ajax call. load is still process and ajax is trigger another call that why it have same page is load again and again.
may be delay in js script require to slow down loading process
script
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
$.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache: false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function() {
var height = $('.posts_area').height(); //Div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) ||
noMorePosts == 'false') {
$('#loading').show();
//alert("hello");
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache: false,
success: function(response) {
$('.posts_area').find('.nextPage')
.remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts')
.remove(); //Removes current .nextpage
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
</script>
i can't really execute your code but you can try to set id_post as attribute for each post you render with js , then next time you get new posts you can know if the post already exists with
document.getElementById('id_post')
if you get an element you don't re-render it.
if its empty you can render your post
I am trying to reload a div with id #todos after the data is saved in the database.
I tried using .load() in $.ajax()
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
},
});
});
The problem with this, that it is not reloading the page but it is updating the data in database correctly.
I also tried this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
In this, it is reloading the page as well as updating the data in the database but the problem is that it only reload and update the data at the first request, and after that I need to reload the whole page to update next data.
I tried to check if I am getting any data or not
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
console.log(data);
},
});
});
It returned nothing, but my data in the mongoDB compass is changing.
I already read this articles so, please don't mark this question as duplicate.
Refresh/reload the content in Div using jquery/ajax
Refresh Part of Page (div)
refresh div with jquery
reload div after ajax request
I suggest you checking requests between your page and the server in the Network tab of browser's Development Console (F12).
Make sure you see PUT request going out to the server to update todo
Make sure that response you receive looks like { success: true } otherwise the following piece of code won't be triggered
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
Make sure you see GET request going out to the server to pull '#todos' asynchronously.
If you don't see request #3 try the following:
replace location.href with window.location.href
try reloading it manually via console (for Chrome, F12 -> Console tab -> paste $('#todos').load(location.href + ' #todos') and hit Enter). That way you are going to skip first ajax request and just will check whether '#todo' section is loadable/reloadable.
I think it’s a cache problem. Try it like this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: '/todo/${value}?t=202103010001',
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
t=202103010001 Set to a random number
Okay so am using Ajax to send a JS variable from index.php to page2.php . Once it is set to page2.php, the database is edited while the user has been on index.php the entire time. However, I need the index.php to reload or refresh once page2.php has finished updating the database in the background. To give you a better clue, I will include some of my code.
On Index.PHP is :
<a href='#' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
and
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
});
}
So basically when they click the button that says "Update" it sends the ID of the button the page2.php and page2.php from there updates the changes the database using that info. However, the URL the user is on is:
http://website.com/index.php#
and the database has not updated for them and they have to see the annoying hash symbol in the URL. I have googled how to refresh the page in JS, and found things that either do not work or do work , but result in the variables not being sent to the PHP file. I just need it so that after it is sent to the php file, and preferably after the php file is finished, the index.php page refreshes and without the # at the end.
e.preventDefault() is the answer but if I may suggest:
Get rid of that inline function and add the event handler with jQuery.
$(function () {
$('.dbchange').click (function (e) {
e.preventDefault();
var id = this.id;
$.ajax({
type: "POST",
url: 'page2.php',
data: {NewID: id},
success: function(data) {
window.location.reload();
}
});
});
});
Remove # then replace with javascript:void(0):
<a href='javascript:void(0)' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
JS:
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
success: function() {
window.location.reload();
}
});
}
I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.
this is a snippet of a js file>
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList',
type: 'POST',
data: {id: id, userT: usertype},
success: function(html){
$('[data-id='+id+']').parents('tr').remove();
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
as you can see there is an alert message after deleting a user from a list.
I want to refresh the page after ok on alert message is pressed so i added the line>
window.location.reload();
but it's not working, why is this? how can i fix it?
I've been trying to use alternative to this like
location.href = '....';
window.location = '/some/url';
but nothing seems to work!
this is in my admin.php, the code for deleting user from the database:
public function deleteUserFromList(){
if ((isset($_POST['id']) && (isset($_POST['userT'])))){
$rowId = $_POST['id'];
$userType = $_POST['userT'];
$result = array();
if($userType == 'front'){
$front = UserManager::getInstance()->getUser($rowId);
UserManager::getInstance()->deleteItem($front);
}else{
$back = UserBackManager::getInstance()->getUser($rowId);
UserBackManager::getInstance()->deleteItem($back);
}
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
}
In order to simulate redirect in your browser try to:
Javascript way:
window.location.replace("http://stackoverflow.com");
jQuery way:
var url = "http://stackoverflow.com";
$(location).attr('href',url);
Try this and let me know it it works for you or not.
EDIT:
Inside ajax success. Try to close modal window and try to replace method.
EDIT 2:
Put this part of code inside of your document ready block and check is it fired or not if it is fired it means your form is reloading correctly.
$( window ).unload(function() {
alert( "Bye now!" );
});
Elaborating on #charlietfl's comment, could you try something like this?
Return the count from the ajax script and insert it into your page:
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList', // this returns the user count as data
type: 'POST',
data: {id: id, userT: usertype},
success: function(data){
$('[data-id='+id+']').parents('tr').remove();
$('#countDisplayElement').text(data); // insert new count into current page
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
That would eliminate the need to refresh the page entirely and be a bit more friendly to use.