WordPress Excerpt - Javascript - PHP - Ajax? - ajax

I've created this script inside my home.php file for my WordPress theme to calculate the value of a div width in relation with a number (1.408). This operation give me the result (inside $chars variable) to establish number of characters to use in the excerpt for Responsive Design. If the div is larger or thinner, I'll have a different number of characters for my WordPress Excerpt.
This is the code I've published on HOME.PHP. Javascript followed by PHP code for excerpt.
I know javascript variable inside PHP is impossible without Ajax (reading on other forums), but I cannot understand what exactly to do. I am not so good with code. Be clear please and if possible with some examples!
<script type='text/javascript'>
jQuery(document).ready(function() {
var $myDiv = jQuery('#last_post_img_text');
var $results = jQuery('#results');
var $chars = jQuery( $myDiv.outerWidth()/1.408 );
</script>
<?php new_excerpt( $chars ); ?>

I would suggest an approach:
Load a page, check conteiner element width and height, then use $.ajax to load elements content, and send some kind of a variable to decide how many characters to use.
If You would like to do it in WordPress way, read about:
add_action('wp_ajax_$handlename', 'function_to_run');
add_action('wp_ajax_nopriv_$handlename', 'function_to_run');
that will reposnd to Yours ajax request.
wp_enqueue_script( 'theme_js', get_bloginfo('template_url') . '/js/jquery-theme.js', array('jquery'), THEME_VERSION, false );
$protocol = isset( $_SERVER["HTTPS"] ) ? 'https://' : 'http://';
$params = array( 'ajaxurl' => admin_url( 'admin-ajax.php', $protocol ) );
wp_localize_script( 'theme_js', 'theme_js', $params );
this might come handy, if You dont know how to send wp-ajax.php localisation to jQuery $.ajax request.

Reloading the comments with Ajax seems like a bad decision. Why would you want to keep reloading content that doesn't really change. I think your best bet is to use a jQuery plugin.
One that seems to do what you want is http://www.bramstein.com/projects/text-overflow/.
Alternatively you can check out the CSS3 property 'text-overflow' (http://www.w3schools.com/cssref/css3_pr_text-overflow.asp).

Related

do_shortcode not running ajaxlaodmore shortcode

I am using ajaxloadmore plugin. it works perfect from the code below inside template.
but when I call above code from the ajax call it returns empty divs with no records.
can someone let me know why it dosen't work from ajax call.
Ajax load more plugin uses ajax to load posts. Why are you not using its inbuilt functionality? You cannot use ajax inside PHP code for another ajax.
If you use this shortcode in ajax action, I don't think it will load it's JS files. If you could share some more details about what you are trying to achieve here, I might be able to help.
Also, if it does work somehow, you also need to manage the offset parameters or you will end up loading the same post again and again.
Edit 1-
You can reload the page when the user selects a category and by default, you can use all categories.
Try below code:-
if ( isset( $_GET[ 'category' ] ) && $_GET[ 'category' ] !== '' ) {
$cat = esc_html( $_GET[ 'category' ] );
} else {
$cat = "in-the-news,leadership,tips-tricks,trends";
}
echo do_shortcode( '[ajax_load_more post_type="post" posts_per_page="6" category="' . $cat . '" ]' );

Force frontpage language

I have got a multilingual joomla 2.5 website with sef urls enabled. The page relies heavily on ajax, so every kind of content is pulled from the server after the good old
window.onload
event. To make everything work proper and urls look nice, I want to force Joomla to always respond in the sites default language if the page loaded and the index.php of the template in invoked.
Or to describe the problem diffrent:
If an ajax-call pulls an item which is different from the default language and a page-refresh follows, joomla redirects to the homepage in the language of the last ajax-call, that is what I want to prevent.
Greetings
Got it working! The question itself was wrong! I should have been asking: "How to redirect to frontpage in default language?"
Answer:
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
$languages = JLanguageHelper::getLanguages('lang_code');
$lang = JFactory::getLanguage();
$defaultLang = ( $lang->getTag() == $lang->getDefault() ) ? $lang : JLanguage::getInstance( $lang->getDefault() );
if( ! ( $lang->getTag() == $defaultLang->getTag() ) ){
$app->redirect( JRoute::_( 'index.php?lang='.$languages[ $defaultLang->getTag() ]->sef ), 'hallo', true );
}
Done!
Greetings....

jQuery Ajax Request - Lose Method

I have a page index.php that uses a modal to upload files. After those have uploaded I use the following to update my database and load in the new images to a list.
$('#sortableImages').load('../includes/sortImages.php?edit=' + edit);
Executes:
<script type="text/javascript">
$(document).ready(function(){
$(function() {
$("#sortableImages ul").sortable({
opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("../albumUploader/queries/sort.php", order);
}
});
});
});
</script>
echo "<ul class='revisionList'>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $getGalleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='recordsArray_{$row['id']}' >";
echo '<img src="'. $sortPath .'"/>';
echo "</li>";
}
echo "</ul>";
The images populate in a div #sortableImages on the index page. However it seems that I lose my method of sortable() from the js file that was originally loaded in the index.php or after the ajax request it's not reading the js. What am I missing here?
Thanks a million.
When you load script from a remote page using ajax, it is important to realize that the ready event has already occured in page you are loading into.
This means that code wrapped in $(function(){}) will fire as soon as it is received. If that code preceeds the html it refers to, it will not find that html, as it doesn't exist yet.
If you move the same code below the html it refers to, it will fire after the html exists and therefore will find it.
EDIT: My answer presumes that all the code shown after "Executes:" in OP is contained in remote page
You have no handler for the result of the sort.php. Invoking this will only load the data into cache.
You need a complete handler function to refresh the data, not to mention add it to the dom. You should clarify your question and make it obvious that those are two different pages.
$.post("../albumUploader/queries/sort.php", order).complete = func...

Drupal 7 ajax_command_* creates unwanted div

I'm populating a select box using an AJAX callback in Drupal 7. I've tried both ajax_command_append() and ajax_command_html() to set the new <option...> statements, but both these wrap the HTML that I create inside a <div>. This causes the <select> to not display any of the options.
Is there a way to tell Drupal "Hey stupid, this is exactly the HTML I want, don't mess with it"?
I can code some jQuery to remove the div I guess, but it would be a lot better if I can prevent it from being added in the first place.
Yes you can!
Declare your own custom js callback. In below example, I used a span instead of the divs. But you can obviously remove the wrapper alltogether.
PHP:
function my_ajax_callback() {
$data = 'saved!';
// instead of using ajax_command_html, we provide our own
// js custom callback function
$output = array(
'#type' => 'ajax',
'#commands' => array(
array('command' => 'myjscallback', 'data' => $data),
),
);
return $output;
}
JS:
$(function() {
Drupal.ajax.prototype.commands.myjscallback = function (ajax, response, status) {
$('#save-btn-message').html('<span>' + response.data + '</span>');
};
});
The answer is yes.
Just use this instead:
$commands[] = ajax_command_invoke('#mywrapper', 'html', array($output));
So it seems the answer is "no" (or at least not without hacking core, and I'll have no dead kittens on my conscience).
misc/ajax.js contains the following:
var new_content_wrapped = $('<div></div>').html(response.data);
The comments therein go on to explain why they require the first HTML element to be a top-level one. If it is, the <div> wrapper is not used. In my case, I'm replacing <option> elements, so I get the <div>.
Now I could just replace the entire <select>, but that causes other issues in my case due to scripts that style things at page load. Rather than find those and re-fire them, it looks like it'll be easier to just ajax_command_invoke a script to run after my options are loaded to remove the div wrapper.
EDIT: As a workaround, I found I can do ajax_command_invoke($selector, 'html', array('<option...>')); and it bypasses the div addition code. Kinda sneaky, but it works...
you can use seen on this link http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax
for more reference and example download this module http://drupal.org/project/examples
it has all the examples of custom code and "ajax_example" as well
It works for me!
$selector = '#my-select';
$method = 'append';
$opts = array('new option');
$commands[] = ajax_command_invoke($selector, $method, $opts);
return array('#type' => 'ajax', '#commands' => $commands);

How can I return actual JSON using Drupal?

I'd like to implement a simple AJAX function locally that allows me to autocomplete node titles of already existing nodes as the user types. To that end, I need the ability to have an API that I can search on node titles. The problem is that when I output raw JSON, it comes surrounded by tags. So, no matter what I do, I keep getting...
<html>
<head>
</head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;"> {json here}</pre>
</body>
</html>
I've tried implementing a custom page template that only outputs content already, that produced the same results. Here is how I am currently doing this, in my module file...
<?php
/**
* Implementation of hook_menu()
*/
function content_relation_menu() {
$items = array();
$items['api'] = array(
'title' => 'Search',
'page callback' => 'content_relation_get',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
function content_relation_get($term = '') {
drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
$var = json_encode(
db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
);
echo $var;
exit(0);
}
How can I return JUST raw JSON?
The 'Drupal' way is using drupal_json_output() and drupal_exit().
$data = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll();
drupal_json_output($data);
drupal_exit();
UPDATE
I've just put your code, as is, into a module and all I get when requesting http://site.com/api is the expected JSON, there are no tags. The problem won't be anything to do with Drupal, more likely to do with server/browser configuration.
This link may help:
What do browsers want for the Content-Type header on json ajax responses?
This actually DID output raw JSON - Chrome was adding the html wrapping. Viewing the output in command line cURL showed that this did output raw JSON.
Take out the exit(0); and it should work. If your page callback doesn't return anything then the normal theme handlers don't get called so you get raw output.
That said, due to the rather poor performance of Drupal, for decent response times you're better off making a small standalone script that talks to the drupal DB, so you don't pay the rather heavy startup costs of a drupal request when you don't need of that functionality.

Resources