I am currently working in wordpress and I have a link that is supposed to play a wav file depending on the title of the post. So if the post title is 'one' then it should play one.wav from the uploads folder. However, the sound file on every post only plays the most current posts title. So if I added a post called two and then a post called one, both posts will play one.wav.
Here's the code:
HTML
<span id="dummy"></span>
<a class="playSound" onclick="playSound();" href="#">
<i class="fa fa-volume-up"></i>
</a>
JQuery
function playSound() {
$.ajax({
url: 'sound.php',
data: "getSound",
type: "GET",
datatype: "html",
success: function(data) {
document.getElementById("dummy").innerHTML= "<embed src=\""+data+"\" hidden=\"true\" autostart=\"true\"loop=\"false\" />";
}
});
}
and the PHP
<?php
require('./wp-blog-header.php');
if(isset($_GET['getSound'])) {
$file='wp-content/uploads/2015/wav/' . get_the_title() . '.wav';
echo $file;
}
?>
I assume get_the_title() is the proper call but at this point I am not so sure. I have tried all the other call functions but still no luck. I assume at this point is has to do with the loading of the page and storing the initial posts title but i am just lost at this point.
<?php
$sound_query = new WP_Query();
if ($sound_query->have_posts()):
while ($sound_query->have_posts()):
$sound_query->the_post();
?>
<script>
function playSound() {
document.getElementById("dummy").innerHTML= "<embed src='wp-content/uploads/2015/wav/<?php echo get_the_title() ?>.wav' />";
}
</script>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
Change your sound.php file code like
<?php
require('./wp-blog-header.php');
global $post;
setup_postdata( $post );
if(isset($_GET['getSound'])) {
$file='wp-content/uploads/2015/wav/' . get_the_title( get_the_ID() ) . '.wav';
echo $file;
}
?>
You can simply get ride of your second php code and just use javascript:
function playSound() {
document.getElementById("dummy").innerHTML= "<embed src='wp-content/uploads/2015/wav/<?php echo get_the_title( get_the_ID() ) ?>.wav' />";
}
Everything is disjointed. The JS file doesn't know what post you are trying to target, and hence the sound.php file doesn't know either.
Pass the post ID to the JS file and then pass it to the sound.php file, then extract the post from that.
Also, try not using the post title for such things, use the ID as the post title and post name can be changed.
Example:
HTML
<a class="playSound" onclick="playSound(<?php echo $post->ID; ?>);" href="#">
<i class="fa fa-volume-up"></i>
</a>
JS
function playSound(postID) {
$.ajax({
url: 'sound.php',
data: data: {"postID": postID
type: "GET",
datatype: "html",
success: function(data) {
//Function here
})
}
PHP
if(isset($_GET['postID'])) {
$file='wp-content/uploads/2015/wav/' . $_GET['postID'] . '.wav';
echo $file;
}
Or something similar to that anyway.
Related
I'm trying to let user edit files they uploaded before.
I created a script, that returns the same HTML as is generated when I upload file.
function add_fineuploader_images () {
$post_id = $_POST['post_id'];
$media = get_attached_media( 'image', $post_id);
if ($media) {
foreach ($media as $image) {
?>
<li class="qq-file-id-0 qq-upload-success" qq-file-id="0" data-id="<?php echo $image->ID; ?>">
<span class="qq-upload-spinner-selector qq-upload-spinner qq-hide"></span>
<img class="qq-thumbnail-selector" qq-max-size="100" qq-server-scale="" src="<?php echo wp_get_attachment_image( $image->ID, 'thumbnail' );?>">
<span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>
<span class="qq-upload-file-selector qq-upload-file"><?php echo $image->post_title; ?></span>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
<a class="qq-upload-cancel-selector qq-upload-cancel qq-hide" href="#">Cancel</a>
<a class="qq-upload-retry-selector qq-upload-retry qq-hide" href="#">Retry</a>
<a class="qq-upload-delete-selector qq-upload-delete" href="#">Delete</a>
<a class="qq-upload-featured-selector qq-upload-set-featured" href="#">Set as featured</a>
<span class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
<?php
}
}
exit();
}
And on page load I'm calling AJAX Post to load the images into page:
var post_id = $('#post_id').val();
$.post(Ajax.ajaxurl, { action: 'add_fineuploader_images', post_id: post_id }, function(data) {
console.log(data);
$('.qq-upload-list').html(data);
});
This created the same preview, as when the files are uploaded via FineUploader.
Now, I would need to let FineUploader know about these, so DELETE and other methods work.
I initialize FineUploader like this:
$("#fine-uploader").fineUploader({
request: {
endpoint: Ajax.ajaxurl,
params: {
action: 'attach_files',
post_id: $('#post_id').val()
}
},
deleteFile: {
enabled: true,
endpoint: Ajax.ajaxurl,
method: 'POST'
}
});
How should I reinitialize FineUploader? Or, is there a better way to do this?
If you want to display files in the upload list that have been uploaded in a previous session, just use the Initial File List feature. No need to reinvent the wheel here. If you want to reset Fine Uploader, use the reset API method.
I've noticed that you are asking a lot of questions that are covered in the documentation. I encourage you to take a close look at the existing documentation and demos, which, we hope, are fairly comprehensive.
I have a main page in my app called index.php where i want to show some photos. Code in that file is:
<div id="main" name="main">
<input type="button" value="Photos" onclick="showIm()">
</div>
File function.php contains a function to show photos on the screen:
function showPhotos()
{
global $link;
$result = pg_query_params($link, 'SELECT photo_name FROM photos');
while($photos_row = pg_fetch_row($result))
{
echo '<a href="photos/'.$photos_row[0].'">
<img src="photos/'.$photos_row[0].'"></a>';
}
}
My last file is function.js where i try to call showPhotos using ajax
function showIm()
{
$.ajax({
url: "functions.php"
})
}
So inside the last function I want to call showPhotos() to get the results. I think that my implementation is a little complicated but I would like to know if anyone could help.
Well, you have to do something with that result! Add a success method and declare a return dataType
function showIm()
{
$.ajax({
url: "functions.php",
dataType: "html",
success: function(html) {
//do something with the response here
//the "html" variable will contain your PHP response
}
})
}
This is my html code
<td class="saltr" style=" border-color:#000; cursor:pointer;" id="<?php echo $grade["DEALID"];?>" onclick="dealid(this.id)" ><?php echo $grade["DEALINGS"];?></td>
on onclick() javascrip is written.
function dealid(psid)
{
var serow = psid;
//alert (serow)
$.ajax({url:"../views/printdeal.php?proc=dealing",data:"dealdatres="+serow,success:
function(z)
{
//alert("hiiiii")
alert(z);
//window.location="printdeal.php";
}
});
}
and in printdeal.php page the code is written as
if($_REQUEST["proc"]=='dealing')
{
$dealdatres1=$_REQUEST["dealdatres"];
include_once("../classes/dbqrs.php");
$obj=new qrys();
$qremp="select deals.PROSPECS ,deals.DEALINGS,deals.BUYER,deals.BENEFICIARY,deals.GUIDE,deals.REMARKS ,deals.DATES,salescal.DEALID from salescal left join deals on deals.ID=salescal.DEALID where salescal.DEALID='$dealdatres1'";
$empr=$obj->exeqry($qremp);
$empres=mysqli_fetch_array($empr);
?>
but when I run this code and when i click on it ,it shows a notice as undifined "proc" .
Please help me to solve this.
It looks like you have placed you function somewhere out of usual global scope. I don't know what should be changed as far as I cannot know your structure.
At first, move all function's content into onclick:
onclick='$.ajax({url:"../views/printdeal.php?proc=dealing",data:"dealdatres="+this.id,success:
function(z)
{
//alert("hiiiii")
alert(z);
//window.location="printdeal.php";
}
});'
and get a proof that there is something wrong with the name/placement only.
P.S. BTW read about addEventListener/attachEvent as strong and more convenient alternative to "onclick" usage.
We have kinds of ways to get the function,one of them like this:
You may write the code in view page :
$.ajax({
url: "<?php echo url('/soc/cnews/savetop') ?>",
type: 'post',
data: "sets=" + $("#top10").val(),
sync: false,
dataType: 'json',
success: function(data) {
if (data.status == 'success') {
window.location.reload();
} else {
alert(data.msg);
}
}
});
and the write the code in page which get data:
if($success){
echo "{status:'success',msg:'victory'}";
}else{
echo "{status:'failur',msg:'I am sorry to failure :('}";
}
And again: if you want get data via ajax,make sure print or echo the message on data page.
Try This
$.ajax({type: "POST",url: "../views/printdeal.php",data: { proc:"dealing",dealdatres=serow }});
if your problem in php, i think you can check values in global variables with
<pre>
<?php
var_dump($_REQUEST);
?>
</pre>
the result can be like this
array(2) {
["asd"]=>
string(3) "qwe"
["zxcv"]=>
string(5) "lkjsf"
}
that's result is from my localhost with url localhost/a.php?asd=qwe&zxcv=lkjsf
I'm trying to implement an Ajax request to load more posts on click.
However I've got an error : Call to undefined function query_posts()
Here is my Ajax script :
$('#next-container').click(function() {
var IDs = [];
$(".element").each(function(){ IDs.push(this.id); });
$('#next-container').html('loading');
$.ajax({
url: 'wp-content/themes/freakyshape/inc/data.php',
type: 'POST',
data: {'post_ids[]': IDs },
success: function(data) {
$container.isotope( 'insert', $(data));
}
});
});
my data.php file to load post:
<?php
if (isset($_POST['post_ids'])) {
$ids = array();
$ids[] = $_POST['post_ids'];
$posts_per_page = 8;
global $wp_query;
query_posts(array('post_type' => array('post', 'portfolio'), 'post__not_in' => $ids, 'posts_per_page' => $posts_per_page));
while (have_posts()) : the_post();
?>
// I do some stuff echo;
<?php
endwhile;
wp_reset_query();
}
?>
and in my functions.php:
$admin_path = TEMPLATEPATH . "/inc/";
require_once ($admin_path . "data.php");
What do I need to make it work?
EDIT:
I try with the right way to do it but nothing works like this... I miss something... It's not easy to correctly understand blog instruction when you are not fluent in English...
function.php:
add_action('wp_ajax_load_post', 'load_post_callback');
add_action('wp_ajax_nopriv_load_post', 'load_post_callback');
wp_enqueue_script('script', get_template_directory_uri().'/js/load_post.js', array('jquery'), '1.0', 1 );
wp_localize_script('script', 'ajax_var', array('url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('ajax-nonce')));
load_post.php :
<?php
function load_post_callback() {
if (isset($_POST['post_ids'])) {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) ) {
die ( 'Interdit !');
}
$ids = array();
$ids[] = $_POST['post_ids'];
$posts_per_page = 8;
global $wp_query;
query_posts(array('post_type' => array('post', 'portfolio'), 'post__not_in' => $ids, 'posts_per_page' => $posts_per_page));
while (have_posts()) : the_post();
$post_type = get_post_type( $post->ID );
if ($post_type == 'post') {
$post_type = 'blog';
}
?>
<div class="element normal <?php echo $post_type; ?>" id="<?php echo the_id(); ?>">
<div class="element-container">
<img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id()); ?>" class="thumbnail" />
<div class="element-back"></div>
<div class="element-description"><?php echo the_title(); ?></div>
<div class="element-category"><i class="icon"></i>   <?php echo $post_type; ?></div>
<a class="link" href="" title="<?php echo the_title(); ?>" onclick="gestionClic(compteur'id');">
<div class="more">more.</div>
</a>
</div>
</div>
<?php
endwhile;
wp_reset_query();
}
}
?>
load_post.js:
jQuery(document).ready(function() {
var url = ajax_var.url;
var nonce = ajax_var.nonce;
jQuery('#next-container').click(function() {
var IDs = [];
$(".element").each(function(){ IDs.push(this.id); });
console.log(IDs);
$('#next-container').html('loading');
$.ajax({
url: 'wp-content/themes/freakyshape/inc/load_post.php',
type: 'POST',
data: {'post_ids[]': IDs },//'post_ids='+IDs,
success: function($data) {
$container.isotope( 'insert', $data);
}
})
})
})
Using Ajax this way is not correct. For your code to work, you need to include wp-load.php and use some other workarounds. The web is full of this awful examples.
Otto, core contributor, explains the main reasons why we Don’t include wp-load, please.. And these are:
Why this is wrong
You don’t have the first clue where wp-load.php actually is. Both the plugin directory and the wp-content directory can be moved around
in the installation. ALL the WordPress files could be moved about in
this manner, are you going to search around for them?
You’ve instantly doubled the load on that server. WordPress and the PHP processing of it all now have to get loaded twice for every
page load. Once to produce the page, and then again to produce your
generated javascript.
You’re generating javascript on the fly. That’s simply crap for caching and speed and such.
The proper way is:
using wp_ajax_ hooks to run PHP code and return it to the JS file.
using wp_localize_script to pass PHP variables to the JS file.
One working example of mine at WordPress Answers. And lots of good examples from one of our mods and leading contributor to the Ajax tag.
Here is my function:
function loadNext(choice) {
$("#thequestion").load("question.php", { ans: choice, id: "<?php echo $row['id']; ?>", nextId: "<?php echo $nextQuestionId; ?>" } );
$("#graph").load("graph.php", { id:"<?php echo $row['id']; ?>", nextId: "<?php echo $nextQuestionId; ?>" } );
}
I execute the function and Firebug says the data is being posted, eg:
Parameters:
ans y
id 3
nextId 1
Source:
ans=y&id=3&nextId=1
But when I try to retrieve them in 'question.php' or 'graph.php' like so:
$id=$_GET["id"];
$nextId=$_GET["nextId"];
They echo back as null.
Any ideas?
EDIT: I've just noticed that the webiste URL does not change when the function is executed. Shouldn't ans=y&id=3&nextId=1 be appended onto it for the data to be sent? Or is this not the case for jQuery/ajax stuff?
EDIT 2: Sorry, this may be becoming really specific, but if I append the
/question.php?ans=y&id=3&nextId=1
manually, it all works fine! So now I'm really confused - this has narrowed the problem down to the function loadNext(choice), has it not?
Edit - (not op) suggested edit to include javascript and jquery tags.
From the jQuery load() API
The POST method is used if data is provided as an object; otherwise, GET is assumed.
Either change your PHP script to look in $_POST (or $_REQUEST if you're feeling lazy) or change the JavaScript to
$.get("question.php", {
ans: choice,
id: "<?php echo $row['id'] ?>",
nextId: "<?php echo $nextQuestionId ?>"
}, function(data) {
$("#thequestion").html(data);
});
Try this as well,
function loadNext(choice) {
$("#thequestion").load("question.php?ans=choice&id=<?php echo $row['id']; ?>&nextId=<?php echo $nextQuestionId; ?>" } );
$("#graph").load("graph.php?id=<?php echo $row['id']; ?>&nextId=<?php echo $nextQuestionId; ?>" } );
}