wordpress ajax call single post - javascript

I tried to do a ajax call in my wordpress loop, basically i would like to load the content of the post in the home page in a div, after the click on the title.
the call ajax seems work, but i have the problem that load whole the page, and i would like to load only the content of a div with specific id.
this is my code: index.php
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a class="post-link" rel="<?php the_ID(); ?>" href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
<?php endwhile; endif; ?>
<div id="single-post-container"></div>
this is the single.php
<?php $post = get_post($_POST['id']); ?>
<div id="single-post post-<?php the_ID(); ?>">
<?php while (have_posts()) : the_post(); ?>
<?php the_title();?>
<?php the_content();?>
<?php endwhile;?>
</div>
and this is the js
jQuery(document).ready(function(){
jQuery.ajaxSetup({cache:false});
jQuery(".post-link").click(function(){
var post_link = jQuery(this).attr("href");
jQuery("#single-post-container").html("content loading");
jQuery("#single-post-container").load(post_link);
return false;
});
});
i tried to add the id #single-post after post_link like this:
jQuery("#single-post-container").load(post_link #single-post);
but when i run gulp i have an error that block me.
how can i achieve this scope?
someone could give me an help or suggestion?

I think this may be the answer but only if I have correctly understood the problem:
What is post_link? What actual url is your AJAX call calling? If you are just calling single.php the first thing that does is call header() - hence you might get the whole page. Looking at your index.php i think this may be what is happening.
If so. You need to look up how to do AJAX calls in WordPress. You have to add an AJAX callback with something like add_action('wp_ajax_my_action', mycallback). Then your callback can just get the single post with get_post(). The actual url your AJAX call should be calling is something like:
yourdomain/wp-admin/admin-ajax.php?action=my_action&post_id=THEPOSTID. You can use admin_url() to help you build the correct url.
You may need to inject THEPOSTID into your JavaScript. Using wp_localize_script. Or you could add it as an attribute in index.php and get it in your JavaScript.
Then your callback - mycallback() - can use get_post() to get just the post and return it without all the page fluff. E.g.:
function mycallback()
{
$postId = $_GET['post_id'];
$postRow = get_post($postId);
echo $postRow->post_content;
wp_die();
}
Maybe look for a few examples on how to do AJAX with WordPress? e.g. http://wptheming.com/2013/07/simple-ajax-example/
UPDATE:
added wp_die(); at the end of the AJAX call-back. You need to do this to stop WordPress spitting out a lot of page bumf as well. In fact this may be the part that is missing from your single.php. Stil, probably better to do to it using admin-ajax.php anyway perhaps.

if this can help someone, i solved with this code
//take the permalink of the single post
var post_permalink = locations[i].post_url + " #single-post";
// load post in the div
jQuery("#single-post-container").html("content loading");
jQuery('#single-post-container').load(post_permalink);
thanks you all anyway

Related

Passing php variable to button onclick function

I am a newbie working on a screen which has a conditional button which should appear only if $step==2. In this case, the button is shown and on click, redirects me to another page within my project. However, the url to which it should redirect me is not fixed, but has a parameter within it. I am having trouble getting the onclick to work!
I have tried defining a $path variable in which I store the relocation string. I do this in the following way:
<?php $path = '"window.location=\'{{ url("/location/'.$location->id.'/description") }}\'"'?>
When I echo this $path, I get exactly the string I need, which is:
"window.location='{{ url("/location/2/description") }}'"
(Note: The $location->id in my test case is 2)
However, I then try using this $path for the onclick of the button and it's not working! Here is the whole thing:
<?php if ($step == 2) : ?>
<?php $path = '"window.location=\'{{ url("/location/'.$location->id.'/description") }}\'"'?>
<button class="button_s_red" onclick=<?php echo $path; ?>>{{ trans('setup_process.STEP2_Button') }}</button>
<?php endif; ?>
When I inspect this button in chrome, it seems that on the onclick, the / character is not getting through. But this is odd since when I echo the $path I do get this character, and / doesn't seem to be an escape character from what I've googled.
I've tried pretty much everything and googled every possible help but can't seem to make it work! Thanks in advance for your help!
id.'/description") }}\'"'?> >{{
trans('setup_process.STEP2_Button') }}
I think u must use " in Your code like this.
<?php if ($step == 2) : ?>
<?php $path = '"window.location=\'{{ url("/location/'.$location->id.'/description") }}\'"'?>
<button class="button_s_red" onclick=("<?php echo $path; ?>")>{{ trans('setup_process.STEP2_Button') }}</button>
<?php endif; ?>

How could I refresh the following the php file? (Without the page reloading)

I've been playing around creating a control panel for gameservers, however I would love to show the user some CPU percentages. I totally can, but it doesn't update itself automatically. Here are my Codes
Note: This is not a working code, I mean it works, but only if you have load.php, which totally works, so I'm not going to bother showing it, it basically returns a number + %, to be able to modify the width of the progress bar.
What I want is pretty simple, I want the bar to update itself automatically. I just don't know why my code doesn't work.
<?php include '../includes/kezelohead.php'; ?>
<?php
include 'load.php';
//echo $cpu;
?>
<h5>Processzor Hasznalat</h5>
<div class="progress progress-striped" id="prog">
<div id='bar' class='progress-bar progress-bar-custom active' role='progressbar' aria-valuemin='0' aria-valuemax='100' style="width:100%;">
</div>
<script type="text/javascript">
var interval = setInterval(cpu, 2000);
function cpu() {
$("#scores").load("load.php #scores");
var data = <?php echo(json_encode($cpu)); ?>;
document.getElementById('bar').style.width = data;
//setTimeout(yourFunction, 5000);
}
</script>
<div id='scores'>
<?php
include 'load.php';
//echo $cpu;
?>
</div>
I've managed to solve the problem, with AJAX, so thanks everyone :)
I have used Ajax's load function, like so: $('#scores').load('load.php');

Why yii captcha always shows a fixed picture?

Captcha works with no problem, but I have no idea why it's not generating a new code to dislay? I've looked into the documents but could find something that could solve my problem.
Is there something here that I'm missing. thanks.
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
my view file:
<?php echo $form->labelEx($model,'verifyCode'); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
<?php echo $form->error($model,'verifyCode'); ?>
This is a known bug, that would most likely be fixed in Yii2.
On the Yii forums, user Black suggests:
My solution was to remove the session key on my controller action on get. Be careful not to remove it in any other place because it will probably fail on server validation.
$session = Yii::app()->session;
$prefixLen = strlen(CCaptchaAction::SESSION_VAR_PREFIX);
foreach($session->keys as $key)
{
if(strncmp(CCaptchaAction::SESSION_VAR_PREFIX, $key, $prefixLen) == 0)
$session->remove($key);
}
Another way to workaround would be to use JavaScript to click on the refresh link on every page load as mentioned by Soph:
$(function() {
$('#yw0_button').click();
});

MVC View Loading DIV but javascript not working

I can not figure this out.
I have a Controller that loads my main.php:
<div id="container"></div>
<script>$('#container').load('index.php?path=wizard&wizard_id=<?php echo $_GET['wizard_id']; ?> #wizard');</script>
"index.php?path=wizard&wizard_id=1" loads: view/module/wizard.php'
view/module/wizard.php looks like this:
<div id="wizard" data-wizard_id="<?php echo $groups_in_set['wizard_id']; ?>" data-total_sets="<?php echo $groups_in_set['total_sets']; ?>">
<div id="set" name="<?php echo $groups_in_set['wand_set']; ?>">
<?php foreach ($groups_in_set['groups'] as $group){ ?>
<!--Step Text -->
<h1><?php echo $group['group']; ?></h1>
<!--Step Detail -->
<div data-group="<?php echo $group['group']; ?>">
<script>alert("group");</script> // No script tags pass to main.php
<?php foreach($group['wands'] as $wand){ ?>
<span id="prompt_elements_<?php echo $wand->wand_id; ?>"></span>
<script>
// Load Wand
// Script not executing on ajax load
loadPromptElements('<?php echo $wand->prompt_type; ?>', <?php echo $wand->wand_id; ?>);
</script>
<?php } // End Wand Loop ?>
</div> <!-- End Group -->
<?php } // End Group Loop ?>
</div> <!-- End Set -->
</div> <!-- End Wizard -->
As you can see from my comments everything loads correctly except the "loadPromptElements" function. The entire script tag does not display in my rendered HTML. I can not figure this one out and need some help. Thanks community!!!
Regarding jQuery .load() handling of scripts:
If .load() is called with a selector expression appended to the URL [like #wizard], however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.
jQuery Reference Page
$('#container').load('index.php?...stuff... #wizard'); // <--- THAT
So you have a couple of options. Either find another way around using the #wizard selector after the URL in your .load() call or you can put it all (that one function) into a separate JS file and load it at the same time with .getScript(). You'll probably have to make it a PHP file so you can utilize the foreach() loop and whatnot.

How to run php code in javascript when callback is called?

I'm using easyModal to create modal windows in my web. Saw that they have callback onClose and I want use php code on close is it possible, if yes How to do that? I want to unset some values from sessions (don't have much experience in javascript, jquery or ajax)
This is my code:
<div id="ebox">
<?php
echo $_SESSION['unameE'];
echo $_SESSION['pwordE'];
echo $_SESSION['emailE'];
?>
</div>
$(function() {
$('#ebox').easyModal( {
autoOpen:<?php echo $error; ?>
onClose:???
});
});
Or maybe there is another solution that unsets values from session after displaying it once?
on your script you should have :
onClose: function(){
$("#ebox").html(' ') ;
$.post("remove-session.php");
}
and then on the page "remove-session.php" you can do all sort of stuff with your session:
<?php
unset($_SESSION['unameE']);
//...
//or even
session_destroy();
?>

Categories

Resources