I'm having a logical problem with my script. The point would be to get a some rows formatted in a table but the header should not be repeated and under all the items should be outputted and than as variable passed to ajax . But I don't see how to solve this.
function abc()
{
global $mainframe;
$db =& JFactory::getDBO();
// Check for request forgeries
if(isset($this->message)){
$this->display('message');
}
// custom: generate token for ajax request
$ajax_token = JHTML::_( 'ajax.token' );
// custom end
// JRequest::checkToken( 'get' ) or jexit( 'Invalid Token' );
$letter_raw = JRequest::getVar('val');
$letter = substr($letter_raw, -1);
$response = '<div class="no-rec">not found</div>';
$html = '';
if (!empty($letter)) {
$query = " SELECT * FROM #__glossary WHERE substr(tterm,1,1) LIKE '$letter%'";
$db->setQuery( $query );
$rows = $db->loadObjectList();
if (count($rows)) {
$header='<table class="stripeMe"><tbody><thead><tr><th>Begriff</th><th>Definition</th></tr></thead><tr>';
foreach($rows as $key => $row) {
$body='<td><span class="title">'.$rows[$key]->tterm.'</span></td><td>'.$rows[$key]->tdefinition.'</td></tr></tbody></table>';
}
$response = $header.$body;
}
$html = $response;
echo $html;
}
}
What exactly is the problem? :)
You probably should not make it a function, since I guess you are just going to load the content in with AJAX?
And you should ADD to the string not override it in each row.
UPDATED, FIXED HTML ERRORS
if (count($rows)) {
// CREATE TABLE AND HEAD
$body = '<table class="stripeMe"><thead><tr><th>Begriff</th><th>Definition</th></tr></thead>';
// TBODY FOR REPEAT INSIDE
$body .= '<tbody>'
foreach($rows as $key => $row) {
$body .= '<tr><td><span class="title">'.$rows[$key]->tterm.'</span></td><td>'.$rows[$key]->tdefinition.'</td></tr>';
}
$body .= '</tbody></table>';
$response = $body;
}
$html = $response;
echo $html;
Well if you are passing the data back as HTML than this will work so your jquery would be:
$('#holderdiv').load('abc.php');
If you are using Something like .post .ajax .get, then you will need to decide what format to pass the data back with so if it's JSON then you will need to format it as such and make sure that your jQuery is told to expect such a response. I can give more help if you can be specific about your situation and what problems you are having.
Related
I've written some code in php to scrape some preferable links out of the main page of wikipedia. When I execute my script, the links are coming through accordingly.
However, at this point I've defined two functions within my script in order to learn how to pass links from one function to another. Now, my goal is to print the links in the latter function but it only prints the first link and nothing else.
If I use only this function fetch_wiki_links(), I can get several links but when i try to print the same within get_links_in_ano_func() then it prints the first link only.
How can I get them all even when I use the second function?
This is what I've written so far:
include("simple_html_dom.php");
$prefix = "https://en.wikipedia.org";
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links = $prefix . $links;
return $absolute_links;
}
}
function get_links_in_ano_func($absolute_links)
{
echo $absolute_links;
}
$items = fetch_wiki_links($prefix);
get_links_in_ano_func($items);
Your function returned the value at the very first iteration. You will need something like this:
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
$absolute_links = array();
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links []= $prefix . $links;
}
return implode("\n", $absolute_links);
}
I know the get_avatar() function but its not working. Maybe its due to the complexity of the loops? Please take a look at the code below and let me know! Thanks!
function displaymeta(){
global $post;
$m_meta_description = get_post_meta($post->ID, 'my_meta_box_check',
true);
global $wpdb;
$user_nicenames = $wpdb->get_results("SELECT id,user_nicename FROM
{$wpdb->prefix}users", ARRAY_N);
foreach($user_nicenames as $nice_name)
{
foreach($nice_name as $name)
{
foreach($m_meta_description as $val)
{
$flag=strcmp($name,$val);
if($flag==0)
{
echo"<li>";
echo $name. "<br>";
echo get_avatar($name->ID,50);
echo"</li>";
}
}
}
}
}
add_filter( 'the_content', 'displaymeta' );
I've tried $name,$nice_name, $user_nicenames in function get_avatar($val->ID,50); but nothing seems to work! What am I missing here?
You've already used the right function, which is get_avatar().
But the problem is that the $name as in get_avatar($name->ID,50) is not an object. Instead, it's a string, which could be the user ID or display name (i.e. the user_nicename column in the WordPress users table).
So try replacing the foreach in your displaymeta() function with the one below, where I assigned $name to $nice_name[1], and the user ID is assigned to $user_id:
foreach($user_nicenames as $nice_name)
{
$user_id = $nice_name[0];
$name = $nice_name[1];
foreach($m_meta_description as $val)
{
$flag=strcmp($name,$val);
if($flag==0)
{
echo"<li>";
echo $name. "<br>";
echo get_avatar($user_id,50);
echo"</li>";
}
}
}
Additional Note
If you remove the , ARRAY_N as in: (but you don't have to remove it. These are just extra info..)
$user_nicenames = $wpdb->get_results("SELECT id,user_nicename FROM
{$wpdb->prefix}users", ARRAY_N);
then the variable $nice_name would be an object. Hence you can then access $nice_name->user_nicename like this:
$user_id = $nice_name->id;
$name = $nice_name->user_nicename;
UPDATE
In reply to your comment on the missing content, it's because you didn't capture the variable that WordPress passes through the the_content filter. And you also need to append the LI's to that $content, and finally return the modified content (i.e. $content).
So try this code (which is already utilizing the new foreach code as I provided before or above):
function displaymeta( $content ){
global $post;
$m_meta_description = get_post_meta($post->ID, 'my_meta_box_check',
true);
global $wpdb;
$user_nicenames = $wpdb->get_results("SELECT id,user_nicename FROM
{$wpdb->prefix}users", ARRAY_N);
// Add the opening UL tag. Remove if not needed.
$content .= '<ul>';
foreach($user_nicenames as $nice_name)
{
$user_id = $nice_name[0];
$name = $nice_name[1];
foreach($m_meta_description as $val)
{
$flag=strcmp($name,$val);
if($flag==0)
{
$content .= "<li>";
$content .= $name. "<br>";
$content .= get_avatar($user_id,50);
$content .= "</li>";
}
}
}
// Add the closing UL tag. Remove if not needed.
$content .= '</ul>';
return $content;
}
add_filter( 'the_content', 'displaymeta' );
Hope that helps! =)
I am attempting to add a date function I created to my JSON data that I am sending back with PHP. I cannot figure out how to properly assign the function in my separate php file and send back. The function is on my main page (comments page) and not in this php file.
However, on my main comments page, when not using JSON (just a normal PHP SELECT query, the function works just fine.
I do it on my comments page (the page without the issue) like this:
$comment_array[] = $comment_date;
echo '<div class="comment-post-date">'.fixDate($comment_date). '</div>';
This is how I try to do it in the php file that isn't working when sent back. It is actually giving an error in the console:
Unexpected token <
I attempt to assign it as a variable and then send it back as this:
$html .= '<div class="comment-post-date">'.$fixed_comment_date. '</div>';
Full code:
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
$select_comments_stmt->execute();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
$comments = array();
foreach ($rows as $row) {
$comment_date = $row['date'];
$fixed_comment_date = fixDate($comment_date);
$html = "";
$html .= '<div class="comment-post-box" id="comment-'.$row['id'].'">';
//$html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">';
$html .= sprintf(
'<img class="home-comment-profile-pic" src="%s">',
empty($row['img']) ? 'profile_images/default.jpg' : $row['img']
);
$html .= '<div class="comment-post-info-block">';
$html .= '<div class="comment-post-username">'.$row['username']. '</div>';
$html .= '<div class="comment-post-date">'.$fixed_comment_date. '</div>';
$html .= '</div>';
$html .= '<div class="comment-post-text">'.$row['comment']. '</div>';
$html .= '</div>';
$data = array('id' => $row['id'], 'date' => $row['date'], 'html' => $html);
$comments[] = $data;
}
}
echo json_encode($comments);
Any ideas how I can get this to work?
Unexpected token < usually means your script didn't output JUST json. It output html+json, which is illegal JSON.
If you're doing a request for which JSON is expected as the response, then any OTHER output, other than the actual json response, will be treated as a JSON syntax error.
e.g.
echo '<div>blahblalblah</div>';
echo json_encode($whatever):
will cause your unexpected token error, because the first < in the <div> line is already a JSON syntax error.
That also means that things like PHP warnings/errors that are output will also become part of the response, and ALSO trigger a syntax error.
You shouldn't take by json HTML code only mysql results, e.g.
$comments['id'][] = $row['id'];
$comments['username'][] = $row['username'];
//next one
//next one
//next one
echo json_encode($comments);
And in JS code:
var count = json.id.length;
for(var i = 0; i<count; i++)
{
var id = json.id[i];
var username = json.username[i];
}
I'm in the process of learning php so forgive me if this is a silly question. I'm trying to make a dynamic gallery that looks through a folder(./JIN/snoii/) and produces the html code for the number of items in said folder. This code I've written isnt returning anything when the file has images(currently has over a hundred) can some one tell me where I messed up or point me in the right direction. Thanks in advance
$CurrentViewFile = "snoii";
function showGallery(){
global $CurrentViewFile;
$galleryHTML = "<h1>Dynamic gallery</h1>";
$galleryHTML .= "<ul>";
$folderToview = "JIN/";
$folderToview .= $CurrentViewFile;
$images = new DirectoryIterator($folderToview);
while($images->valid()){
$galleryHTML .= "<li>!!</li>";
$images->next();
}
$galleryHTML .= "</ul>";
return $galleryHTML;
}
return showGallery();
Your DirectoryIterator makes the problem,
Please try like this
$CurrentViewFile = "/snoii";
function showGallery(){
global $CurrentViewFile;
$galleryHTML = "<h1>Dynamic gallery</h1>";
$galleryHTML .= "<ul>";
$folderToview = "JIN/";
$CurrentViewFile .= $folderToview;
foreach (new DirectoryIterator($CurrentViewFile) as $images) {
if($images->valid())
$galleryHTML .= "<li>!!</li>";
$images->next();
}
$galleryHTML .= "</ul>";
return $galleryHTML;
}
$output_data = showGallery();
echo $output_data;
If you want to get file name from the iterator you should use like this,
$images->getFilename()
I am using a formbuilder plugin in Wordpress which submits the form input to the database as XML data. Now I would like to fetch that data and have it displayed in another page. I have started trying simpleXML to achieve this but now I have hit a road bump.
The XML data that appears in each row of the database follows this format:
<form>
<FormSubject>Report</FormSubject>
<FormRecipient>****#***.com</FormRecipient>
<Name>admin</Name>
<Department>test</Department>
<Value>1000</Value>
<Comments>test</Comments>
<Page>http://***.com</Page>
<Referrer>http://****.com</Referrer>
</form>
I have previously managed to fetch the data that I need using simpleXML from an XML string of the same markup which is in the database but now my question is, how do I do this with a loop for each row in the database?
When the following code is run, wordpress displays a blank page meaning that there is an error:
<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$string = $statistic->xmldata
$xml = simplexml_load_string($string);
$Name = (string) $xml->Name;
$Department = (string) $xml->Department;
$Value = (string) $xml->Value;
$Comments = (string) $xml->Comments;
echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";
?>
You are missing ; on line 5
$string = $statistic->xmldata
Should be
$string = $statistic->xmldata;
You should consider enablign WP_DEBUG constant in wp-config.php file. Insert following code to your wp-config.php, just before /* That's all, stop editing! Happy blogging. */
define('WP_DEBUG', true);
/* That's all, stop editing! Happy blogging. */
For more tips on debugging, read the codex
Formbuilder users custom function to extract XML data in formbuilder_xml_db_results Class:
function xmltoarray($xml)
{
$xml = trim($xml);
$match = "#<([a-z0-9_]+)([ \"']*[a-z0-9_ \"']*)>(.*)(</\\1>)#si";
$offset = 0;
if(!preg_match($match, $xml, $regs, false, $offset)) {
return($xml);
}
while(preg_match($match, $xml, $regs, false, $offset))
{
list($data, $element, $attribs, $content, $closing) = $regs;
$offset = strpos($xml, $data) + strlen($data);
$tmp = $this->xmltoarray($content);
$result[$element] = $tmp;
}
return($result);
}
Define that function in your code (before global $wpdb; you don't have to be afraid of same name as that function is defined in Class) and than modify your code in this way:
<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$xml = xmltoarray( $statistic->xmldata );
$Name = (string) $xml['form']['Name'];
$Department = (string) $xml['form']['Department'];
$Value = (string) $xml['form']['Value'];
$Comments = (string) $xml['form']['Comments'];
echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT: edited $xml['Comments'] to $xml['form']['Comments'] and analogous
I fixed it by stripping the backslashes from the XML string using stripslashes()