I made a button but I can't get the function to work as I want, does anyone know what code I could use here?
I was thinking of downloading all the images with ZIP and it can be compressed by creating a folder on my server.
I think that a button is better to download them all or individually
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Parser</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/style.css" rel="stylesheet">
</head>
<body>
<header class="header-image">
<div class="container">
<h1><strong>Image Parser</strong></h1>
<h3>Enter any URL and get all the images on the page</h3>
<button type="button" class="action-buttons" data-toggle="modal" data-target="#aboutmodal">About</button>
<button class="action-buttons">Get API</button>
</div>
</header>
<hr>
<div class="container">
<div class="row">
<div class="col-md-12">
<form id="form-extractor" class="form-horizontal form-main" method="GET">
<input type="text" class="form-control" name="url" placeholder="Enter the URL from where images are to be extracted" required autofocus>
<br>
<button type="button" id="submit" class="btn btn-lg btn-success">Extract</button>
</form>
</div>
</div>
</div>
<div class="spinner" style="display:none;">
<div class="rect1"></div> <div class="rect2"></div> <div class="rect3"></div> <div class="rect4"></div> <div class="rect5"></div>
</div>
<div id="stats" class="container" style="display:none;">
<div class="row">
<div class="col-xs-12 text-center" id="download-file" >
<a class="btn btn-lg btn-info" target="_blank" href="#">Download zip file</a>
</div>
</div>
</div>
<div id="result" class="other-text">Welcome :)</div>
</div>
<div class="modal fade" id="aboutmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Image-Parser</h4>
</div>
<div class="modal-body text-justify">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="assets/js/script.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
script.js
$(document).ready(function() {
var spinner = toggleSpinner(),
submit_button = $("#submit");
submit_button.click(function(e) {
e.preventDefault();
spinner();
$.ajax({
url: 'api/image-parser.php?url=' + $('input[name="url"]').val(),
dataType: 'json',
beforeSend: function() {
submit_button.text("Extracting...");
submit_button.prop('disabled', true);
},
success: function(result) {
spinner();
if (result.success) {
renderStats(result);
renderImages(result);
} else {
$('#result').html('Invalid URL!');
}
},
error: function(xhr, resp, text) {
spinner();
$('#result').html('Could not connect to server, please try again later');
},
complete: function() {
submit_button.text("Extract");
submit_button.prop('disabled', false);
}
})
});
});
function renderStats(result) {
var stats =
'<strong>URL Searched</strong> : ' + $('input[name="url"]').val() + '<br>' +
'<strong>Parent Domain</strong> : ' + result.parent_url + '<br>';
$('#stats .other-text').empty().append(stats);
}
function renderImages(result) {
var images;
if (0 == result.images.length) {
images = '<b>No Image Found at your Given Location</b>';
} else {
images = result.images.map(function(image) {
return '<img src="' + image + '" width="250" style="margin:20px">';
});
}
$('#result').empty().append(images);
}
function toggleSpinner() {
var isHidden = true;
return function() {
if (isHidden) {
$('#stats').hide();
$('#result').empty();
$('.spinner').show();
} else {
$('#stats').show();
$('.spinner').hide();
}
isHidden = !isHidden;
}
}
image-parser.php
<?php
/**
* error reporting disabled, if you want to enable it
* change it to "error_reporting(E_ALL)"
* ref : http://php.net/manual/en/function.error-reporting.php
*/
error_reporting(0);
$final_response = get_extracted_images();
echo json_encode($final_response);
/**
* function to extract images from URL in GET Parameter
* #return response object
*/
function get_extracted_images() {
$final_response = array();
$images = array();
if (isset($_GET['url'])) {
$url = $_GET['url'];
$parts = explode('/', trim($url));
/**
* this flag is to check whether user has entered the http or https in the beginning of URL or not
* #var boolean
*/
$flag = ($parts[0] == 'http:' || $parts[0] == 'https:') ? true : false;
if (!$flag)
$url = 'http://' . $url;
/**
* check whether URL entered by user is correct or not
*/
if (!isValidURL($url)) {
return array(
'url_searched' => $url,
'valid_url' => false,
'success' => false
);
} else {
$final_response['valid_url'] = true;
/**
* check if there is a trailing slash (/) or not, if there is one, remove it
*/
if (substr($url, strlen($url) - 1) == '/')
$url = rtrim($url, "/");
$parts = explode('/', $url);
/**
* parent domain name called, if there is a subdomain, it would also be included here
* #var string
*/
$Root = $parts[0] . '//' . $parts[2];
$html = curl_URL_call($url);
if (empty($html)) {
return array(
'url_searched' => $url,
'valid_url' => false,
'success' => false,
'message' => 'We are unable to access the given URL: ' . $url
);
}
$dom = new DOMDocument;
$dom->loadHTML($html);
$final_response['url_searched'] = $url;
$final_response['parent_url'] = $Root;
/**
* check if there is any image in HTML source code or not
*/
if (preg_match_all('/<img[^>]+>/i', $html, $result)) {
$final_response['success'] = true;
foreach ($result[0] as $key) {
preg_match('/src="([^"]+)/i', $key, $src_key);
for ($i = 0; $i < count($src_key); $i += 2) {
$src = $src_key[1];
if (!preg_match("/http:/", $src) && !preg_match("/https:/", $src)) {
/**
* check whether the URL in the src is absolute or relative
* if it is relative, make it absolute
*/
if ($src[0] == '/' && $src[1] == '/') {
$src = 'http:' . $src;
} else if ($src[0] == '/') {
$src = $Root . $src;
} else {
$src = $Root . '/' . $src;
}
}
array_push($images, $src);
}
}
} else {
/**
* No images were found in the HTML
* source code, hence success if false
*/
$final_response['success'] = false;
}
/**
* Getting urls for stylesheets in the webpage
*/
foreach ($dom->getElementsByTagName('link') as $node) {
if ($node->getAttribute("rel") == "stylesheet") {
$css_route = $node->getAttribute("href");
/**
* check whether the URL in the $css_route is absolute or relative
* if it is relative, make it absolute
*/
if ($css_route[0] == '/' && $css_route[1] == '/') {
$css_route = 'http:' . $css_route;
} else if ($css_route[0] == '/') {
$css_route = $Root . $css_route;
} else if ($css_route[0] != 'h') {
$css_route = $Root . '/' . $css_route;
}
$parts = explode('/', $css_route);
$parts_length = sizeof($parts);
$css_root = $parts[0] . '//' . $parts[2];
$css_active_dir = $css_root;
$css_parent_dir = $css_root;
for ($i = 3; $i < $parts_length - 1; ++$i) {
if ($i < $parts_length - 2) {
$css_active_dir = $css_active_dir . '/' . $parts[$i];
$css_parent_dir = $css_parent_dir . '/' . $parts[$i];
} else {
$css_active_dir = $css_active_dir . '/' . $parts[$i];
}
}
$css = curl_URL_call($css_route);
$matches = array();
/**
* Getting image urls using image extension matches in stylesheet extracted
*/
preg_match_all('/url\(\s*[\'"]?(\S*\.(?:jpe?g|gif|png))[\'"]?\s*\)[^;}]*?/i', $css, $matches);
foreach ($matches[1] as $image_link) {
/**
* check whether the URL in the $image_link is absolute or relative
* if it is relative, make it absolute
*/
if ($image_link[0] == '.' && $image_link[1] == '.') {
$image_link = $css_parent_dir . substr($image_link, 2);
} else if ($image_link[0] == '.') {
$image_link = $css_active_dir . substr($image_link, 1);
} else if ($image_link[0] == '/') {
$image_link = $css_active_dir . $image_link;
} else {
$image_link = $css_active_dir . '/' . $image_link;
}
array_push($images, $image_link);
}
}
}
}
/**
* All the images are added to the images array in
* final response
*/
$final_response['images'] = $images;
return $final_response;
} else {
$message = "Please enter a URL to extract information as a 'url' parameter in GET request";
return array(
'url_searched' => null,
'valid_url' => false,
'success' => false,
'message' => $message,
);
}
}
/**
* function to check if the URL entered by the user is correct or not
* #param string $url URL to be passed which is to be checked
* #return boolean returns if URL passed is valid or not
*/
function isValidURL($url){
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
/**
* function to make a CURL call in order to fetch the complete HTML source code of URL entered
* #param string $url URL of the page
* #return string HTML source code of the URL entered
*/
function curl_URL_call($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
Related
This question already has answers here:
Preview an image before it is uploaded
(29 answers)
Closed 3 years ago.
I'm a beginner and still learning to programme.
I want to do something like this:
https://ufile.io/z2w0l
My question is how to preview a few images before uploading in the database with php,mysql?
I have code but it work like this:
When I choose which image i want to upload, the image doesn't display. Image is displaying when i click on submit button. I will take the picture of my layout here: https://prnt.sc/mv1ef0 (this is my form where i can upload image), https://prnt.sc/mv1erl (this is my submit button "Post"). When i click on submit button the page is refreshing and the image is displaying(like this photo): https://prnt.sc/mv1fjg
I want to preview picture first: https://prnt.sc/mv1iiz (in this box)
Here is my php code:
public function create() {
$this->requireSession();
$this->load->model('store_model');
$visible = 0;
if($this->input->post('is_visible') == 'on') {
$visible = 1;
}
$promotion = 0;
if($this->input->post('is_promotion') == 'on') {
$promotion = 1;
}
$internal = 0;
if($this->input->post('is_internal') == 'on') {
$internal = 1;
}
$userId = $this->authorization->getUserId();
$storeId = $this->authorization->getStore();
$price = $this->input->post('price');
$prev_price = $this->input->post('prev_price');
if($promotion == 1) {
$price = $this->input->post('prev_price');
$prev_price = $this->input->post('price');
}
date_default_timezone_set('Europe/Sofia');
$data = array(
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
'price' => $price,
'currency' => 'BGN',
'is_promotion' => $promotion,
'promotion_price' => $prev_price,
'quantity' => $this->input->post('quantity'),
'status' => $this->input->post('status'),
'main_image' => 0,
'is_internal' => $internal,
'is_visible' => $visible,
'url_address' => $this->input->post('url'),
'total_views' => 0,
'total_likes' => 0,
'total_comments' => 0,
'product_added' => date("Y-m-d H:i:s"),
'is_active' => 1,
'category_id' => $this->input->post('category_id'),
'user_id' => $this->authorization->getUserId(),
'store_id' => $storeId,
'brand_id' => $this->input->post('brand_id')
);
$this->db->insert("products", $data);
$product_id = $this->db->insert_id();
$this->db->query("UPDATE categories SET total_products = total_products + 1 WHERE id = " . $this->input->post('category_id'));
$this->db->query("UPDATE stores SET total_products = total_products + 1 WHERE id = " . $storeId);
$this->db->query("UPDATE users SET total_products = total_products + 1 WHERE id = " . $userId);
$tags = $this->input->post('tags');
$this->load->model('tag_model');
$this->tag_model->updateTags($tags, $product_id);
$this->load->model('category_model');
$this->load->model('attribute_model');
$attributes = $this->category_model->getOnlyAttributes($this->input->post('category_id'));
$values = array();
foreach($attributes as $row) {
$values[] = array('product_id' => $product_id, 'attribute_value_id' => $this->input->post('attribute_id' . $row->attribute_id));
}
if($attributes) {
$this->attribute_model->updateProductAttributes($values, $product_id);
}
if($_FILES["fileToUpload"]["tmp_name"]) {
$uploadOk = 1;
//$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$uploadOk = 0;
}
// Allow certain file formats
/*if($imageFileType != "jpg") {
$uploadOk = 0;
}*/
// Check if $uploadOk is set to 1
if ($uploadOk == 1) {
$this->db->insert('products_images', array('product_id' => $product_id));
$insert = $this->db->insert_id();
$target_dir = "./" . p_image_path();
$target_file = $target_dir . '/' . $insert . '.jpg';
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$this->db->update("products", array('main_image' => $insert), array('id' => $product_id));
}
}
redirect(site_url('mystore/products/edit/' . $product_id));
}
Here is my HTML code:
<div class="item-card">
<div class="card-section">
<div class="clearfix">
<!---<div class="pull-right">
<input type="file" name="fileToUpload" id="fileToUpload">
</div>---->
<div class="pull-right">
<span class="btn btn-white upload_image" type="file" id="fileToUpload">Upload image</span>
<input class="upload_file" type="file" name="fileToUpload" id="fileToUpload" style="display:none;">
</div>
<h2 class="al">Images</h2>
</div>
<hr />
<div class="item-images clearfix">
<div class="empty-text">
Upload images
</div>
</div>
</div>
</div>
You need to use Jquery onchange event when the file is selected read the file using FileReader
$('#fileToUpload').on('change', function() {
var file = this.files[0];
var imagefile = file.type;
var imageTypes = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
if (imageTypes.indexOf(imagefile) == -1) {
//display error
return false;
$(this).empty();
}
else {
var reader = new FileReader();
reader.onload = function(e) {
$(".empty-text").html('<img src="' + e.target.result + '" />');
};
reader.readAsDataURL(this.files[0]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="upload_file" type="file" name="fileToUpload" id="fileToUpload">
<div class="item-images clearfix">
<div class="empty-text">
Upload images
</div>
</div>
I have a dynamic navigation bar that stores the pages/URLs in a database. The nav.php is the script that handles displaying and running through the SQL queries to display the links. I'm having a difficult time adding a script that adds an active class to the links.
My page URLs are as follows:
/page/2/full-service-fleet
/rate-request
/employment
/page/5/links
/page/6/contact
PHP:
<nav>
<?php
while ($row = $result->fetch_assoc())
{
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != ''){
$navlink = $navurl;
}
else{
$navlink = "page.php?id=".$navid."&title=".$navslug;
}
if (substr($navlink,0,4) != "http"){
if ($server_name <> "") {
$navlink = "http://".$server_name."/".$navlink;
}
}
if ($navurl == '#'){
$navlink = $navurl;
}
if ($navnum ==0){
?>
<?php echo $navname; ?>
<?php
}else{
?>
<!-- the rest isn't necessary -->
......
</nav>
Browser Rendered Output
The actual links that are being displayed is this line:
<?php echo $navname; ?>
JS Script:
jQuery(document).ready(function($){
// Get current path and find target link
var path = window.location.pathname.split("/").pop();
// Account for home page with empty path
if ( path == '' ) {
path = 'index.php';
}
var target = $('nav a[href="'+path+'"]');
// Add active class to target link
target.addClass('active');
});
You can use this code as it is or you can grab some idea from this one
:
<div class="w3-top" style="z-index: 999;">
<div class="navcontainer">
<div class="w3-hide-small">
<img src="/images/-logo.png" alt="U.S. Transportation" title="" style="">
<div class="abovenav w3-right">
<button class="w3-button w3-round-large" onclick="">Customer Login</button>
<button class="w3-button w3-round-large" onclick="">Carrier Login</button>
</div>
</div>
<div class="w3-bar nav w3-card-2 w3-left-align w3-large" style="text-overflow: auto;" id="nav">
<div class="w3-hide-large w3-hide-medium">
<a class="w3-hide-medium w3-hide-large w3-right w3-margin-right w3-text-white buttons" href="javascript:void(0);" onclick="myFunction()" title="Toggle Navigation Menu"><span class="fa fa-bars"></span></a>
<a href="<?php
if ($server_name <> "") {
echo "http://" . $server_name . "/";
}
?>/index.php" title="Home" class="w3-left w3-margin-left w3-text-white buttons"><span class="fa fa-home w3-xlarge"></span></a>
</div>
<div style="margin-right: 10%;">
<nav>
<?php
include 'yortal\db.php';
$sql = "SELECT *,(select count(*) from pages where parent = p.id) as num from pages p where parent = 0 and status = 'ON' order by sort DESC";
$result = $mysqli->query($sql);
while ($row = $result->fetch_assoc()) {
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != '') {
$navlink = $navurl;
} else {
$navlink = "page.php?id=" . $navid . "&title=" . $navslug;
}
if (substr($navlink, 0, 4) != "http") {
if ($server_name <> "") {
$navlink = "http://" . $server_name . "/" . $navlink;
}
}
if ($navurl == '#') {
$navlink = $navurl;
}
if ($navnum == 0) {
$current_link = $_SERVER[REQUEST_URI];
$active_class = ($navlink==$current_link)?'active':'';
?>
<?php echo $navname; ?>
<?php
} else {
?>
<div class="w3-dropdown-hover w3-hide-small w3-right" onclick="javascript:window.location.href = '<?php echo $navlink; ?>'">
<button class="w3-button"><?php echo $navname; ?></button>
<div class="w3-dropdown-content w3-white w3-card-4">
<?php
//Subpages
$sql2 = "SELECT *,(select count(*) from pages where parent = p.id) as num from pages p where parent = " . $navid . " and status = 'ON' order by sort";
$result2 = $mysqli->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
$dropid = $row2['id'];
$dropname = $row2['nav'];
$dropurl = $row2['url'];
$dropslug = $row2['slug'];
$dropnum = $row2['num'];
if ($dropurl != '') {
$droplink = $dropurl;
} else {
$droplink = "page.php?id=" . $dropid . "&title=" . $dropslug;
}
if (substr($droplink, 0, 4) != "http") {
if ($server_name <> "") {
$droplink = "http://" . $server_name . "/" . $droplink;
}
}
if ($dropurl == '#') {
$droplink = $dropurl;
}
?>
<?php
$actual_link = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
$active_class = ($actual_link==$droplink || $_SERVER[REQUEST_URI] == $droplink)?'active':'';
?>
<?php echo $dropname; ?>
<?php
}
?>
</div>
</div><?php
}
}
?>
</nav>
</div>
</div>
</div>
First of all I'm pretty sure that you may have got wrong path. I suggest the following implementation which will depend on each():
$(document).ready(function(){
loc = window.location.pathname;
$("nav a").each(function(){
if ($(this).attr("href") == loc){
$(this).addClass("active");
$(this).attr("href") = "#"; // to prevent link to the same page
return true;
}
});
});
I have a div element which is populated by the query result(in index.php). I have also another file widget.php which has same query to update page. I have variable in widget.php "page" which navigates through the pages. If I use widget.php?page=2 it will load next page with results. I want to update a div element in index.php on click.(Click "next" and show another 8 news without reloading page).
in index.php :
<button type="button" id="prevbutton">Previous</button>
<button type="button" id="nextbutton">Next</button>
<div id="list"></div>
in script.js:
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var page = 0;
if (id_name == '#prevbutton' || id_name == '#nextbutton') {
if (id_name == '#prevbutton') {
page -= 1;
}
if (id_name == '#nextbutton') {
page +=1;
}
}
$.ajax({
url: 'widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
in widget.php :
<?php
header("Cache-Control: public, max-age=60");
include("logindb.php");
$page = $_GET['page'];
$page = $page*9;
?>
<div id="list">
<?php
$abfrage59 = "SELECT n.news_title,n.news_id,FLOOR(TIMESTAMPDIFF(HOUR, n.timestamp, NOW())) as diff
FROM news n
WHERE n.domain_id = '2' AND n.timestamp < NOW()
ORDER BY timestamp DESC
LIMIT $page,9";
$ergebnis59 = mysql_query($abfrage59);
while ($row59 = mysql_fetch_object($ergebnis59)) {
$newstitleslug = $row59->news_title;
$newstitleslug = str_replace(' ', '-', $newstitleslug);
$newstitleslug = strtolower($newstitleslug);
echo "<div class=\"col-sm-6 col-md-4\" style=\"padding-bottom: 15px;\">
<div class=\"item\">
<img class=\"main\" src=\"http://www.example.com/news/$row59->news_id.png\" />
<div class=\"text\">
<div class=\"inner\">
<a href=\"http://www.example.com/$newstitleslug/$row59->news_id/\" style=\"color:white;\">$row59->news_title<br />
<span class=\"date\">$row59->diff hours ago</span>
</div>
</div>
</div>
</div>";
}
?>
<?php
include("close_connect.php");
?>
So I want to update value $page on click and refresh content of DIV with new data. Thanks in advance.
Edit: removed script from script.js and put in the end of the index.php body:
<script>
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var temppage = 1;
if (id_name == 'prevbutton' || id_name == 'nextbutton') {
if (id_name == 'prevbutton') {
temppage -= 1;
}
if (id_name == 'nextbutton') {
temppage +=1;
}
var page = temppage;
}
$.ajax({
url: 'widgets/news_archive_widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
</script>
Remove the # you're prefixing to prevButton and nextButton as $(this).attr('id') will return the id without the #. The value of id_name will either be prevButton or nextButton.
UPDATE:
Your final js script should look like this:
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var page = $("#currPageNumber").val();
if (id_name == 'prevbutton' || id_name == 'nextbutton') {
if (id_name == 'prevbutton') {
page -= 1;
}
if (id_name == 'nextbutton') {
page +=1;
}
}
$.ajax({
url: 'widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
PHP script:
<?php
header("Cache-Control: public, max-age=60");
include("logindb.php");
$page = $_GET['page'];
$page = $page*9;
?>
<div id="list">
<?php
$abfrage59 = "SELECT n.news_title,n.news_id,FLOOR(TIMESTAMPDIFF(HOUR, n.timestamp, NOW())) as diff
FROM news n
WHERE n.domain_id = '2' AND n.timestamp < NOW()
ORDER BY timestamp DESC
LIMIT $page,9";
$ergebnis59 = mysql_query($abfrage59);
while ($row59 = mysql_fetch_object($ergebnis59)) {
$newstitleslug = $row59->news_title;
$newstitleslug = str_replace(' ', '-', $newstitleslug);
$newstitleslug = strtolower($newstitleslug);
echo "<div class=\"col-sm-6 col-md-4\" style=\"padding-bottom: 15px;\">
<div class=\"item\">
<img class=\"main\" src=\"http://www.example.com/news/$row59->news_id.png\" />
<div class=\"text\">
<div class=\"inner\">
<a href=\"http://www.example.com/$newstitleslug/$row59->news_id/\" style=\"color:white;\">$row59->news_title<br />
<span class=\"date\">$row59->diff hours ago</span>
</div>
</div>
<input type='hidden' value='".$_GET['page']."' id='currPageNumber'>
</div>
</div>";
}
?>
<?php
include("close_connect.php");
?>
I want to add photos dynamically but I have a problem, I confused where fix this error.
This error is:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
This is my pages index.html
<?php
//Foto_ID
$dr = (rand(100,10000));
$ymdhis = date("ymdhis");
$rd = $dr.$ymdhis;
?>
<div id="main-content2">
<script>
var maxSlide = 5;
var curSlide = 1;
var Ids = 1;
var ajaxCheckInterval = "";
function readImage(input,ids)
{
if (input.files && input.files[0])
{
var reader = new FileReader();
reader.onload = function (e) {
$('#img_'+ids).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
function generateSlide()
{
if( curSlide <= maxSlide )
{
var html ='<br/><div id="slideAdd_'+Ids+'" >';
html+=' <form action="#" id="slide_'+Ids+'" class="form-horizontal" enctype="multipart/form-data">';
html+=' <div class="form-group">';
html+=' <label class="col-sm-3 control-label">Foto Barang</label>';
html+=' <div class="col-sm-9">';
html+=' <input type="hidden" name="ft_'+Ids+'" id="ft_'+Ids+'" value="<?php echo $rd ?>">';
html+=' <input type="hidden" name="ur_'+Ids+'" id="ur_'+Ids+'" value="'+Ids+'" >';
html+=' <input onChange="readImage(this,'+Ids+')" type="file" id="foto_'+Ids+'" name="foto_'+Ids+'" />';
html+=' <img src="images/noimage.jpg" id="img_'+Ids+'" style="width: 300px; height: 250px;" />';
html+=' </div>';
html+=' </div>';
html+=' <div class="form-group">';
html+=' <div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2">';
html+=' <button onClick="removeSlide(\''+Ids+'\'); return false;" class="btn btn-danger"><i class="fa fa-times"></i> Remove</button>';
html+=' </div>';
html+=' </div>';
html+=' </form>';
html+='</div><br/>';
$("#main-content2").append(html);
curSlide++;
Ids++;
}
else
{
}
}
function removeSlide(Ids)
{
$('#slideAdd_'+Ids).slideUp('slow');
setTimeout(function(){ $('#slideAdd_'+Ids).remove(); }, 2000);
curSlide--;
}
function getSlide()
{
showLoading("show");
ajaxCheckInterval = setInterval(function(){ redirectMe() }, 1000);
var a = 1;
for( var i = 0; i <= Ids; i++ )
{
try{
var formData = new FormData();
formData.append("file", $( '#foto_'+i )[0].files[0]);
formData.append("ft", $( '#ft_'+i ).val()) ;
formData.append("ur", $( '#ur_'+i ).val()) ;
uploadSlide(formData,i,Ids);
a++;
}catch(e){
}
}
}
function redirectMe()
{
if($.active == 0){
setTimeout(function(){
showLoading("show");
myStopFunction();
window.location.href = "barang";
}, 1000);
}
}
function myStopFunction() {
clearInterval(ajaxCheckInterval);
}
function uploadSlide(formData,x,Ids2)
{
$.ajax({
url: 'crud.php?type=Foto_Barang',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
if( response != "OK" )
{
// Error In Here
dataSlide = JSON.parse(response);
}
}
});
}
function showLoading( type )
{
if( type == "show" )
{
var html = '';
html += '<div id="loader">';
html += '<div id="loadOver" class="loadOver"></div>';
html += '<div class="loading">';
html += '<img src="images/animatedCircle.gif" />';
html += '</div></div>';
$('body').append(html);
}
else
{
$('#loader').remove();
}
}
</script>
</div>
<center>
<button type="button" class="btn btn-success" onClick="generateSlide()" ><i class="fa fa-plus"></i> Add Photos (Maks : 5)</button>
<button onClick="getSlide()" class="btn btn-primary"><i class="fa fa-check"></i> Save</button>
</center>
and this my PHP crud.php
<?php
include "../element/connection.php";
switch ($_REQUEST['type'])
{
case "Foto_Barang":
{
$foto_id = $_REQUEST['ft'];
$urut = $_REQUEST['ur'];
$path = '../images/barang/';
$url = $path.$foto_id."_".$_FILES["file"]["name"];
if($_FILES['file']['size'] < 500000) // 500 kb
{
move_uploaded_file($_FILES["file"]["tmp_name"],$url);
}
else {
function compress_image($source_url, $destination_url, $quality)
{
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
compress_image($_FILES["file"]["tmp_name"], $url, 20);
}
$sql ="INSERT INTO foto_barang
(foto_id,foto,urut) VALUES ('".$foto_id."','".$foto_id."_".$_FILES["file"]["name"]."','".$urut."')";
if( mysqli_query($con,$sql) ){
echo "OK";
}else{
echo "NOK";
}
break;
}
}
?>
You needs to create correct JSON response instead "echo 'ok';" or "echo 'nook';"
echo json_encode('ok/nook');
And also you need set headers to 'application/json':
headers('Content-Type: application/json');
This is wrong,
dataSlide = JSON.parse(response);
In php, you are echoing OK or NOK, you cannot use parse on that.
Also in php
this will not work
return $destination_url;
Instead,
echo json_encode($destination_url);
I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>