By the click of the delete button, I receive this error. SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Can someone help me resolve it as all efforts to resolve it have proved futile.
Here's a screenshot of the error.
json error
And here's the screenshot of my directory structure.
directory structure
Here's the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Bootstrap File Upload</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/fileinput.min.js" type="text/javascript"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<input id="files" name="images[]" type="file" multiple=true class="file-loading">
</body>
<?php
$directory = "images_/";
$images = glob($directory . "*.*");
?>
<script>
$("#files").fileinput({
uploadUrl: "upload.php",
uploadAsync: false,
minFileCount: 1,
maxFileCount: 20,
showUpload: false,
showRemove: false,
initialPreview: [
<?php foreach($images as $image){?>
"<img src='<?php echo $image; ?>' height='120px' class='file-preview-image'>",
<?php } ?>],
initialPreviewConfig: [<?php foreach($images as $image){ $infoImages=explode("/",$image);?>
{caption: "<?php echo $infoImages[1];?>", height: "120px", url: "delete.php", key:"<?php echo $infoImages[1];?>"},
<?php } ?>]
}).on("filebatchselected", function(event, files) {
$("#files").fileinput("upload");
});
</script>
</html>
Here's my upload.php
<?php
$enclosedFolder="images_/";
// Count sent by plugin
$Images =count(isset($_FILES['images']['name'])?$_FILES['images']['name']:0);
$infoImagesUploaded = array();
for($i = 0; $i < $Images; $i++) {
// The name and the temporary file name we're gonna attach
$nameFile=isset($_FILES['images']['name'][$i])?$_FILES['images']['name'][$i]:null;
$nameTemp=isset($_FILES['images']['tmp_name'][$i])?$_FILES['images']['tmp_name'][$i]:null;
$pathFile=$enclosedFolder.$nameFile;
move_uploaded_file($nameTemp,$pathFile);
$infoImagesUploaded[$i]=array("caption"=>"$nameFile","height"=>"120px","url"=>"delete.php","key"=>$nameFile);
$ImagesUploaded[$i]="<img height='120px' src='$pathFile' class='file-preview-image'>";
}
$arr = array("file_id"=>0,"overwriteInitial"=>true,"initialPreviewConfig"=>$infoImagesUploaded,
"initialPreview"=>$ImagesUploaded);
echo json_encode($arr);
?>
And here's my delete.php
<?php
$enclosedFolder="images_/";
if($_SERVER['REQUEST_METHOD']=="DELETE"){
parse_str(file_get_contents("php://input"),$dataDELETE);
$key= $dataDELETE['key'];
unlink($enclosedFolder.$key);
echo 0;
}
?>
As seen on Github:
Its an error on your server code returning an invalid json format for
your upload response. Debug it with firebug or javascript console and
resolve to return a right JSON format. You must return a RIGHT JSON
response from your AJAX (even if you do not have anything... you must
at least return an empty JSON object like {}).
In PHP file, I'm feedback empty JSON to Ajax
return "{}";
or
echo "{}";
Related
I have been trying to implement the FilePicker.io API to let users upload images on a product page and I have been desperately trying to display the uploaded files (images only) on the page. The Filepicker opens fine, I can upload the image successfully etc, so after uploaded a file I can see in the console that I have an object with some information about the newly uploaded file. All I want now is to display the images, using $.ajax POST ? Here is the code I have so far:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Upload</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//api.filepicker.io/v2/filepicker.js"></script>
<script type="text/javascript">
$(function() {
filepicker.setKey('l5uQ3k7FQ5GoYCHyTdZV');
$('#big-freaking-button').click(function() {
filepicker.pickAndStore({},{location: 's3'},function(fpfiles){
console.log(JSON.stringify(fpfiles));
});
});
});
</script>
</head>
<body>
</div>
<div id="content">
<div class="row button">
Filepicker Something
</div>
</div>
</body>
</html>
UPDATE:
Ok I have manage to display one image... using the filepicker and a placeholder. Now can any one tell me how to display multiple images as a gird?
Working Exemple
$('#big-freaking-button').click(function(){
filepicker.pickAndStore({},{location: 's3'},
function(fpfiles){
console.log(JSON.stringify(fpfiles));
},
function(Blob) {
console.log(Blob);
console.log(Blob.url);
$.ajax("/upload", {
type: "POST",
data: {
product_id: {{{ $product->id }}},
img_path: Blob.url
}
});
}
)
};
You will need to store the URL somewhere for this to work, then in your HTML you can perform a foreach to display the images:
<?php foreach($product->images as $image){ ?>
<img src="{{{ $image->img_path }}}">
<?php } ?>
I would like to get the value sent from php via AJAX in php. But i can not get value. Where is my mistake?
It is my functions.js
$(document).ready(function(){
$(".yeni_problem").click(function(){
var uid = 1;
$.ajax({
url: 'admin.php',
type: "post",
data: {'uid': uid},
success: function(data){
// $("#cvb").text(data);
},
statusCode: {
404: function(){
alert("admin.php not found");
}
}
});
});
});
and it is my php page that, i control sending value in here. The Codes is large but i write small form. Which that when i run the small codes on other folders as other site it does't work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HELPDESK</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/css.css">
<link rel="stylesheet" href="css/default.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/icon.css">
</head>
<body>
<button class="yeni_problem">Yeni Problem</button>
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "<hr>Value not found<br/>";
}
var_dump($_POST);
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="bootstrap.min.js"></script>
<?php
echo "</body>
</html>";
?>
When i click to ".yeni_problem" class i can not get value.
1st- check you include Jquery
2nd- Be sure admin.php page in the same directory with file you called functions.js in if not check its path
3rd- you pass uid not data so in php use
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "Value not found";
}
?>
4th: and if you dynamically generate the element with class="yeni_problem" .. so use
$('body').on('click',".yeni_problem", function(){
instead of
$(".yeni_problem").click(function(){
5th: if yeni_problem is a submit button or anchor so you need to use e.preventDefault(); to prevent page from reloading
$(".yeni_problem").click(function(e){
e.preventDefault();
// rest of code here
6th: if yeni_problem is a form use .submit()
$(".yeni_problem").submit(function(e){
e.preventDefault();
// rest of code here
Pay attention to your code: in the JS snippet, the parameter passed to the server is "uid", which means your server will be getting a $_POST array with a position labeled "UID".
<?php
if(isset($_POST["uid"])){
echo "Value:".$_POST["uid"];
}else{
echo "Value not found";
}
?>
You should also check what is in the $_POST variable, insert var_dump($_POST) and comment out the rest of the code.
I'm trying to pass a simple variable from my jQuery to my php and then echo it on my HTML. It doesn't seem to work though.
I can't get my variable $result to show up on my page. Any thoughts? The Ajax POST seems to be working fine. The problem seems to be communication between php and HTML.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='front.js'></script>
</head>
<body>
<?php echo $result; ?>
</body>
</html>
front.js:
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(data) {
});
});
back.php:
<?php $result = $_POST['name']; ?>
Try this
index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='front.js'></script>
</head>
<body>
</body>
</html>
front.js:
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(result) {
$('body').html(result);
});
});
back.php:
<?php echo $_POST['name']; ?>
Change this
<body>
<div id="show-data"></div>
</body>
And
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(data) {
$('#show-data').html(data);
});
});
And
<?php echo $result = $_POST['name']; ?>
Change Your PHP Code :
<?php echo $_POST['name']; ?>
And Also Your HTML Code :
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
</body>
<script>
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(data) {
$('body').append(data)});
});
</script>
</html>
$result in back.php and $result in index.html aren't related. Setting it in back.php has no effect on index.html. If you echo something in back.php however, that output will be passed to the empty callback function you have in your $.post() call. You can handle the data there and use javascript to insert it into your page.
Just add the following line to your code: $('body').html(data);
Like your question we have three different files one is index.html
1) index.html
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='front.js'></script>
</head>
<body>
<?php echo $result; ?>
</body>
</html>
2) front.js
$(document).load(function(){
$.ajax({
url: '/back.php',
type: 'POST',
data: 'name=Bob',
async: false,
success: function(data) {
$('body').html(data);
},
cache: false
});
});
3) back.php
<?php echo $result = $_POST['name']; ?>
Now use this, your files will work out. Please let me know if you have any queries.
Puh, lot of mistakes. First, your index.html contains PHP - Code which won't be executed because this is not a PHP - Skript (ending with php).
Second you are saving the value of your request to back.php in a variable, which won't be existing after the request is finished. You can either:
rename index.html to index.php, exchange your statement to
<?php echo $_POST['name']; ?>
and change your request to
$.get('/index.php', {name: "Bob"}, function(data) {
});
which would cause a continously reloading of the site,
or store your result in a $_SESSION (see PHP Session Handling), and retrieve that in your index.php (you got to rename the file).
I have a SlickGrid set up, it is reading data from my database with PHP, my problem is arising when i try to save the data back to my database, I am trying to use JSON to give me an array that I can then use to write back to the database, i have see this thread explaining this:
Saving changes in SlickGrid
So I have the hidden form element in my code, and am using JSON to encode the data variable, the assign it to the data hidden input on the form, this form posts to a page called save_price.php, the trouble is when I print_r, or var_dump the data variable, I get null as an output, I think it might be something to do with how I am using PHP to add the content into the data variable, either that or I am doing something really obviously wrong, hopefully you can see what the problem is, there isn't a great deal of documentation online about retrieving/saving to a db with PHP, so I'm kinda stuck banging my head against the wall on this one, here's my code:
Ok so I found the problem, just incase anyone is struggling to get this all to work, here is the working code, it gets data from a database, then sends the changed data to another page for processing, it nees a little bit of refinements, that will happen once I've got it all implemented:
<?php
include("includes/check_session.php");
require_once('includes/functions.php');
require_once('includes/config.php');
$data = '';
$i = 0;
$query = "
SELECT * FROM `prices`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$data .= '
data['.$i.'] = {
id: "'.$row['id'].'",
title: "'.$row['title'].'",
duration: "'.$row['duration'].'",
percentComplete: "'.$row['percentComplete'].'",
start: "'.$row['start'].'",
finish: "'.$row['finish'].'",
effortDriven: "'.$row['effortDriven'].'"
};
';
$i++;
echo $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<?php // include("includes/cms_head_scripts.php"); ?>
<link rel="stylesheet" href="css/slick.grid.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/examples.css" type="text/css" media="screen" charset="utf-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" src="js/jquery.json.js"></script>
</head>
<body>
<div id="content_cont">
<div id="main">
<div style="position:relative">
<div style="width:600px;">
<div id="myGrid" style="width:100%;height:500px;"></div>
</div>
</div>
pricing
</div><!-- #main -->
</div><!-- #content_cont -->
<script src="lib/firebugx.js"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js"></script>
<script src="lib/jquery.event.drag-2.0.min.js"></script>
<script src="slick.core.js"></script>
<script src="plugins/slick.cellrangeselector.js"></script>
<script src="plugins/slick.cellselectionmodel.js"></script>
<script src="slick.editors.js"></script>
<script src="slick.grid.js"></script>
<script type="text/javascript">
var grid;
var data = [];
var columns = [
{id:"title", name:"Title", field:"title", editor:TextCellEditor},
{id:"duration", name:"Duration", field:"duration", editor:TextCellEditor},
{id:"%", name:"% Complete", field:"percentComplete", editor:TextCellEditor},
{id:"start", name:"Start", field:"start", editor:TextCellEditor},
{id:"finish", name:"Finish", field:"finish", editor:TextCellEditor},
{id:"effort-driven", name:"Effort Driven", field:"effortDriven", editor:TextCellEditor}
];
var options = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true
};
$(function() {
<?php echo $data ?>
grid = new Slick.Grid($("#myGrid"), data, columns, options);
})
</script>
<form method="POST" action="save_price.php">
<input type="submit" value="Save">
<input type="hidden" name="data" value="">
</form>
<script type="text/javascript">
$(function() {
$("form").submit(
function() {
$("input[name='data']").val($.JSON.encode(data));
}
);
});
</script>
</body>
</html>
I have a simple upload form working in PHP (works in web) and also am able to capture a photo from iPhone using PhoneGap (base64) and displaying it on the device.
But I can't figure out how to upload it to my server with PHP.
Here's the code running in PHP:
INDEX.PHP
<?
//print_r($_POST);
if($_POST["action"] == "Upload Image")
{
unset($imagename);
if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;
if(!isset($_FILES['image_file']))
$error["image_file"] = "An image was not found.";
$imagename = basename($_FILES['image_file']['name']);
//echo $imagename;
if(empty($imagename))
$error["imagename"] = "The name of the image was not found.";
if(empty($error))
{
$newimage = "images/" . $imagename;
//echo $newimage;
$result = #move_uploaded_file($_FILES['image_file']['tmp_name'], $newimage);
if(empty($result))
$error["result"] = "There was an error moving the uploaded file.";
}
}
include("upload_form.php");
if(is_array($error))
{
while(list($key, $val) = each($error))
{
echo $val;
echo "<br>\n";
}
}
include("list_images.php");
?>
And here are the two includes...
UPLOAD_FORM.PHP
<form method="POST" enctype="multipart/form-data" name="image_upload_form" action="<?$_SERVER["PHP_SELF"];?>">
<p><input type="file" name="image_file" size="20" value="beautiful.jpg"></p>
<p><input type="submit" value="Upload Image" name="action"></p>
</form>
LIST_IMAGES.PHP
<?
$handle = #opendir("images");
if(!empty($handle))
{
while(false !== ($file = readdir($handle)))
{
if(is_file("images/" . $file))
echo '<img src="images/' . $file . '"><br><br>';
}
}
closedir($handle);
?>
Here's the code running on iPhone 4 (iOS 4.2) in PhoneGap
INDEX.HTML (running in WWW directory in PhoneGap)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=yes" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="style.css">
<!-- iPad/iPhone specific css below, add after your main css >
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" />
-->
<!-- If you application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here -->
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.min.js"></script>
<script type="text/javascript" charset="utf-8">
// If you want to prevent dragging, uncomment this section
/*
function preventBehavior(e)
{
e.preventDefault();
};
document.addEventListener("touchmove", preventBehavior, false);
*/
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* When this function is called, PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
// do your thing!
}
function getPicture(sourceType)
{
var options = { quality: 10 };
if (sourceType != undefined) {
options["sourceType"] = sourceType;
}
// if no sourceType specified, the default is CAMERA
navigator.camera.getPicture(getPicture_Success, null, options);
};
function getPicture_Success(imageData)
{
//alert("getpic success");
document.getElementById("test_img").src = "data:image/jpeg;base64," + imageData;
}
</script>
</head>
<body onload="onBodyLoad()" marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>
<h1>Camera</h1>
<img style="width:80px;height:120px" id="test_img" src="" />
<p>
<!-- for testing, add the buttons below -->
<button onclick="getPicture()">From Camera</button>
<p>
<button onclick="getPicture(PictureSourceType.PHOTO_LIBRARY)">From Photo Library</button>
</body>
</html>
</html>
Incidentally, while I can grab a fresh picture from the device camera, I've been completely unable to get images from the Library... if anyone knows how to do that, I'd appreciate feedback there too.
Had anyone been able to upload photos from PhoneGap/iPhone to PHP? Any source code on both sides of this would be GREATLY appreciated.
The Base64 option is really just for ease of displaying on the webpage. if it's not needed then don't use it.
i'd say your best option is to use FILE_URI instead of DATA_URL for Camera.DestinationType
check out http://docs.phonegap.com/phonegap_camera_camera.md.html for more info
Use options PHOTOLIBRARY or SAVEDPHOTOALBUM to get existing pictures from your phone. See more at http://docs.phonegap.com/en/1.4.0/phonegap_camera_camera.md.html#Camera.
In phonegap:
$.post(URLReport,{
pic1: document.getElementById("image1").src.slice(23),
}, function(xml) {
//stuff to do on success
});
On server:
if (isset($_POST['pic1'])) {
$pic = base64_decode( $_POST['pic1']);
if (strlen($pic) > 9 ) {
$fh = fopen(yourfilename, 'w') or die("can't open file");
fwrite($fh, $pic);
fclose($fh);
}
}
Easy peasy.