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];
}
Related
i'm working on setting up a page that uses PHP to layout the page, but i also need this PHP HTML code inserted into the PHP page for a search function. The search is done on a different page, and then the action is sent to the results page. I'm trying to get the PHP and HTML to mix together. I've tried using echo to no success. Basically i need the PHP HTML code to put the results into the $layout->content("");
<?php
require_once($_SERVER["DOCUMENT_ROOT"].'/layout/layout.inc.php');
require_once($_SERVER["DOCUMENT_ROOT"].'/functions/general.inc.php');
$layout = new default_layout();
$layout->title('IT KB Search');
$layout->content("<div class='border'>");
$layout->content('<h1>IT Support Knowledge Base - Search Results</h1>');
if (isset($_GET['q'])) {
$query = rawurlencode( strip_tags($_GET['q']));
$timestamp = time();
$baseUrl = 'https://oursite.atlassian.net/wiki';
$url = $baseUrl.'/rest/api/content/search?cql=space=KB%20AND%20type=page%20AND%20title~'.$query;
// To enable authenticated search:
// $url .= "&os_username=$username&os_password=$password";
$response = file_get_contents($url);
$response = json_decode($response);
$results = $response->results;
Echo '<div>';
Echo ' <ol>';
foreach($results as $item) {
Echo ' <li><strong><a href="';
$baseUrl. $item-> _links-> webui
Echo ' " target='_blank'>';
$item->title
Echo ' </a></strong></li>';
}
Echo ' </ol></div><hr>';
}
$layout->content("</div>");
$layout->render();
?>
You can to store the HTML to a string and then pass it to the $layout->content() function, like this...
<?php
require_once($_SERVER["DOCUMENT_ROOT"].'/layout/layout.inc.php');
require_once($_SERVER["DOCUMENT_ROOT"].'/functions/general.inc.php');
$layout = new default_layout();
$layout->title('IT KB Search');
$layout->content("<div class='border'>");
$layout->content('<h1>IT Support Knowledge Base - Search Results</h1>');
if (isset($_GET['q'])) {
$query = rawurlencode( strip_tags($_GET['q']));
$timestamp = time();
$baseUrl = 'https://oursite.atlassian.net/wiki';
$url = $baseUrl.'/rest/api/content/search?cql=space=KB%20AND%20type=page%20AND%20title~'.$query;
// To enable authenticated search:
// $url .= "&os_username=$username&os_password=$password";
$response = file_get_contents($url);
$response = json_decode($response);
$results = $response->results;
# Change Starts
$html = '<div>';
$html .= '<ol>';
foreach($results as $item) {
$html .= '<li><strong><a href="';
$html .= $baseUrl. $item-> _links-> webui;
$html .= '" target="_blank">';
$html .= $item->title;
$html .= '</a></strong></li>';
}
$html .= '</ol></div><hr>';
$html .= '</div>';
$layout->content($html);
# Change Ends
}
$layout->content('</div>');
$layout->render();
I'm generating dynamic content from a database like this:
$sql_select_items = $db->query("SELECT * FROM table WHERE ...);
Then it pulls the results, which may be one or multiple, like this:
while ($item_details = $db->fetch_array($sql_select_items))
{
$items_content =
'<table><tr> '.
'<td>RETRIEVED CONTENT HERE</td> '.
'</tr></table>';
}
Then, further down, I am outputting the generated content like this:
if ($section == 'summary_main')
{
$summary_page_content['content'] =
$summary_page_content['details'] .
$items_content .
$summary_page_content['messaging_received'] .
$summary_page_content['footer']
;
$template->set('members_area_page_content', $summary_page_content['content']);
}
Everything works except for the content generated by $items_content , which only displays 1 item no matter if there are 1 or 20. I tried to do a
$items_content . =
instead of
$items_content =
but that didn't seem to work either and just gave me an error.
What am I doing wrong?
It's not $db->fetch_array($sql_select_items) it's $sql_selected_items->fetch_array(). Here's how I would do it:
$table_rows = $db->query("SELECT * FROM table WHERE ...");
if($table_rows->num_rows > 0){
$table = '<table><tbody>';
while($row = $table_rows->fetch_object()){
$table .= "<tr><th>{$row->title_column_name}</th><td>{$row->other_column_name}</td></tr>";
}
$table .= '</tbody></table>';
}
else{
$table = '';
// no results
}
echo $table;
$table_rows->free(); $db->close();
Outside of (before) the while loop:
$items_content = '';
Inside the while loop:
$items_content .= '...';
This will make sure that your $items_content variable exists before your loop, and then the .= will concatenate your string to the end of $items_content.
"What am I doing wrong?"
As you didn't post the error, I can only assume you either got an undefined variable notice, which is solved by placing $items_content = ''; before the loop, or your got a syntax error because the operator you should be using is .= and not . = (note that the space is wrong).
I have a class that is building some HTML using data stored in an array. There are around 100 items in this array. Each item includes information like company name, a description, and flags for the different programming languages the company supports. I am doing string concatenation as I build the HTML for each item.
I have noticed that performance suddenly takes a huge hit when I append the programming language data. I see the page rendering timer jump from 0.15 secs to ~0.60 secs. This time includes grabbing the same data from the database each time. I can consistently get the performance to jump between these 2 times but commenting/uncommenting the following line of code:
$html .= '<div class="programmingLanguages"><strong>Programming Languages</strong> '.implode(', ', $progLanguagesArray).'</div>';
I've also been able to get the same performance drop by appending a long test string, something like this:
$html .= 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest';
What's especially bizarre is that I have another line of code that uses the same 'implode' function and does NOT make any significant difference in performance:
$html .= '<div class="integrationMethods"><strong>Integration Methods:</strong> '.implode(', ', $intMethodsArray).'</div>';
Does anybody have any insight into what might be going on here? I am doing tons of concatenation like this elsewhere in my code and haven't seen anything like this before. At this point, I'm stumped.
Here's the full class:
class DeveloperView {
public static function getHtml($developers) {
$html = '';
$html .= '<div>';
$html .= '<div>';
$count = 0;
foreach ($developers as $developer) {
$url = $developer['attributes']['url'];
$phone = $developer['attributes']['phone'];
$company = $developer['attributes']['desc'];
$active = $developer['attributes']['active'];
$desc = $developer['object_value'];
$intMethodsArray = array();
if ($developer['attributes']['m1']) { $intMethodsArray[] = 'method 1'; }
if ($developer['attributes']['m2']) { $intMethodsArray[] = 'method 2'; }
if ($developer['attributes']['m3']) { $intMethodsArray[] = 'method 3'; }
if ($developer['attributes']['m4']) { $intMethodsArray[] = 'method 4'; }
if ($developer['attributes']['m5']) { $intMethodsArray[] = 'method 5'; }
$progLanguagesArray = array();
if ($developer['attributes']['dotnet']) { $progLanguagesArray[] = '.Net (C# or VB.Net)'; }
if ($developer['attributes']['asp']) { $progLanguagesArray[] = 'Classic ASP'; }
if ($developer['attributes']['cf']) { $progLanguagesArray[] = 'Cold Fusion'; }
if ($developer['attributes']['java']) { $progLanguagesArray[] = 'Java'; }
if ($developer['attributes']['php']) { $progLanguagesArray[] = 'PHP'; }
if ($developer['attributes']['perl']) { $progLanguagesArray[] = 'Perl'; }
if ($developer['attributes']['other']) { $progLanguagesArray[] = 'Other'; }
$html .= '<div class="';
if ($count % 2 == 0) {
$html .= 'listingalt';
} else {
$html .= 'listing';
}
$html .= '">';
$html .= '<div class="developerPhone">'.$phone.'</div>';
$html .= '<a class="ext_link" target="_blank" href="'.$url.'">'.$company.'</a>';
$html .= '<div>';
if (!empty($intMethodsArray)) {
$html .= '<div class="integrationMethods"><strong>Integration Methods:</strong> '.implode(', ', $intMethodsArray).'</div>';
}
if (!empty($progLanguagesArray)) {
$html .= '<div class="programmingLanguages"><strong>Programming Languages</strong> '.implode(', ', $progLanguagesArray).'</div>';
}
$html .= '</div>';
$html .= '<p>'.$desc.'</p>';
$html .= '</div>'."\n";
$count++;
}
$html .= '</div></div>';
return $html;
}
}
Now that I can provide an answer, I'll just post my follow-up comment as the 'answer'...
I did indeed have a 'bug' in my timer, in that it was calculating the end processing time AFTER the echo of the HTML. So the amount of data being sent to the browser was effecting the processing time, where I was expecting to see the time spent processing BEFORE transmitting any data.
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.
I have the code below:
$result = mysql_query("SELECT link, notes FROM links WHERE username='will';");
$html .= "<ul>";
while ($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "<li>{$link} - {$notes}</li>";
}
I need the bit where it says {$link} to become a clickable link which opens a new window. How would I do this?
When I put tags around it you get this error:
The error is: Parse error: syntax error, unexpected '{' in /data/www/vhosts/themacsplash.com/httpdocs/ClipBoy/will.php on line 18
Line 18 is $html .= "<li>{$link} - {$notes}</li>";
In general you make a link like this: link title. So in your case like this:
$html .= "<li>{$link} - {$notes}</li>";
First create a correct code and make error handeling, than set variables outside quotes.
$qry = "SELECT link, notes FROM links WHERE username='will'";
$mysqlqry = mysql_query($qry);
if($mysqlqry){
if(mysql_num_rows($mysqlqry) > 0){
$html .= "<ul>";
while($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "<li>". $notes ."</li>";
}
}
}
if your $link contains an url in the form "http://www.example.com/", use this:
$html .= "<li>{$notes}</li>";