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.
Related
Im new to learning PHP as you might have guessed. I have the contents of a .txt file echoed but I would like it to stand out more, so I figured I would make it a different colour.
My code without colour:
<?php
$file = fopen("instructions.txt", "r") or exit("Unable to open file");
while(!feof($file))
{
echo fgets($file);
}
fclose($file);
?>
I have researched this and seen suggestions to others to use a div style, however this didn't work for me, it gave me red errors all the way down the page instead! I think its because I'm using 'fgets' not just a variable? Is there a way to colour the echo red?
The code I tried but doesn't work:
echo "<div style=\"color: red;\">fgets($file)</div>";
(In general) You need to separate the actual PHP code from the literal portions of your strings. One way is to use the string concatenation operator .. E.g.
echo "<div style=\"color: red;\">" . fgets($file) . "</div>";
String Operators
Other answer already told that you can't use a function call in a double quoted string. Let additionally mention that for formatting only tasks a <span> element is better suited than a <div> element.
Like this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
You should try:
<div style="color: red;"><?= fgets($file);?></div>
Note: <?= is an short hand method for <?php echo fgets($file);?>
This version does not need to escape double quotes:
echo '<div style="color:red;">' . fgets($file) . '</div>';
You can do this with the concatenate operator . as has already been mentioned but IMO it's cleaner to use sprintf like this:
echo sprintf("<div style='color: red;'>%s</div>", fgets($file));
This method comes into it's own if you have two sets of text that you want to insert a string in different places eg:
echo sprintf("<div style='color: red;'>%s</div><div style='color: blue;'>%s</div>", fgets($file), fgets($file2));
Confused by the title? hehe. Not sure how to explain this one, but I think my snippet of code should explain things a little easier.
This is what I'm trying to pass through the $data variable. div is displayed as it should be, but the echo statement inside (which I need) is NOT displayed.
Where am I messing up?
$data['packagename'] = '<div class="somedoodoo"> echo $row->subscription </div>';
You can just use string concatenation:
$data['packagename'] = '<div class="something">' . $row->subscription . '</div>';
you can't execute code inside a string like that, plus, it's the wrong quotes:
$data['packagename'] = <<<EOL
<div class="somedoodoo">{$row->subscription}</div>
EOL;
relevant docs on heredocs: http://php.net/heredoc
I am echoing back these 2 variables in to a table, but wanted to know how to add a line break between these 2?
echo $row ['username'] . $row ['date_time'];
if you're printing an HTML output to your browser:
echo $row["username"]."<br />".$row["date_time"];
EDIT:
when printing to HTML - you better print the variables after passing them through htmlspecialchars function in order to avoid Cross-site-scripting (XSS), I'll do it this way:
echo htmlspecialchars($row["username"],ENT_QUOTES)."<br />".htmlspecialchars($row["date_time"],ENT_QUOTES);
if you want to print it to a file or something similar:
echo $row["username"]."\n".$row["date_time"];
you can always echo normal html from php.
echo "<div id=\"mydiv\"> Div content goes here </div>";
note the backslashes for double quotes wrapping mydiv to escape them.
so you can add a tag in between them to get a new line.
echo $row["username"] . "<br />" . $row["date_time"];
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('"',""e;",$row['item']) . "\");\">" . $row['item'];
And where you would like to display the $item field, just replace it in reverse if you get "e; instead of ' " '. For example:
$qoute_free= str_replace('"e','"',$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(/"e;/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!!
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