Assigning Wordpress query result to js variable - javascript

I am extremely new to WordPress customisation world and I am working on a task, where I am supposed to assign the content of specific page of WordPress to the JS variable, I am able to fetch the content of the page i need and I can also see in the chrome console tab the content of the page being assigned to the variable, however i am stuck at the error
Uncaught SyntaxError: Unexpected token <
Here is the code I wrote, I am not sure if this is the right way to do things in WordPress but it does seem to give me the result I need so any correction on this approach is also welcome
<script>
jQuery(document).ready(function ($) {
var intern = '<?php
$internPageId = jobboard_option('intern_tab_page');
$the_query = new WP_Query('page_id='.$internPageId);
while ($the_query->have_posts()) :
$the_query->the_post();
the_content();
endwhile;
wp_reset_postdata()?>';
var company = '<?php
$companyPageId = jobboard_option('company_tab_page');
$the_query = new WP_Query('page_id='.$companyPageId);
while ($the_query->have_posts()) :
$the_query->the_post();
the_content();
endwhile;
wp_reset_postdata()
?>';
$('#intern-content').click(function () {
console.log(intern);
$('div.tabs-content').html(intern);
});
$('#company-content').click(function () {
$('div.tabs-content').html(company);
console.log(company);
});
});
</script>
As you can see the code does seem to pull the text of the page but with an error.
What am i doing wrong?

Check this out
<?php
$internPageId = jobboard_option('intern_tab_page');
$post_me = get_post($internPageId);
$excerpt = $post_me->post_content;
$companyPageId = jobboard_option('company_tab_page');
$post_me2 = get_post($companyPageId);
$excerpt2 = $post_me2->post_content;
?>
<input type="hidden" id="intern_tab_page" value="<?php echo $excerpt;?>">
<input type="hidden" id="company_tab_page" value="<?php echo $excerpt2;?>">
<script>
jQuery(document).ready(function ($) {
var intern = $('#intern_tab_page').val();
var company = $('#company_tab_page').val();
$('#intern-content').click(function () {
console.log(intern);
$('div.tabs-content').html(intern);
});
$('#company-content').click(function () {
$('div.tabs-content').html(company);
console.log(company);
});
});
</script>

Related

Video Current time giving undefined

Hello I have dynamic videos which I tried to get the current video time but I seem to be getting undefined which i don't know why. I fire a function using on time update javascript event, however when i alert this var ok=$(e).attr('id'); i get the videos id but i dont know why when i try to get video current time i get undefined as value, these is my code dont know where i am getting it wrong.
<script type='text/javascript'>
function men(e){
var ok = $(e).attr('id');
var ol = $(e).attr('id');
// alert(ol[0].currentTime); --- GIVES ME UNDEFINED
$.ajax({
type : 'POST',
url : 'updatetime.php',
data : {ok: ok, om: om},
success : function(r)
{
}
});
}
</script>
<?php
$tl="channel";
$ooa="playing";
$played="played";
$timeline = mysqli_query($con, "SELECT * FROM plays WHERE streamers_type ='$tl' AND played !='$played' GROUP BY streamers_id ORDER BY id ASC") or die ();
while($row = mysqli_fetch_array($timeline)) {
$id = $row['id'];
$file1 = $row['file1'];
$video_name = $row['video_name'];
$video_type = $row['video_type'];
?>
<video class="uopi spinal" id="<?php echo $id ?>" style="height:180px; width:100%!important;" autoplay muted onended="run(this)" ontimeupdate="men(this)"><source src="plays/<?php echo $file1 ?>" type="<?php echo $video_type ?>"></video>
<?php } ?>
What you're doing is
var ol = $(e).attr('id');
ol[0].currentTime;
But .attr('id') returns a string, the ID of the element, which clearly doesn't have a currentTime property.
Try doing
$(e)[0].currentTime
instead

Access Wordpress PHP Variables within Plugin JS

edit: I'm now wondering how I can access post ID from within plugin (outside of loop). If I try to get the post id, it returns 0.
How does one access a specific page's PHP variables within a plugin JS file?
I originally had the JS in the page template file but have moved it to a plugin. Now I am unsure how to access that page's PHP variables. Maybe move the PHP logic to a plugin function?
content-course.php (JS)
<?php
$user_id = get_current_user_id();
$course_id = $post->ID;
$vimeo_progress = 0;
$vimeo_seconds = 0;
if ( is_user_logged_in() ) {
// Run WP query to retrieve user progress
$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $course_id) );
if ($row) {
$vimeo_seconds = $row->seconds_played;
$vimeo_progress = $row->progress_percent;
}
}
?>
<script>
jQuery(document).ready(function($) {
var progress = <?php echo $vimeo_progress; ?>;
var seconds = <?php echo $vimeo_seconds; ?>;
var userProgress = <?php echo $vimeo_seconds; ?>; //example user data retrieved
var lastUpdateProgress = <?php echo $vimeo_progress; ?>;
var videoUrl;
var courseID = <?php echo $course_id; ?>;
</script>
How would the JS script be able to access the PHP variables if moved to the plugin? Do I need to move the PHP above the script to a plugin function.. because then I am not sure how it would pass the data to the JS.
Wordpress have a classified function for the job
wp_localize_script()
Take a look. It's very easy to do.
http://codex.wordpress.org/Function_Reference/wp_localize_script

Javascript send array to PHP using ajax

I am trying to send an array from javascript to PHP script using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function() {
var parms = [];
parms.push($(this).text());
});
</script>
<script>
function loadXMLDoc()
{
$.ajax({
type: "POST",
url: "update.php",
data: { value : $(parms).serializeArray() },
success: function(data)
{
console.log (data);
}
});
}
$("button").on('click',function(){ loadXMLDoc(); });
</script>
In my $.output function, I am using the parms [] array to store all the UI slider values which I am trying to pass on to the next PHP script page on a button click event as defined in loadXMLDoc() function. In my PHP page, I am accessing them as below.
<?php
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
// Do whatever you want with the $uid
?>
However, I am not able to view the data in my update.php script. Can someone please let me know what am doing wrong?
This is the link to my work so far.
serializeArray returns the json object ,maybe you could try json_decode in your php script,simply like:
$uid_arr = json_decode($uid,true);
print_r($uid_arr);
Just Use
data: $(parms).serializeArray()

Create a single JS function for all products in magento for add to cart using Ajax method

I have created a instant add to cart buttons successfully in Magento. I have done it using Forms and Java script i.e. each product displayed on the page has its own form and its won JavaScript function created on the form accordingly.
So, If I display 60 products in one page, it leads to 60forms and 60 js functions. Is there anyway where I can use a single JS for all the forms/products? ...I have tried and looked everywhere but unable to get a solution.
Here is the Form and JS:
<form action="<?php echo $this->getSubmitUrl($_product) ?>" method="post" id="product_addtocart_form<?php echo $this->htmlEscape($_product->getId())?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<button1 title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cartsd" onclick="productAddToCartForm<?php echo $this->htmlEscape($_product->getId())?>.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>
<?php echo $this->getChildHtml('', true, true) ?>
</form>
JS :
var productAddToCartForm<?php echo $this->htmlEscape($_product->getId())?> = new VarienForm('product_addtocart_form<?php echo $this->htmlEscape($_product->getId())?>');
productAddToCartForm<?php echo $this->htmlEscape($_product->getId())?>.submit = function(button) {
if (this.validator.validate()) {
var form = this.form;
var e = null;
var oldLabel;
try {
this.form.request({
parameters: { adeptaajax:'true' },
onSuccess: function(transport){
var json = transport.responseText.evalJSON();
var displayString = json.message;
if(json.success) {
jQuery("#topCartContent").load("page/ #element > *");
jQuery("#cartHeader1").load("page/ #element2 > *");
}
alert(displayString);
},
onFailure: function(transport){
alert("<?php echo $this->__('There has been a problem adding your product. Please try again later.'); ?>");
}
});
} catch (e) {
}
if (e) {
throw e;
}
}
}.bind(productAddToCartForm<?php echo $this->htmlEscape($_product->getId())?>);
</script>
As you dont want to fire 60 requests and there is no checkout cart controller action which is able to add more than one product, you propably have to write your own addMultipleAction in a class extending Mage_Checkout_CartController.
There is a blog entry i found via a 2 second google search which seems to do exactly this:
http://www.danneh.org/2010/09/adding-multiple-products-to-the-cart-simultaneously-in-magento/

JavaScript FF IE Update + message script issue

I have this ajax_update script that updates file.php every 60 seconds..
Now file.php outputs this after updated a table:
<div id='message' style="display: none;">
<span>Hey, <b><? echo $userid; ?></b>, You've got +1 points, you now have <u>
<? echo $n["points"]; ?></u></span>
X
</div>
<script>
$("#message").fadeIn("slow");
</script>
Why will this only work in FF, i mean appear, but not in IE..
What I am trying to do is that after file.php have updated a field in the database(points), there will come up a message like stackoverflow at the top(just like when you earn a badge) saying that you have received 1 point.
This works perfectly in FF but in IE, the message is not showing at all?
Maybe another way to do this? Or a fix, solution?
I tried to put the little JS script in the index.php and remove the ajax update thing, and it works fine in IE.
function addpoints() {
var userid = document.getElementById('user_id_points');
var postFile = 'addpoints.php?userid='+ userid.value;
$.post(postFile, function(data){
$("#message").fadeIn("slow");
$("#points").html(data);
setTimeout(addpoints, 62000);
});
}
function closeNotice() {
$("#message").fadeOut("slow");
}
my ajax script^
<?php
include "tilslut.php";
$userid = $_GET["userid"];
$s = mysql_query("SELECT points, lastpoint FROM member_profile WHERE user_id = '".$userid."'");
$n = mysql_fetch_array($s);
$tid = time();
mysql_query("UPDATE member_profile set points = points+1, lastpoint=$tid WHERE lastpoint<=$tid-60 AND user_id = '".$userid."'");
if(isset($userid)) {
$e = mysql_query("SELECT points FROM member_profile WHERE user_id = '".$userid."'");
$f = mysql_fetch_array($e);
echo $n["points"];
}elseif (mysql_affected_rows() == 1) {
$s = mysql_query("SELECT points FROM member_profile WHERE user_id = '".$userid."'");
$n = mysql_fetch_array($s);
?>
If you receive this text, no problem with php
<div id="message" onclick="closeNotice()">this works
</div>
<?
}else{
?>
This doesnt work at all
<?
}
?>
my php coding, with the
In your ajax update script, call this after the results are in:
$("#message").fadeIn("slow");
Scripts coming back as part of the request are unreliable, putting the logic in your ajax result function is a better approach in this case.
Try this for your ajax call:
function addpoints() {
var postFile = 'addpoints.php?userid='+ $('#user_id_points').val();
$.post(postFile, function(data){
$("#points").html(data).find("#message").fadeIn("slow")
setTimeout(addpoints, 62000);
});
}
Solved this by adding a
header('Content-type: text/html; charset=utf-8');
in the top in addpoints.php

Categories

Resources