After button submit, refresh page - php

I am using wordpress version 4.9.8 and PHP 7.1.8.
Below you can see, that I have added a button to my post. This button inserts content into the_content field of a post. After submitting the button I would like to refresh the single post page and show the content.
Find below my code for the button:
add_action('media_buttons', 'add_my_media_button', 99);
function add_my_media_button()
{
$post = $GLOBALS['post_ID'];
echo "<a href='#' id='insert-my-media' data-post-id='{$post}' class='button'>Own content</a>";
}
add_action('wp_ajax_updateContent', 'updateContent');
function updateContent()
{
$post_id = intval($_POST['post_id']);
try {
$sp = new SinglePostContent();
$sp->main($post_id);
} catch (Exception $e) {
echo $e;
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action('admin_footer', 'my_media_button_script');
function my_media_button_script()
{
?>
<script>
jQuery(document).ready(function ($) {
$('#insert-my-media').click(function () {
var post_id = $(this).attr('data-post-id');
var data = {
'action': 'updateContent',
'post_id': post_id
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function (response) {
console.log("test12")
console.log(response);
});
});
});
</script>
<?php
}
Any suggestions how to refresh the page and show the content.
Looking forward to your replies!

Change your code like this :
[...]
jQuery.post(ajaxurl, data, function (response) {
console.log("test12")
console.log(response);
window.location.reload();
});
[...]

in callback function, reload the page:
jQuery.post(ajaxurl, data, function (response) {
console.log("test12")
console.log(response);
location.reload();
});

jQuery.post(ajaxurl, data, function (response) {
console.log("test12")
console.log(response);
location.reload(true);
});
use ture in reload to make a hard refresh reload from the server.
or you can return the updated post content and use html() to replace it without a refresh.

Related

How not to redirect page on ajax submit codeigniter

So, i have a following ajax code and controller code, my problem is i want to insert comment withouth refreshing the page and not redirecting to another page, and it seems that whenever i hit btnCommentSubmit it is redirecting me to my controller page, how to prevent that?
Ps. The insertion is working
//AJAX CODE
$('#btnComment').click(function(e){
var comment_identifier = $(this).data("value");
var comment_by = $(this).data("id");
$('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/'+comment_identifier+"/"+comment_by);
});
$('#btnCommentSubmit').click(function(){
var url = $('#formAddComment').attr('action');
var addCommentTxt = $('#addCommentTxt').val();
$.ajax({
type: 'post',
url: url,
data: {addCommentTxt:addCommentTxt},
success: function(){
alert('success');
},
error: function(){
console.log(data);
alert('Could not add data');
}
});
});
});
//Controller code
public function addComment(){
$cIden = $this->uri->segment(3);
$cBy = $this->uri->segment(4);
$data = array(
"comment_identifier" => $cIden,
"comment_by" => preg_replace('/[^a-zA-Z-]/', ' ', $cBy),
"comment" => $this->input->post('addCommentTxt'),
"comment_at" => time()
);
if ($this->Crud_model->insert('comments',$data)) {
return true;
}else{
return false;
}
}
Add e.preventDefault() in the beginning of your function:
$('#btnCommentSubmit').click(function(e){
e.preventDefault();
...
}
You may want to use jQuery form plugin. It submit form to our controller without any page refresh/redirect. I use it all the time.
https://jquery-form.github.io/form/
Example usage:
$('#form').ajaxForm({
beforeSubmit: function() {
//just optional confirmation
if (!confirm('Are you sure want to submit this comment?')) return false;
show_loading();
},
success: function(status) {
hide_loading();
if (status == true) {
alert('success');
} else {
alert('Could not add data');
}
}
});
You can use javascript:void(0); like href="javascript:void(0);"

Ajax POST to Cakephp Controller always give array() result

i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});

AJAX load content using link instead of button?

I am trying to load content of a URL which is in a href of a Link using AJAX/JQUERY.
For some reason, the AJAX doesn't get executed and when i click on the Link, the URL will open in a new window!
but I need to load the content of URL on the same page that has the AJAX without opening a new window!
this is my current code:
<div id="content"></div>
<a id='listc' class='lisitem' href='file.php?id=".$id."' >".$id."</a>
and the AJAX:
<script type="text/javascript">
$("#listc").click(function() {
$("#content").load(this.href);
return false;
});
</script>
just to clarify, I do have the jquery lib included in my page header and I am using it for other stuff on the same page. so the issue is not that.
could some please advise on this issue?
Thanks
You need to prevent the default action of the link:
<script type="text/javascript">
$("#listc").click(function(e) {
e.preventDefault();
$("#content").load(this.href);
return false;
});
</script>
You need to do something with your AJAX return :
<script type="text/javascript">
$("#listc").click(function() {
$("#content").load(this.href, function(result){
alert("AJAX done");
});
return false;
});
</script>
You can change the href from the actual page, to a javascript: call. This way, you wouldn't have to concern about the default link redirect.
<a id='listc' class='lisitem' href=javascript:LoadFunction('file.php?id=".$id."'); >".$id."</a>
JS:
function LoadFunction(url) {
$("#content").load(url, function(result){
//something
});
}
Give the following a try:
document.getElementById('listc').addEventListener('click', function() {
$("#content").load(this.href);
return false;
});
UPDATE
Change:
<a id='listc' class='lisitem' href='file.php?id=".$id."' >".$id."</a>
to:
<a id="listc" class="listitem" data-id="<?= $id; ?>" href="#"> <?= $id; ?></a>
And AJAX to:
$(document).delegate('.listitme','click',(function() {
var id = $(this).data('id');
$('#content').load('file.php?id=' + id);
return false;
}
or:
$(document).delegate('.listitme','click',(function() {
var id = $(this).data('id');
$.post('file.php', {id : id}, function(answer) {
$('#content').html(answer);
});
}
Try something like that :
When you click on the link, do an AJAX call then print the result in your container.
<script type="text/javascript">
$("#listc").click(function(e) {
e.preventDefault();
$.ajax({
url: $(e.currentTarge).attr('href'),
complete: function () {
// remove loading status if neeed
},
success: function (response) {
$("#content").html(response)
},
error: function() {
//manage error here
}
});
});
</script>

Jquery stop function when user hovers over a div

I have a jquery ajax function:
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
posts();
And I want to stop the function when a user hovers over the div 'Posts' and resume when the user stops hovering over that div. Is there any way I could do that.
Thanks
Here you go :)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
timer = setTimeout(posts,2000);
}
});
}
posts();
$(document).ready(function(){
$('#posts').hover(function(){clearTimeout(timer);}, function(){setTimeout(posts,2000);});
});
</script>
<div id = 'posts'></div>
Basically I added a mouser-over and mouse-out event handlers to the #post div which will clear and reset the timeouts respectively..
you probably wnat to stop ajax function from running what you are looking for is called
var pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
more on hover event
$("idofyourdiv").hover(
function () {
pfunc.abort();
},
function () {
pfunc();
}
);
First, I'd structure your base code somewhat like this:
var timer = null;
var request = null;
function posts() {
request = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data).fadeIn(2000);
timer = setTimeout(posts, 2000);
}
});
}
posts();
Next, to clear the timer, run clearTimeout() on the timer object. timer stores the id of your timeout function, which might not exist when you try to clear it, so safely clear it like this:
if (timer !== null) {
clearTimeout(timer);
}
Finally, you should abort the AJAX request, so just add that in as well:
if ((timer !== null) && (request !== null)) {
clearTimeout(timer);
request.abort();
}
This one will check if your div is being hovered. And if it is true, the ajax call will be cancelled.
Trying not to modify too much your code:
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
beforeSend: function(){
if($("#posts").is(":hover")){
return false;
}
},
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
posts();
javascript is not multi threaded so you can not stop a piece of code from running. As stated in other answers you may call abort on your ajax request but that is not stopping any code, it just aborting a request. And I'm not even sure its smart to abort the request when your just going to make the request again when the user stops hovering. I would let the request go thru and check the hover state in the response. If the hover state does not match your condition buffer the response and wait till the user stops hovering then resume your execution. Something like the following...
var hovering = false;
var onResponse = null;
$('.Posts').mouseover(function() {
hovering = true;
});
$('.Posts').mouseout(function() {
hovering = false;
onResponse && onResponse();
});
function posts() {
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
onResponse = function() {
if(hovering) return;
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts, 2000);
onResponse = null;
};
onResponse();
}
});
}
posts();

Basic javascript function

I have this function working
<script type="text/javascript">
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
});
</script>
But I need to have the same stuff happening (on IOS Devices), but instead of it happening when the browser reaches the loadmoreajaxeloader div, I simply need it to happen on an onclick event on a link. Thanks heaps.
Tried to add code but didn't format so here it is http://pastebin.com/p2VUqZff
You need to separate the Ajax and the scroll event.
So create a function to load the content like so:
// Create the load content function
function loadContent(){
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html){
if(html){
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
}else{
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
Then bind the scroll event to the window:
// Set the onscroll event
$(window).scroll(function(){
if($(window).scrollTop()==$(document).height()-$(window).height()){
$('div#loadmoreajaxloader').show();
// IF YOU WANT TO LOAD MORE CONTENT WHEN SCROLLING THEN UNCOMMENT THE NEXT LINE
// loadContent();
}
});
Then set the onclick event of the Load More link:
// Bind the click event to the Load More link
$('#loadMore').click(function(e){
// This will prevent any default action
e.preventDefault();
// Load the content
loadContent();
});
UPDATE
I forgot to make sure the events are assigned once the page has loaded. Surround all of your javascript with this:
$(document).ready(function(){
// PUT ALL THE JAVASCRIPT HERE
});
If you're saying you want the code to execute both on scroll and when your link is clicked you can put the common code in a function that you call from all the places you need it:
function doStuff() {
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
doStuff();
}
});
$("#idOfYourLinkGoesHere").click(function() {
doStuff();
return false;
});
Noting that returning false from the click handler stops the default behaviour for a click on a link (i.e., prevents it navigating away from the current page or moving back to the top of the page).
I wasn't sure if the .show() was to occur from the link so I've left it within the scroll handler. If it applies to either case move it into the doStuff() function.
Try to replace the scroll parts with something like that:
$('a#moreLoader').click(function() {
$('div#loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
return false;
});
where a#moreLoader is a link with 'moreLoader' as id :
<a id="moreLoader" href="#">load more</a>
I think what you are asking is "how can I reuse this function when a link is clicked" - and if so, the answer is this:
<script type="text/javascript">
// Declare the AJAX action as a separate function
var loadMoreContent = function() {
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
};
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
loadMoreContent(); // Just call the separate function here
}
});
// ...and attach the function as a click handler to the link:
$('#idOfMyLink').click(function() {
loadMoreContent(); // Just call the separate function here
return false; // Return false to prevent navigation away from the page
});
</script>

Categories