I tested my jsno example here:
data.php
<?php
ob_start();
echo "string1";
$div1 = ob_get_clean();
ob_start();
echo "string2";
$div2 = ob_get_clean();
$resultArray = array("resultOne" => $div1,"resultTwo" => $div2);
echo json_encode($resultArray);
?>
start.php
xmlhttp.onreadystatechange=function()
{
var div1=document.getElementById("myDiv1");
var div2=document.getElementById("myDiv2");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data=JSON.parse(xmlhttp.responseText);
//document.getElementById("myDiv1").innerHTML=xmlhttp.responseText;
div1.innerHTML=data['resultOne'];
div2.innerHTML=data['resultTwo'];
}
}
This gives correct result and show data.
Now I tried to implement on my actual application.
login.php (verify user login, if success) -> start.php (loaded into login.php through ajax) -> data.php (returns json array values as in above case)
just difference is data.php is in following manner:
<?php
$url = $_POST['url'];
$user_id = $_POST ['userid'];
if(isset($_POST['rate']))
{
$rate =$_POST['rate'];
}
else
$rate = 0;
$data = file_get_contents($url);
function get_title($html)
{
return preg_match('!<title>(.*?)</title>!i', $html, $matches) ? $matches[1] : '';
}
function get_logo($html)
{
preg_match_all('/\bhttps?:\/\/\S+(?:png|jpg)\b/', $html, $matches);
//echo "mactch : $matches[0][0]";
return $matches[0][0];
}
function plaintext($html)
{
// remove comments and any content found in the the comment area (strip_tags only removes the actual tags).
$plaintext = preg_replace('#<!--.*?-->#s', '', $html);
// put a space between list items (strip_tags just removes the tags).
$plaintext = preg_replace('#</li>#', ' </li>', $plaintext);
// remove all script and style tags
$plaintext = preg_replace('#<(script|style)\b[^>]*>(.*?)</(script|style)>#is', "", $plaintext);
// remove br tags (missed by strip_tags)
$plaintext = preg_replace("#<br[^>]*?>#", " ", $plaintext);
// remove all remaining html
$plaintext = strip_tags($plaintext);
return $plaintext;
}
function trim_display($size,$string)
{
$trim_string = substr($string, 0, $size);
$trim_string = $trim_string . "...";
return $trim_string;
}
$title = get_title($data);
$logo = get_logo($data);
$title_display = trim_display(30,$title);
$content = plaintext($data);
$Preview = trim_display(100,$content); //to Show first 100 char of the web page as preview
function MakeTinyUrl($url)
{
return md5($url);
}
$hash = MakeTinyUrl($url);
ob_start();
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$content=mysqli_real_escape_string($con,$content);
$Preview=mysqli_real_escape_string($con,$Preview);
$title_display=mysqli_real_escape_string($con,$title_display);
$result = mysqli_query($con,"SELECT COUNT(*) as val FROM post_data WHERE url ='".$url."' and userid='".$user_id."'");
$bool= mysqli_fetch_assoc($result);
if($bool['val'])
{
echo '<div style="clear:both;"><i>You have already worked on this url..</i> </div>';
}
else
{
$insertQuery = "INSERT INTO post_data(`userid`, `url`, `desc`, `preview`, `img_url`, `title` ,`hash`) VALUES ('".$user_id."','".$url."','".$content."','".$Preview."','".$logo."','".$title_display."','".$hash."')";
if (!mysqli_query($con,$insertQuery))
{
die('Error: ' . mysqli_error($con));
}
}
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid ='".$user_id."' and url='".$url."'");
//This will fetch only one row from db
while ($row = #mysqli_fetch_array($result))
{
$title = $row['title'];
$url = $row['url'];
$preview = $row['preview'];
$image = $row['img_url'];
}
//Update Rate value in table
$update = "update post_data set rate='".$rate."' where url='".$url."'";
if (mysqli_query($con, $update))
{
//echo "updated";
}
else
{
//echo "Not updated";
}
?>
<html>
<body>
<a class="fragment" href="google.com">
<div>
<span id='close' onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span>
<img src ="<?php echo $image ?>" height="116" width="116" alt="some description"/>
<h3><?php echo $title ?></h3>
<h4><?php echo $url ?> </h4>
<p class="text"> <?php echo $preview ?>
</p>
</div>
</a>
<?php
$div1 = ob_get_clean();
ob_start();
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid ='".$user_id."'");
echo "Records for user : $user_id"; echo "<br/>";
while ($row = #mysqli_fetch_array($result))
{
$title = $row['title'];
$url = $row['url'];
$preview = $row['preview'];
$image = $row['img_url'];
echo "Title: $title"; echo '<br/>';
echo "URL: $url"; echo '<br/>';
echo "Preview : $preview"; echo '<br/>';
echo "Image url: $image"; echo '<br/>';
//echo '</br>';
}
$div2 = ob_get_clean();
$resultArray = array("resultOne" => $div1,"resultTwo" => $div2);
echo json_encode($resultArray);
?>
</body>
</html>
I get error message:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
var data=JSON.parse(xmlhttp.responseText);
You can validate your json responses using below url, so that you can conclude your results some point,
$resultArray = array("resultOne" => $div1,"resultTwo" => $div2);
echo json_encode($resultArray);
Ref: http://jsonformatter.curiousconcept.com/#jsonformatter
Related
I have a database with two tables: accounts and recipes(each have their own ID column).
I have a page that displays all the recipes. I want to enable users to add recipes to their favourites in accounts table. Once user is logged in, $_SESSION['user_id'] is set.
I have script that will add the recipe id to the favourites in accounts table, but I don't know how to run it without redirecting from the page that displays all recipes.
Here is what i have so far:
_view.php
<?php
$result = $mysqli->query("SELECT * FROM recipes");
if ( $result->num_rows == 0 ){
$_SESSION['message'] = "Error!";
echo "<div class='error-mess'>" . $_SESSION['message'] . "</div>";
}
else {
while ($row = mysqli_fetch_array($result)) {
$slug = $row['slug'];
$ingr = json_decode($row['ingr']);
$ingr_count= count($ingr);
$id = $row['id'];
echo '<div class="container recipe mb-2">';
echo '<img class="" src="/images/recipes/';
echo $row['img'];
echo '"/>';
echo '<div class="title-cats"><a href = "/recipe_preview.php?slug=' . $slug . '">';
echo $row['title'];
echo '</a></div>';
echo '<h4>Ingredients:</h4><br>';
for($i = 0; $i<$ingr_count;$i++){
$num = $i + 1;
echo $num . '. ';
$ingrs = json_decode($ingr[$i],true);
print_r($ingrs[0]);
echo '<br>';
}
echo '<br><button type="submit" class="btn" name="add">Read More</button>';
//favourites link
echo '<span class="fa fa-heart ml-3"></span>';
echo '</div><hr>';
}
}
_favourite.php
<?php
//relationship
require 'db.php';
$user_id = $_SESSION['user_id'];
//$favourite_id = $_POST['fav'];
$favourite_id = $_GET["id"];
echo $favourite_id;
echo $user_id;
$result = $mysqli->query("SELECT favourites FROM accounts WHERE id ='$user_id'");
if ( $result === null) {//doesnt work
$favs = array();
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
echo 'null';
}
else{
$favs = array();
$result = json_decode($result,true);
array_push($favs, $result);
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
}
$sql = "UPDATE accounts SET favourites ='$new_favs' WHERE id = '$user_id'";
if ( $mysqli->query($sql)){
echo '<div class="error-mess">Recipe sucessfully saved!</div>';
}
else{
echo '<div class="error-mess">NOT</div>';
}
.js -jquery library is there
$(document).ready(function() {
$('#favourite').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
id: $(this).data('id'),
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
My sitemap not working its not showing any url or data when i run my sitemap its showing blank empty page
Here is my code for sitemap and keywords is main table name and check image for my table
<?php
require dirname(__FILE__) . ("/includes/includes.php");
header("Content-Type: text/xml");
print "<?xml version='1.0' encoding='utf-8'?>";
$pageLimit = 50000;
$base = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
$base = substr($base,0,strrpos($base,"/")+1);
$link = mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name,$link);
if (isset($_GET["page"]))
{
print "<urlset xmlns='http://www.google.com/schemas/sitemap/0.84' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd'>";
$page = intval($_GET["page"]);
$from = (($page-1)*$pageLimit);
$sql = "SELECT * FROM keywords LIMIT ".$from.",".$pageLimit;
$result = mysql_unbuffered_query($sql,$link);
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
print "<url>";
print "<loc>".genSearchUrl(implode('-',array_filter(explode('-', str_replace(' ', '-', xmlentities(iconv("utf-8", "utf-8//ignore", $row["keyword"])))))))."</loc>";
print "</url>";
}
print "</urlset>";
}
else
{
print "<sitemapindex xmlns='http://www.google.com/schemas/sitemap/0.84' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/siteindex.xsd'>";
$sql = "SELECT count(*) as count FROM keywords";
$result = mysql_query($sql,$link);
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$pages = ceil($row["count"] / $pageLimit);
for($i=1;$i<=$pages;$i++)
{
print "<sitemap>";
$loc = $base."sitemap.php?page=".$i;
print "<loc>".$web_path."sitemap_".$i.".xml</loc>";
print "</sitemap>";
}
print "</sitemapindex>";
}
exit();
function xmlentities($text)
{
$search = array('&','<','>','"','\'');
$replace = array('&','<','>','"',''');
$text = str_replace($search,$replace,$text);
return $text;
}
?>
please help, i am learning json, but i find it difficult to insert code echo. If you know the answer please help me
My Code
if ($result) {
$arr['news'] = '';
$idterakhir = '';
$query = $pdo->query($sql);
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
// change this into echo
$arr['news'] .= '<div class="card" news_id="'.$row->news_id.'">'.$row->news_id.'<br>'.$row->news.'</div>';
// change this into echo
$idterakhir = $row->news_id;
}
$arr['idterakhir'] = $idterakhir;
$arr['end'] = false;
} else {
$arr['end'] = true;
}
echo json_encode($arr);
into :
echo "
<div class='card' news_id='$id'> $id <br> $title </div>
";
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$id2 = $row['news_id'];
$id = <div class="card" news_id="'.$id2.'">
$news = $row['news'];
$title = $id.$id2.<br>'.$news.'</div>
$arr['news'] .= title;
echo $arr['news'];
$idterakhir = $row->news_id;
}
This should print $arr['news'] for each circle of the while.
If you need to echo out the contents of $arr['news'], just do:
echo $arr['news'];
I am trying to fetch image from my database and show uder image tag but it is showing a broken image. Where is the problem?
$query="SELECT imagetype,Attachments from Events where E_id='$id' ";
$result = mysqli_query($link,$query);
// $image = mysql_result($result,0);
// echo "<img src =".$image."/>";
if ($row = mysqli_fetch_array($result)){
// echo $row['Attachments'];
header('content-type: image/jpeg');
// exit();
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['Attachments']).'" alt="photo"><br>';}
?>
Class image.php
<?php
class image extends mysqli {
public $a = array();
public function __construct($host, $user,$password,$db_name) {
parent::mysqli($host, $user,$password,$db_name);
}
public function save() {
$num = count($this->a);
$i = 0;
foreach ($this->a as $c) {
$ext = explode(".", $c);
$this->query("INSERT INTO Events set name='{$c}',Attachments='" . $this->real_escape_string(file_get_contents($c)) . "',imagetype='" . $ext[count($ext) - 1] . "'");
$i++;
}
return $i == $num;
}
public function select($id) {
$rs = array();
$sql = "SELECT * FROM Events WHERE 1";
if ($id != NULL) {
$sql.=' AND E_id=' . $id;
}
$query = $this->query($sql);
if ($query->num_rows) {
while ($line = $query->fetch_object()) {
$rs[] = $line;
}
}
return $rs;
}
}
$image_url=array('');//contain array of image url if you would like to save
$obj=new image($host, $user,$password,$db_name);
$obj->a=$image_url;
$obj->save();
$row=$obj->select(isset($_GET['id'])?$_GET['id']:1);
header("Content-type: image/{$row[0]->imagetype}");
echo $row[0]->image;
show.html
<html>
<head></head>
<body>
<img src="image.php?id=<?php echo $_GET['id']?>" width="175" height="200" />
</body>
</html>
I need to extract the thumbnail image from a video to facebook.
I should do it via json, the fact is that I can not extract the image to 720px.
I did so, but I get nothing, no errors or anything.
<?php
/*
10152765849330530
https://www.facebook.com/video.php?v=10152765849330530&set=vb.48166220529&type=2&theater
*/
$id = "10152765849330530";
$xml = #file_get_contents('https://graph.facebook.com/' . $id);
$result = #json_decode($xml);
//var_dump($result);
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
$result = $result->format->picture;
echo $result;
?>
Ideas?
The link is to be extracted:
https://fbcdn-vthumb-a.akamaihd.net/hvthumb-ak-xfp1/v/t15.0-10/10470126_10152765850455530_10152765849330530_61772_571_b.jpg?oh=ea81bafb0b88da98068fe8697b058bd0&oe=5493EF9F&gda=1422872671_cf3d63eef79db332df7a30c8041abdd9
Just tried to play with your code, works now -
<?php
/*
10152765849330530
https://www.facebook.com/video.php?v=10152765849330530&set=vb.48166220529&type=2&theater
*/
$id = "10152765849330530";
$xml = file_get_contents('http://graph.facebook.com/' . $id);
$result = json_decode($xml);
echo "<pre>";
echo $result->format[0]->picture;
?>
To fetch the 720px sized picture -
<?php
/*
10152765849330530
https://www.facebook.com/video.php?v=10152765849330530&set=vb.48166220529&type=2&theater
*/
$id = "10152765849330530";
$xml = file_get_contents('http://graph.facebook.com/' . $id);
$result = json_decode($xml);
echo "<pre>";
echo $result->format[3]->picture;
?>