How to use jCarousel with PHP function? - php

I'm still learning both PHP and jQuery, and this seems to me to be a reasonably complex thing to try and do.
What I'd like to be able to do is use jCarousel's textscroller capability to display a list of URLs generated by a PHP function rather than the XML feed and URLs that jCarousel is written for. (Demo: http://sorgalla.com/projects/jcarousel/examples/special_textscroller.html)
The WordPress PHP function I want to use generates a list of URLs with some html markup for some or all posts in a WordPress category.
As a result, I think I don't need jCarousel's XML function or the html creator function, and I don't need to truncate strings.
So, is it possible to include the PHP function in the jQuery function, or would I have the jQuery function retrieve the URL list from the PHP function, something similar to providing a XML feed to jCarousel? Do I need to use the jQuery-PHP library? http://jquery.hohli.com
Any answers will be appreciated. - Mark
This are the jCarousel functions that use the XML feed: (I omitted document ready function)
function mycarousel_initCallback(carousel, state)
{
carousel.lock();
jQuery.get(
'special_textscroller.php',
{
'feed': 'http://jquery.com/blog/feed/atom/'
},
function(xml) {
mycarousel_itemAddCallback(carousel, xml);
},
'xml'
);
};
function mycarousel_itemAddCallback(carousel, xml)
{
var $items = jQuery('item', xml);
$items.each(function(i) {
carousel.add(i + 1, mycarousel_getItemHTML(this));
});
carousel.size($items.size());
// Unlock and setup.
carousel.unlock();
carousel.setup();
};
/**
* Item html creation helper.
*/
function mycarousel_getItemHTML(item)
{
return '<h3>'+$('title', item).text()+'</h3><p>'+mycarousel_truncate($('description', item).text(), 90)+'</p>';
};
/**
* Utility function for truncating a string without breaking words.
*/
function mycarousel_truncate(str, length, suffix) {
if (str.length <= length) {
return str;
}
if (suffix == undefined) {
suffix = '...';
}
return str.substr(0, length).replace(/\s+?(\S+)?$/g, '') + suffix;
};
And this WordPress PHP function:
<?php $my_query = new WP_Query('category_name=mycategory&showposts=10'); ?><?php while ($my_query->have_posts()) : $my_query->the_post(); ?><?php the_title(); ?><br /><br /><?php endwhile; ?>
generates html like this:
link title<br /><br />link title<br /><br />, etc....
which is the html I'd like the jCarousel text scroller to display.

you seem to be missing the actual call to start the carousel
the html needs to be wrapped in a div
<div id="mycarousel">
link title<br /><br />
link title<br /><br />, etc....
</div>
then call
jQuery('#mycarousel').jcarousel({
vertical: true,
size: 0,
initCallback: mycarousel_initCallback
});

in
function mycarousel_initCallback(carousel, state){
carousel.lock();
jQuery.get(
'special_textscroller.php',
{
'feed': 'http://jquery.com/blog/feed/atom/'
},
function(xml) {
mycarousel_itemAddCallback(carousel, xml);
},
'xml'
);};
this method you need to put your WP-php file name in place of "special_textscroller.php"
file or can change the "special_textscroller.php" with your WP function .
Again , you need to send output via XML format only if you do not want to change other "jCarousel" functions.

Related

HTML-PHP Relative Path to Absolute Path

Hi I am basically trying to fetch a page via php, get its html and change the html(to highlight some keywords) to a bit and display it as a overlay in my page(jquery).
//My php page data.php
<?php
$html= file_get_contents($_GET['url']);
echo $html;
?>
//My jquery ajax request to data.php from page main.html
function test()
{
$.ajax({
type: 'GET',
url: 'data.php',
data: 'url=http://www.developphp.com/view_lesson.php?v=338',
cache: false,
success: function(result)
{
$("#overlay").append(result);
}
});
}
}
As you can see, since the webpage uses relative URL, I am having issues displaying it in a overlay. I tried searching for a way to convert relative to absolute but did not find anything useful. Can you guys please point me in the right way?
Can start here
function test(){
var domain='http://www.developphp.com/', path= 'view_lesson.php?v=338';
$.ajax({
type: 'GET',
url: 'data.php',
data: { url: domain + path},
cache: false,
success: function(result)
{
var $html=updatePaths( $(result) );
$("#overlay").append($html);
}
});
}
function updatePaths( $html, domain){
/* loop over all images and adjust src*/
$html.find('img').attr(src,function(i, src){
if(src.indexOf(domain) ==-1){
src= domain+src
}
return src;
})
/* return updated jQuery object*/
return $html;
}
This will only work for simplest case where remote site isn't using a variation of the domain you use like not using www and you do. Also won't work if image paths are set usng ../ to move up a directory.
You would have to create a far more robust set of tests to manipulate the final path you use correctly.
My intent was to show you how to manage situation
I ilke #charlietfl's solution. However, somehow I think it gives more sense to manipulate the scraped content serverside before passing it to the client. You can do that by using DomDocument.
The following code converts all <img> src relative paths to absolute paths before echoing the result. Use the same approch for the <a> tags href attributes and so on,
error_reporting(0); //suppress DOM errors
$basePath='http://www.developphp.com/'; //use parse_url to get the basepath dynamically
$content=file_get_contents('http://www.developphp.com/view_lesson.php?v=338');
$dom=new DomDocument();
$dom->loadHTML($content);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src=$image->attributes->getNamedItem("src")->value;
if (strpos($basePath, $src)<=0) {
$image->attributes->getNamedItem("src")->value=$basePath.$src;
}
}
echo $dom->saveHTML();
With all your help, I did something like this,
Instead of trying to replace the relative by absolute path, I appended the base url html tag to the scrapped content.
<?php
include 'URL2.php';
error_reporting(0); //suppress DOM errors
$content=file_get_contents($_GET['fullURL']); //http://somewebsite.com/page1.html
$url = new Net_URL2($_GET['fullURL']);
$baseURL= $url->host; //http://somewebsite.com
if(strpos($baseURL,'http://')<0)
{
$baseURL='http://'.$baseURL;
}
$dom=new DomDocument();
$dom->loadHTML($content);
$head = $dom->getElementsByTagName('head')->item(0);
$base = $dom->createElement('base');
$base->setAttribute('href',$_GET['baseURL']);
if ($head->hasChildNodes()) {
$head->insertBefore($base,$head->firstChild);
} else {
$head->appendChild($base);
}
echo $dom->saveHTML();
?>

Can I call the function from php class using jquery ajax?

I begin with an object-oriented programming in php.
I want to do the logging - using ajax and jquery.
EDIT: Can I call the function ajax from file jquery.php - using jquery AJAX?
//FILE jquery.php
class jquery {
public function ajax() {
echo "result";
}
}
If you make an ajax call similar to this :
http://example.com/ajax.php?firstParam=1
Within your ajax.php file you can do something like this :
switch($_GET['firstParam']){
case "1":
callYourFunction();
break;
case "2":
someOtherFunction();
break;
}
This is a very stripped down example... In a real world case you would have to take security into account and sanitize any information you are getting from outside your server (i.e. from a user).
The names I have given are only place holders - you can change the function/variable names to whatever you feel comfortable with.
I hope this sheds some light on your conundrum.
Not sure if you completely understand what AJAX is, but it's an acronym for Asynchronous JavaScript and XML. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behaviour of the existing page. That's it.
This I believe is what you're looking for (though its not OOP, but im not writing an entire OOP login to try answer your question)
File: login.php
<?php
$db = new PDO("mysql:host=localhost;dbname=database", SQL_USER, SQL_PASS );
$stmt = $db->prepare('SELECT user_id, user_activated FROM users WHERE ( username = AND user_password = ? LIMIT 1');
$stmt->execute( array( $_POST['u'], $_POST['p'] ) );
if( $stmt->rowCount() == 1 )
{
// Authentication session storage stuff here
echo 'Logged in';
}
else
{
echo 'bad login';
}
?>
So you could have a HTML page with something like:
<div id="results"></div>
<input type="text" id="txtUsername" /> <br />
<input type="password" id="txtPassword" /><br />
<button id="cmdLogin">Login</button>
<script>
$(document).ready(function(){
$("#cmdLogin").click(function(){
$u = $("#txtUsername").val();
$p = $("#txtPassword").val();
$.ajax({
type: "POST",
url: "http://yoursite.com/login.php",
data: "u="+u+"&p="+p
}).done(function(results) {
$("#results").html(results).hide().fadeIn();
});
});
});
</script>
Also, keep in mind this code is un-tested and written it as replying to this, so don't treat this as a solution to what you're wanting, but rather a resource to help you to implement what it is you're asking for.
You cannot call a class directly - but you can fetch the result of an execution.
Here an example how you can call it nearly direct - but don't use this for critical login code.
<?php
$ftcn = $_GET['getname'];
$bc = new ReallyBadCode();
$bc->$ftcn();
class ReallyBadCode{
function test(){
}
function __call($name, $args){
$this->$name($args);
}
}

Cannot Access Global PHP Variable in jQuery.ajax call in MediaWiki

I'm running into trouble accessing global variables when I make an AJAX call to a php function in the MediaWiki framework.
My jQuery AJAX call looks like this:
jQuery.ajax({
url: 'GeneralFunctions.php',
type: 'GET',
dataType: 'json',
data: {
text: anchorText
},
success: function (data) {
alert("data: " + data);
}
});
My GeneralFunctions.php file looks like this:
<?php
if (isset($_GET['text'])) {
jsonInlineParse((string) $_GET['text']);
}
function jsonInlineParse($wikiText)
{
global $wgOut;
$return = $wgOut->parseInline($wikiText); //fails here
echo json_encode($return);
}
?>
When I run the jQuery call through a click event I get as far as the parseInline() function. The global variable is never defined in the scope and I get the error:
Fatal error: Call to a member function parseInline() on a non-object in /path/to/file/GeneralFunctions.php on line 54
I'm not sure how to make the parse call and define the global variable when the AJAX call is made?
UPDATE
$wgOut is the OutputPage object associated with MediaWiki. It holds all the HTML of the page and is used throughout the MediaWiki framework to add content to a page or article. It is used on the server side to create customized output for wiki articles. I use it to create forms or add HTML on many of our wikis.
More info here: http://www.mediawiki.org/wiki/Manual:$wgOut
UPDATE 2
#Juhana I changed my function to look like this which results in the same error as before. Each echo outputs "NULL".
<?php
function jsonInlineParse($wikiText)
{
include_once '/path/to/file/includes/OutputPage.php';
include_once '/path/to/file/includes/parser/Parser.php';
echo var_dump($wgOut);
global $wgOut;
echo var_dump($wgOut);
$return = $wgOut->parseInline($wikiText);
echo $return;
echo json_encode($return);
}
?>
I took a different approach after running into global variable problems. I changed the AJAX call I was making and the code below works very well for me. I'm using the editable jquery table you can find here.
PHP
function ajax_parse(){
global $wgRequest;
if($wgRequest->wasPosted()){
$text = $wgRequest->getVal("text");
wfDebug("Recieving::::".$text);
if(!strpos($text, "href")){
$text = myInlineParse($text);
$text = str_replace("<pre>", "", $text);
$text = str_replace("</pre>", "", $text);
}
wfDebug("Returning::::".$text);
echo $text;
}
exit;
}
function myInlineParse( $wikiText ) {
global $wgOut;
return $wgOut->parseInline( $wikiText );
}
JavaScript
// inject wikitext after hitting save
function postSave(o) {
var response = new Array("");
for(var i=0;i<o.row.length;i++){
new Ajax.Request(wgScript +'/Special:EditClass/ajax_parse',
{
asynchronous: false,
parameters: {'text': o.row[i].innerHTML},
onSuccess: function(text){
response.push(text.responseText);
}
}
);
}
return response;
}
For whatever reasons, extensions don't seem to have access to $wgOut. I solved this for my extension by using the hook: OutputPageParserOutput for the code I needed output (I needed to inject some scripts and stylesheets as well as using another hook to modify links and didn't want to bother with Resource_Loader though it is useful and recommended):
$wgHooks['OutputPageParserOutput'][] = array($this, 'doOutputPageParserOutput'); // 'doOutputPageParserOutput' defined as method in my class
As with other hooks, you can get rid of the array in favor of just a function name if you don't want to execute within a class.

jquery including post request (exchanging vars)

i'm a little stuck with a jQuery. At the moment my function looks like this.
$(function(){
$(".url2").keyup(validNum).blur(validNum);
function validNum() {
var initVal = $(this).val();
outputVal = initVal.replace(/(https?:\/\/)?(www.)?[0-9A-Za-z-]{2,50}\.[a-zA-Z]{2,4}([\/\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#]){0,250}(\s){1}$/
,"http://my.site/ref.php?id=<?php $code = unqiue-ref-id(); echo $unqiue-ref-id;?>");
if (initVal != outputVal) {
$(this).val(outputVal);
return false;
}}
});
So right now it rewrites a user typed url (in a textarea) to a redirection link with my own url (e.g. my.site?ref.php?id=unique12. What I need exactly is a POST Request to a php file (code below) where the valid user-url is given to the php file as a var and then the php file should give back a var with the generated unique unique-ref-id. I do of course know that the code above isn't working like that, it only shows how the final result should look like. The php file wich generates the unique-ref-id looks like this.
function unqiue-ref-id() {
$unqiue-ref-id = "";
$lenght=4;
$string="abcdefghijklmnopqrstuvwxyz123456789";
mt_srand((double)microtime()*1000000);
for ($i=1; $i <= $lenght; $i++) {
$shorturl .= substr($string, mt_rand(0,strlen($string)-1), 1);
}
return $unqiue-ref-id;
}
$user-url = // var send from jquery
do{
$unqiue-ref-id = unqiue-ref-id();
} while(in_array($unqiue-ref-id, $result));
// var send back to jquery function => final results of do function above
// Here i add the $user-url and $unique-ref-id to datebase (Dont need code for that)
?>
Would be so great if someone can help me out with that. Thanks a lot :)
Use the POST jQuery's method. Here's an example
$.post('URL-TO-POST-DATA', {'parameter1': 'value', 'parameter2': 'value'}, function(data_received){
/** Here goes your callback function **/ alert(data_received);
});
More information about POST method
Don't forget one thing. jQuery will not receive nothing if you don't use echo on PHP (instead of return). You MUST use echo in PHP, don't forget it.

Querying a function in functions.php?

I have a jQuery code that is going to check when the user is near the bottom of the page. That's not the problem though. This jQuery is going to send a AJAX request, giving it some details on what to load when the user is near the bottom of the page. The code looks a bit like this at the moment:
$("<div>").load('?ajax=y&offset=something', function() {
$(".empty-div").append($(this));
setTimeout(function(){ console.log('after', $(document).height()); }, 0);
setTimeout(function(){ console.log('after', $(window).height()); }, 0);
});
My main problem is that I don't know what to query or how to go about sending the information to the PHP function in functions.php. For example, I have at the moment this as my PHP function (until it's working):
function get_posts_page() {
if(isset($_GET['offset'])) {
echo"Hello!";
}
}
I'm aware the wordpress has add_action and all that but I have no idea what I would apply as an action to either function to make the PHP recieve the data the Javascript is sending. Is there a URL where all functions are parsed or something? Thanks for any help in advance. So how do I get the data from the Javascript to the PHP function in functions.php, in my theme directory?
I just made a video to show you how to use the add_action request in WordPress. You can watch it here.
Here's my javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
$('#branding img').click(function() {
$.post('<?php bloginfo('siteurl') ?>/wp-admin/admin-ajax.php', {
action: 'my_unique_action',
offset: 5
}, function(data) {
$('#content').prepend('<p>' + data + '</p>');
});
});
</script>
And the php that I used in functions.php
// Make sure it runs when the user is logged in,
// and when they are not.
add_action('wp_ajax_my_unique_action', 'get_offset');
add_action('wp_ajax_nopriv_my_unique_action', 'get_offset');
function get_offset() {
if( isset($_POST['offset']) ) {
echo 'Your ajax request was successful. Here was your offset: <strong>' . $_POST['offset'] . '</strong>';
}
die;
}
Reference: http://codex.wordpress.org/AJAX_in_Plugins
You're trying to call a PHP function from Javascript, correct?
You'll need some logic on some page which calls get_posts_page(). Either you can create a new page getPostsPage.php?offset= or you can put some logic in functions.php, something like
if(isset($_GET['function']) {
switch($_GET['function']) {
case 'get_posts_page':
get_posts_page();
}
}
However, the former approach is recommended; you don't want someone to be able to modify the function parameter and access deleteAllPosts() maliciously.
Therefore:
// getPostsPage.php
require PATH . 'functions.php';
get_posts_page(); //checks $_GET['offset']
And remember to fail gracefully (do not expose an error message) if 'offset' is not set, or whatever.

Categories