Jquery/json pull string with html from mysql db - php

I'm pulling data from a mysql db using php and echoing a json_encoded array.
Using ajax I pull in the results and set the values of various dom elements. I have a string which has some html tags eg <p></p>.
When I set the element $("#element").html(data['text']) it adds double quotes to the text and all of the html elements appear as text.
I can't seem to remove the quotes using replace. Oddly when I alert the value there are no quotes. They only appear in the html when I view the code.
What is the best way to include html with text? And how do I get jquery to render this has html and not text?
Many thanks!
PHP / MySQL
//Article by id
if(isset($_GET['do']) && $_GET['do']=='get_art') {
$content = array();
$id = clean_input($_GET['id']);
$q = "SELECT * FROM articles WHERE id = '$id'";
$r = $conn->query($q);
$row = $r->fetch_assoc();
$content['title'] = str_replace("€", '€', $row['title']);
$content['img'] = $row['img'];
$content['text'] = str_replace('€', '€', $row['text']);
$content['text'] = htmlentities($row['text']);
echo json_encode($content);
}
//end article by id
jQuery
//load article onclick
$('body').on('click', '.get_art', function (e) {
e.preventDefault();
var href = $(this).attr('href').replace('#', ' ');
$.ajax({
url: 'actions.inc.php?do=get_art&id=' + href,
dataType: 'json',
type: 'post',
success: function(data) {
var art_text = data['text'];
art_text = art_text.replace('&euro;', '€');
$("#art_img").attr("src", "images/" + data['img']);
$("#art_title").html(data['title']);
$("#art_text").html($.parseHTML(art_text));
} //end success
});//end ajax
});
//end load

The htmlentities (php) was making a mess of things, got it working now after I console logged the output from the php file

Related

Transfer blob Image between mysql database and HTML using AJAX and Jquery

My problem is not being able to encode the image properly after retrieving it from the database otherwise all my work is fine. After I fetch the image I managed to display it at the same php file using "header('content-type: image/jpeg')".
<?php
header('content-type: image/jpeg');
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select image from images order by id desc limit 1";
require_once('connection.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
?>
The previous piece of code is for displaying directly but it was for testing only, I need to use it as a JSON source so I modified it in this way:
header('Content-type: application/json');
.
.
.
$r['a'] = base64_encode( $result['image']);
echo json_encode($r);
For the Jquery and Ajax part also worked fine and I tested it by making another json file and put an image encoded professionally by this website https://www.base64-image.de/.
And here is Jquery code:
$(document).ready(function(){
(function()
{
d='';
var poll=function()
{
$.ajax({
url: "getjson.php",
type :"get",
dataType: "JSON",
success: function(json)
{
d +='data:image/jpeg;base64,';
d +=json.a;
$("#myimg2").attr("src",d);
}
})
};
poll();
setInterval(function(){
poll();
}, 2000);
})();
});
What I need now is to encode the image just like what this website does https://www.base64-image.de/ because this line base64_encode( $result['image']) seems to be not enough, I have tried many solutions available online but no one worked for me!

PHP/JQUERY- Can't return data from a query

I'm doing a project for an exam. I'm stuck with that and I hope someone of you could help me (I'm italian, so sorry for my bad english!).
I have to query an existing database stored in phpmyadmin with a PHP script. Then, the query result need to be parsed with a jquery script and printed to an HTML page.
Here is the PHP script:
<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Errore di connessione: ' . mysql_error());
}
mysql_select_db("progetto_lpw", $con);
$sql="SELECT denominazione FROM farmacia";
$result = mysql_query($sql) or die(mysql_error());
$num=mysql_numrows($result);
while($row = mysql_fetch_array($result)){
print json_encode($row['denominazione']);
print "<br />";
}
?>
I've already tested the PHP script calling it via browser and it works.
Then, I parse the result with this jquery script (the use of this combination is a requirement of the project):
$("#button").click(function(){
$.getJSON('json.php', function(data) {
$.each(data, function(index,value){
$("#xx").append("<p>"+value+"</p>")
})
})
})
Here is the problem: when I open the HTML page and I click the button on firefox, consolle says "no element found" referring to PHP script.
"xx" is the id of the div in which elements are printed.
Where is the error?
Thanks to everyone.
Replace below code
while ($row = mysql_fetch_array($result)) {
print json_encode($row['denominazione']);
print "<br />";
}
With below code and try
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row['denominazione'];
}
header('Content-type: application/json');
echo json_encode($rows);
HTML
<button id="button">Fetch JSON</button>
<div id="xx"></div>
JS
$("#button").click(function() {
$.getJSON('json.php', function(data) {
$.each(data, function(index, value) {
$("#xx").append("<p>" + value + "</p>")
});
});
});
Response from json.php should be in below format
["AGGERI","ALCHEMICA 1961"]
The reason your code isn't working is that it's producing output like this:
"foo"<br />
"bar"<br />
That's not valid JSON. To be valid, you have to not have the HTML <br /> in there (this is JSON, not HTML), and you have to have commas between the elements you want to return.
json_encode will handle formatting the array correctly for you.
jsFiddle Demo with post request to send and get json output
'print' works differently then 'echo'. At least i am sending JSON packages with echo from php.
Can you replace it ?
// in php
echo json_encode($row['denominazione']);
// in jquery script, best to place "<br />" tag here
$("#xx").append("<p>"+value+"</p><br />")

passing html id to php/mysql, receiving 'cannot read property __e3_ of undefined'

I'm making a Google Map that will pull information from a database and output xml to be interpreted into markers on the map. I want to pass the clicked elements id into the PHP to filter the database results. When the function is executed, I get an error stating "cannot read property '_e3' of undefined". Everything works fine when I get rid of the variable and directly enter a type into the code.
relevant jQuery
$(document).ready(function() {
$('.map_item').toggle(
function() {
var itemid = this.id;
$.ajax({
type: 'POST',
//php script takes info from database, outputs xml
url:'SQL.php',
//pass var to the php to select only items matching this id
data: 'variable1=' + itemid,
success: function(data) {
relevant PHP from file SQL.php
$ajax_var = $_POST['variable1'];
$query = 'SELECT * FROM location WHERE Type="' . $ajax_var . '"';
$result = mysql_query($query); //sqlsrv_query
header('Content-type: text/xml');
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement('marker');
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("dirtType",$row['dirtType']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
}
echo $dom->saveXML();
I would say that the data should be sent in a different way, like this:
data: {
"variable1": itemId
}

Jquery/Ajax and PHP rendering TR

I am scraping sites, and I am doing this one at a time, and then trying to get the results to display AS I get them. I am trying to render one TR at a time, but instead, it does every single one, and then renders ALL the TRs.
Here is the call to javascript:
<body onload="getOffers(companies , {$scraped}, {$isbn13});">
Here is the JS/Jquery function:
function getOffers($company_ids, $scraped, $isbn)
{
if($scraped)
{
$.ajaxSetup({cache: false});
for(var $id in $company_ids)
{
$.ajax({
url: "../get_offer.php",
data: "id=" + $company_ids[$id] + "&isbn=" + $isbn + "&code=" + $id,
dataType: "html",
success: function(data) {
$("#results tbody:last").append(data);
}
});
}
}
else
{
return true;
}
}
And here is the PHP page:
<?php
require_once 'scrape.php';
require_once 'include.php';
$id = requestValue('id');
$isbn = requestValue('isbn');
$code = requestValue('code');
$page = curlMultiRequest(isbn10($isbn), $id);
$offer = getOffer($code, $page[$code], isbn10($isbn));
print "<tr><td>". $offer['company']."</td><td>". $offer['offer_new'] . "</td><td>" . $offer['offer_used']."</td></tr>";
?>
I tried returning the sting I am printing, but that didn't even work. How can I make it print each table row to the screen as the data is retrieved?
EDIT: so I tried adding this:
print "<tr><td>". $offer['company']."</td><td>". $offer['offer_new'] . "</td><td>" . $offer['offer_used']."</td></tr>";
ob_flush();
flush();
To the PHP and it didn't work. I don't understand, if I throw an alert, it happens on the fly for every ID, but the html rendering does not.
It may have magically fixed itself because your browser was caching some of the javascript. You should use some developer tools to manually flush the cache of resources for the host you are testing on to avoid old code being subtly used ....

jQuery Ajax - Alternate XML sources for each request

I have two XML sources to retrieve data from. I want to use them alternately per page load. So when someone visits the page the first source will be used, next time the visit the page the other source will be used. Here is the ajax request I am using to get one data source:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "source1.xml", //how do I alternately load two different xml data sources?
dataType: "xml",
success: function(xml) {
var counter = 0
var output = '<li>';
$(xml).find('person').each(function(){
counter++;
var image = $(this).find('image').text();
var name = $(this).find('name').text();
var title = $(this).find('title').text();
var company = $(this).find('company').text();
output = output + '<div><img src=img/' + image + '.jpg />' + '<br /><label><span>' + name + '</span><br />' + title + '<br />' + company + '</label><br /></div>';
if(counter % 3 === 0){
output = output + '</li><li>';
}
});
output = output + '</li>';
$('#update-target ul').html(output);
}
});
});
For extra info, here is how I am alternately loading 2 flash files using PHP:
if(isset($_SESSION['rotation'])){
$picker = $_SESSION['rotation'];
}else{
$picker = rand(0,1);
}
if($picker == 0){
echo '<script type="text/javascript">
var video1 = new SWFObject("somefile1.swf", "p1", "151", "590", "9", "#ffffff");
video1.addParam("wmode","transparent");
video1.write("meh");
</script>';
$_SESSION['rotation'] = ++$picker;
} else {
echo '<script type="text/javascript">
var video1 = new SWFObject("somefile2.swf", "p1", "151", "590", "9", "#ffffff");
video1.addParam("wmode","transparent");
video1.write("meh");
</script>';
$_SESSION['rotation'] = --$picker;
}
I realize I could just stick the jquery document ready code right in there where I have the js calling the flash but it does not seem like a very efficient way of handling this. What is a "best case" way to do this?
You can just use a variable to keep it short, like this:
echo '<script type="text/javascript">var xmlSource = "source1.xml";</script>';
Use that in an if caluse as well, then just reference that in your code:
url: xmlSource,
There are other ways of course, using a cookie (the cookie plugin), putting the text right in the document.ready handler, etc...whichever seems most elegant to you I suppose.
I recommend the variable from the PHP side or a cookie...both of these options allow the document.ready code to stay outside the page in an external script, and not downloaded by the user each time.

Categories