return json string with html characters? - php

i want to call a php with jquery ajax to perform some database things and then return 2 lists of links. so i have to pass these two link lists back to jquery so it can display list 1 in the left side of the webpage and list 2 in the right side.
i created the lists in separate arrays that i send back to jquery with json_encode but i noticed that it escapes all the html characters.
<a>dog</a> became <a>dog<\/a>
so when i displayed the list in the html they werent links anymore.
how can i preserve the html codes in my returned arrays to jquery?
EDIT: is this the right way to go if you want to split up data from php so that jquery can display them in different locations in html?
// list 1
while($row = mysqli_fetch_assoc($saved_tags))
{
$display_saved_tags[] = "<a id='showtag' href='answer.php?id=" . $row['id'] . "'>" . $row['name'] . "</a><br />";
}
// list 2
while($row = mysqli_fetch_assoc($related_tags))
{
$display_related_tags[] = "<a id='showtag' href='answer.php?id=" . $row['id'] . "'>" . $row['name'] . "</a><br />";
}
// return lists to jquery
echo json_encode('display_saved_tags' => $display_saved_tags, 'display_related_tags' => $display_related_tags));

json_encode's escape characters directly conflict with HTML output. I have had the same issue but decided to use an alternative solution at the time. I just had a thought that you could perhaps do this:
$data = new stdClass();
$data->html1 = base64_encode('<h1>html in here</h1>');
$data->html2 = base64_encode('<p><strong>more html</strong></p>');
echo json_encode($data);
On the frontend:
callbackFunction(json) {
alert(base64_decode(json.html1));
alert(base64_decode(json.html2));
}
You would need the javascript implementations of base64_decode and utf8_decode which can be found at:
http://phpjs.org/functions/base64_decode:357

use can use below function to un-escape the chars when reading or sending on to the browser:
html_entity_decode('your response here');
Also because your are using json_encode, make sure that you don't need the below function in your code:
json_decode

Related

How do I get custom PHP to use existing CSS styling in Wordpress

I am using woody snippets to insert php code to make an API call to return information in a table. How do I get the table to display using the default css from my wordpress theme?
I am new to PHP, but not to wordpress. And I know just enough CSS to get myself in trouble. So, I need ELI5 instructions.
My programmer provided the basic PHP code to call the API and return the data in a basic table. But, it looks horrid and there's no spacing or styling.
$tableStart = "<table>";
$tableEnd = "</table>";
$trStart = "<tr>";
$trEnd = "</tr>";
$tdStart = "<td >";
$tdEnd = "</td>";
$fname = 'alabama_energy_data.json';
$data = json_decode(file_get_contents($fname));
echo $tableStart;
foreach($data as $bill_data)
{
echo $trStart;
echo $tdStart . $bill_data->bill_id . $tdEnd . $tdStart . $bill_data->title . $tdEnd;
echo $trEnd;
}
echo $tableEnd;
This returns a basic table with the data I need, but it's not styled. How do I get it to use the default CSS from our wordpress site that it's displaying in so that the table renders in a format that looks decent?
If your table isn't styled like it should be, then you're probably missing and id or class attribute at your table. You could check on what current attributes your "wordpress" tables have, and just add them to your table.
Example:
<table class="wp-class-table">
# OR
<table id="wp-id-table">
And one other thing, I personally don't really like the way you "echo" your data. If you want, you can read this answer. It shows a nicer way to do it in my opinion.

How can i json_encode long html?

If I have a large html markup that gets populated with values from the database and gets echoed containig lots of divs that have classes:
echo "<div>";
echo"<div class='className'> {$_results['value']} </div>";
echo"</div>";
. . .
// large markup incoming
How can I save this in a variable so I can send it back as json ? is it possible to do that ?
This is what I am trying to do:
$html = "echo "<div>";
echo"<div class='className'> {$_results['value']} </div>";
echo"</div>";"
echo json_encode(array('html'=> $html, 'otherValue' => $_results['otehr']);
I just don't know how to save all the html in a variable so I can send it back in an array along with other values that need to be used separately.
Using echo means that you output strings. So, if you don't need to output all strings, then concatenate them into one and assign this final string to a variable, e.g.:
$html = "<div>"
. "<div class='className'>" . $_results['value'] . "</div>"
. "</div>";
echo json_encode(array('html'=> $html, 'otherValue' => $_results['otehr']));
A simple fiddle.
I will give you what I think is a great advice.
Use a template system for this, I will recommend you mustacheJS
It will be a little difficult the first time, but you will gain a better and clear code.

build link using postgresql and php

)
I have a question:
I have a databse with the following information:
Name of report [name]
Link to report [link]
The various reports are displayed in tables in my page (using db_tables filed with static, month, week etc)
But i want to generate a link to the report based on "link" and "name"
so i set up a pgsql query :
result = select name, link from db where type = 'week'
This works fine.
To display the above i have:
echo "<div id=\"selMaand\">" ;
echo "<table id = \"t2\">\n ";
echo "\t<tr class=\"head\">\n";
echo "<th colspan=\"2\">Select Maand</th>";
while ($line = pg_fetch_array($result5, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td width=\"100%\">$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
echo "</div>";
which works fine to.
Now, the link from database is http://192.168.178.1:8080/etc/etc/page.html"onclick humptydumpty>name
each time i want to adjust something in either the onlclick or address, i have to change all my links.
What can i insert in my querys so i will be able to build a link like;
echo "<a href = "http://192.168.178.1:8080/etc/etc/**$link**"onlclick humptydumpyu>**$name**</a>
I cant figure out how to break down my array!
Thanks in advance
Sjoerd
If you just need a portion of your URL in the database (i.e. only a portion of it would change for each record), then only store that portion of the URL in the database. You can then generate the remaining portion of the URL (call it the URL base) in your code.
So something like this:
define('URL_BASE', 'http://some.url.base/that/you/can/change/globally/');
Then you get the remaining piece of the URL from the database for each item. So you would have something like this inside your query loop to build the full URL.
$link = $line['link'];
$final_url = URL_BASE . $link;
As far as the onclick stuff goes, I would have that set sepearately as well, since I assume the onclick behavior is not dependent on the individual link (if it is you can make a separate DB column for it).
define('LINK_ONCLICK', 'onclick="some_onclick_function()"');
And in your query loop you can put this together like this:
$name = $line['name'];
$link = $line['link'];
$final_url = URL_BASE . $link;
echo '<a href="' . $final_url . '" ' . LINK_ONCLICK . '>' . $name . '</a>';
Note that it is not really necessary to define the strings for the url base and onclick behavior as constants. I just showed it this way as it is common practice to set globally defined values that do not need to change at run-time ion such a manner.

php var value contains quotes

So... I have a mysql_fetch_array and I'm running into an issue when some of the mysql data contains single or double quotes. This is the dumbed down version of my code:
while($row=mysql_fetch_array($list)) {
echo "<tr>";
echo "<td onclick='edit_form(\"" . $row['item'] . "\");'>" . $row['item'];
echo "</td></tr>";
}
The edit_form() function is used to send the value of the current item back to the value of the input in the form so the user can then easily edit their entry and then sends an UPDATE command to mysql along with the proper primary key id (which I left out because of irrelevancy). The only issue I have is if a user puts single or double quotes into the form then it messes up the onclick attribute. Please help!! I am pretty new to php and can't figure this out. I've messed around with htmlentites() and html_entity_decode() but am still getting no where. Thank you so much!
Use htmlspecialchars on $row['item'] before inserting it in your document.
So your "dumbed-down" code should be:
while($row=mysql_fetch_array($list)) {
$item = htmlspecialchars($row['item']);
echo "<tr>";
echo "<td onclick='edit_form(\"" . $item . "\");'>" . $item;
echo "</td></tr>";
}
Try the below line instead of the original in your code and see if it works:
echo "<td onclick='edit_form(\"" . str_replace('"',"&quote;",$row['item']) . "\");\">" . $row['item'];
And where you would like to display the $item field, just replace it in reverse if you get &quote; instead of ' " '. For example:
$qoute_free= str_replace('&quote','"',$passed_value);
If you are using it in javascript, the function can be as below:
function edit_form(passed_value)
{
new_value=passed_value.replace(/&quote;/g,'"');
}
I advise using json_encode. That way you don't have to worry about special cases htmlspecialchars might miss (such as newlines).
while($row=mysql_fetch_array($list)) {
echo "<tr>";
echo "<td onclick='edit_form(" . json_encode($row['item'], JSON_HEX_APOS) . ");'>" . $row['item'];
echo "</td></tr>";
}
I'm just putting the values back into my <form> (when they click on a <td>) and when they hit SUBMIT it directs the data to a different .php file that uses a MySQL UPDATE instead of an INSERT. I finally found some code that works!
$list is a mysql_query I ran at the top of the document
$item is the title of one of my columns in MySQL
while($row=mysql_fetch_array($list)){
$item = json_encode($row['item']);
$item = str_replace("'","'",$item);
echo "<td onclick='edit_form(" . $item . ");'>" . $row['item'] . "</td>";
}
Now it display's correctly in the <form> when <td> is clicked (by jQuery input.val($item)) and it shows up in the table correctly via $row['item']. I don't really understand exactly how it's working (how the encode is making it work) but I am glad it is. Crazyness!!!! Thanks for responding! and thanks for your effort!!

PHP help with styling content from a database

I'm new to PHP as building a site for my company as a college project. I'm looking to style and split the text into two columns on the following page... http://c-hall.the-word.com/assignment/artwork.php Was wondering the best way to go about this. I get that some of this will be done using CSS, but as the text is pulled in from a database how do I split this into two columns? As for styling am I right in using for example <h1> tags etc in the text on the database?
Thanks for your help - Charley
In what format is the text that you retrieve from the database? Here is a semi-pseudo-code that shows how to retrieve text from db and show it in two columns:
echo "<table>";
$result = mysql_query(...)
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>" . $row['lefttext'] . "</td><td>" . $row['righttext'] . "</td></tr>";
}
echo "</table>";
Still we can't help you until we know in what format the retrieved text is.

Categories