array from php to JavaScript - php

i am trying to transfer a array list from php to javascript with json, but it does not work.
JS:
$.ajax({
url: 'getProfilePhotos.php',
type: 'post', // post or get method
data: {}, // if you need to pass post/get parameterds you can encode them here in JSON format
dataType: 'json', // the data type you want returned... we will use json
success: function(responseData) {
var arrayList[0] = new Array();
var lung = arrayList.length;
for(var i = 0; i<lung; i++)
//arrayList[i] = responseData.i;
console.log(responseData.i);
}});
PHP:
<p> <?php
$array = array();
$nr = count($friends['data']);
for($i = 0; $i < $nr; $i++){
$array = 'link'=>array("http://graph.facebook.com/".$friends['data'][$i]['id']."/picture");
?>
<img src="http://graph.facebook.com/<?php echo $friends['data'][$i]['id'] ?>/picture" />
<?php
}
header('Content-type: application/json');
echo json_encode($array);
?></p>
Update for Christopher McCann
i have got a error in console. this is the error.
[02:46:21.281] missing } after property list # http://romanager.ro/api/examples/script.js:3
line 3 in script.js is
type: 'post', // post or get method
In fact i want to get from facebook profile photos. with php script i managed to get photos, but i can transfer ids from php to javascript. if you need i will try to write entire php script and javascript files.
Update
still have problems with these scripts. in php script i do and authentification of user on facebook, because i need for user ID from facebook to get ids of his friends. to make login i need to create html in php script. well i will post the code of my scripts and i hope you will help me.
PHP script:
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '137061043024243',
'secret' => '619c4dc94343584eb7792ae9933978c9',
'cookie' => true,
));
// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<!--
We use the JS SDK to provide a richer user experience. For more info,
look here: http://github.com/facebook/connect-js
-->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<?php if ($me): ?>
<a href="<?php echo $logoutUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<div>
Using JavaScript & XFBML: <fb:login-button></fb:login-button>
</div>
<div>
Without using JavaScript & XFBML:
<a href="<?php echo $loginUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
</a>
</div>
<?php endif ?>
<?php $array = array();
$nr = count($friends['data']);
echo $nr;
for($i = 0; $i < $nr; $i++) {
$array[$i] = "http://graph.facebook.com/".$friends['data'][$i]['id']."/picture";
}
header('Content-type: application/json');
echo json_encode($array);
?>
</body>
</html>
JAVASCRIPT
$.post("getProfilePhotos.php", function(data) { alert(data); console.log(data);/*DO WHAT YOU WANT WITH DATA HERE*/}, "json");
window.onload = init;
function init() {
if (window.Event) {
document.addEventListener("mousemove", getCursorXY("mousemove"), false);
var cursorXX = 0;
var cursorYY = 0;
var cursorX = document.getElementById("cursorX");
var cursorY = document.getElementById("cursorY");
cursorX.innerHTML = cursorXX;
cursorY.innerHTML = cursorYY;
}
//initializare canvas1
canvas = document.getElementById('game');
//coordonatele unde se afla mouseul
canvas.onmousemove = getCursorXY;
//initializare canvas2
canvas2 = document.getElementById('teroristi');
//coordonatele unde se afla mouseul
canvas2.onmousemove = getCursorXY;
//lista de inamici
lista = new Array();
initial();
for(var j = 0; j < 20; j++)
for(var k = 0; k < 2;k++)
console.log(matx[j][k]);// = -1000;
scor = 0;
viata = 5;
//creerea contextului de desenare 2D
ctx2 = canvas2.getContext("2d");
ctx = canvas.getContext("2d");
//creerea unui obiect imagine
img = new Image();
img.src = 'glont.png';
imgTerorist = new Image();
imgTerorist.src = 'terorist.jpg';
ctx.beginPath();
ctx.stroke();
imgviata = new Image();
imgviata.src = 'vieti.png';
//score();
viataF();
}
//initializeaza matricea de aparitii
function initial(){
matx = new Array(24);
for (var m = 0; m <24; m++)
matx[m] = new Array(3);
for(var m = 0; m < 24; m++)
matx[m][2] = 0;
matx[0][0] = 20;
matx[0][1] = 20;
for(var m = 1; m < 6; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[6][0] = matx[0][0];
matx[6][1] = matx[0][1] + 120;
for(var m = 7; m < 12; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[12][0] = matx[0][0];
matx[12][1] = matx[0][1] + 240;
for(var m = 13; m < 18; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[18][0] = matx[0][0];
matx[18][1] = matx[0][1] + 360;
for(var m = 19; m < 24; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
}
function getCursorXY(e) {
//se ia pozitia de pe axa x al cursorului
cursorXX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
//se ia pozitia de pe axa y al cursorului
cursorYY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
//
var cursorX = document.getElementById("cursorX");
var cursorY = document.getElementById("cursorY");
cursorX.innerHTML = cursorXX;
cursorY.innerHTML = cursorYY;
}
function Nr(){
return Math.floor(Math.random()*24);
}
//stergerea inamicului
function sterge(x){
//setTimeout("genereaza(flag)",3000);
var img = ctx.createImageData(60, 100);
for (var i = img.data.length; --i >= 0; )
img.data[i] = 0;
ctx.putImageData(img, matx[x][0], matx[x][1]);
matx[x][2] = 0;
}
//genereaza inamici
function genereaza(flag){
if(flag == 1){
setTimeout("genereaza(flag)", 2000);
var x = Nr();
terorist(x);
if(lista.length > 3){
viata = viata - 1;
sterge(lista[0]);
lista.splice(0, 1);
viataF();
}
}
}
//creeaza un inamic
function terorist(x){
console.log("X primit = " + x + "valoarea flagului = " + matx[x][2]);
//sterge(x);
if(matx[x][2] == 0){
ctx.drawImage(imgTerorist,matx[x][0],matx[x][1]);
matx[x][2] = 1;
lista.push(x);
}
else if(matx[x][2] == 1){
var q = Nr();
console.log("in recursie: " + q);
terorist(q);
}
}
function viataF(){
var remove = ctx2.createImageData(20,20);
for (var i = remove.data.length; --i >= 0; )
remove.data[i] = 0;
ctx2.putImageData(remove, 10, (10+(viata*20)));
console.log(viata);
for(var m = 0; m < viata; m++)
ctx2.drawImage(imgviata,10,(10+(m*20)));
}
function impuscat(){
var shootX = cursorXX;
var shootY = cursorYY;
var tm = 0;
console.log("ShootX = " + shootX + " ShootY = " + shootY);
for(var m = 0, tm = lista.length; m < tm; m++){
if(shootX >= matx[lista[m]][0] && shootX <= matx[lista[m]][0] + 60 && shootY >= matx[lista[m]][1] && shootY <= matx[lista[m]][1] + 100){
sterge(lista[m]);
lista.splice(m, 1);
scor = scor + 10;
console.log("IMPUSCAT");
}
}
}
function glont(x, y){
ctx.beginPath();
ctx.stroke();
ctx.drawImage(img,x-40,y-40);
impuscat();
}
function mouse(){
impuscat();
/*console.log('Maus apasat');
console.log(cursorXX);
console.log(cursorYY);*/
//glont(cursorXX, cursorYY);
//console.log("Dupa glont()");
}
function start(){
viataF();
flag = 1;
genereaza(flag);
setTimeout("stop()", 10000);
}
function stop(){
ctx2.fillStyle = '#000000';
ctx2.strokeStyle = '#FFFFFF';
ctx2.font = 'bold 30px sans-serif';
ctx2.fillText ('TIMPUL A EXPIRAT!', 100, 200);
ctx2.fillText('Scorul tau este: ' + scor, 100, 235);
console.log("TIMPUL A EXPIRAT");
flag = 0;
genereaza(flag);
}
function score(){
ctx2.fillStyle = '#000000';
ctx2.strokeStyle = '#FFFFFF';
ctx2.font = 'bold 15px sans-serif';
ctx2.fillText('Scorul tau este: ', 350, 20);
}

Your PHP section is wrong as you are still trying to generate HTML, rather than just JSON.
Also the array handling within the loop is incorrect.
Try changing the PHP code to:
<?php
$friendData = array();
foreach ($friends['data'] as $cFriend) {
$friendData[$cFriend['id']] = "http://graph.facebook.com/" . $cFriend['id'] . "/picture";
}
header('Content-Type: application/json');
echo json_encode($friendData);
exit;

Header will not work in this case as you cannot output any content (including whitespace) to the browser before you call header(). In your for loop you output HTML to the browser which will cause an error.
As Orbling said you are also not correctly adding the element to the array. I am just assuming this is what you want but the loop you want is:
for($i = 0; $i < $nr; $i++) {
$array[] = "http://graph.facebook.com/".$friends['data'][$i]['id']."/picture";
}
I am confused by what you are trying to achieve with your javascript. I would use the following code instead to simplify:
$.post("getProfilePhotos.php", function(data) { alert(data); //DO WHAT YOU WANT WITH DATA HERE }, "json");
I would run that code first to check you get the JSON back and then play about with the callback function to do what you want with the returned json.

Related

Convert data to Json in CodeIgniter with AJAX

I am struggling to convert json code in CodeIgniter, i wanna make pagination.
I am using ajax and want to controle data convert to json and send it to view. I can someone explain me how to do that.
Code in controler, instead foreach part i am trying to make Json, and send it to view
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$row = $this->db->get('pages');
$dataString='';
foreach($row->result() as $r){
$id = $r->id;
$info = $r->info;
$dataString .= $id.'|'.$info.'||';
}
echo json_encode($dataString);
}
}
view part
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
// alert(msg)
;
var dataArray = msg.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "ID: "+itemArray[0]+" - Testimonial from <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
});
var paginationCtrls = "";
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
its easy
you should have a view to encode the data to json. Its just this:
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
In the controller you just have to load this view with an array as parameter (i think that stdClass is also valid):
$data['json'] = array("foo" => "bar", "bar" => "foo");
$this->load->view('your_json_view', $data);

How to use google maps to produce a result for a web service

I'd like to use google maps in an unconventional way. I want to execute the javacript but I do not want to render any images. Rather I want to send some data to a file, use some of the computational functions the API has to offer and then pass back a text response. I attempted this with the following code but I then realized this probably won't work as javascript is run in a browser and not as a remote web service. That being said, how could a remote server call a 'web service' much like the one my code below has to offer with the goal of getting the simple 'yes' or 'no' response.
<?php
// Get vars
$lat=$_GET["lat"];
$lon=$_GET["lon"];
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEYNOTYOURS:)&sensor=true&libraries=geometry">
</script>
<script type="text/javascript">
// Poygon getBounds extension - google-maps-extensions
// http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds = function(latLng) {
var bounds = new google.maps.LatLngBounds();
var paths = this.getPaths();
var path;
for (var p = 0; p < paths.getLength(); p++) {
path = paths.getAt(p);
for (var i = 0; i < path.getLength(); i++) {
bounds.extend(path.getAt(i));
}
}
return bounds;
}
}
// Polygon containsLatLng - method to determine if a latLng is within a polygon
google.maps.Polygon.prototype.containsLatLng = function(latLng) {
// Exclude points outside of bounds as there is no way they are in the poly
var bounds = this.getBounds();
if(bounds != null && !bounds.contains(latLng)) {
return false;
}
// Raycast point in polygon method
var inPoly = false;
var numPaths = this.getPaths().getLength();
for(var p = 0; p < numPaths; p++) {
var path = this.getPaths().getAt(p);
var numPoints = path.getLength();
var j = numPoints-1;
for(var i=0; i < numPoints; i++) {
var vertex1 = path.getAt(i);
var vertex2 = path.getAt(j);
if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) {
if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) {
inPoly = !inPoly;
}
}
j = i;
}
}
return inPoly;
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(38.990842,-76.93625),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var box = [new google.maps.LatLng(38.9913160,-76.937079),
new google.maps.LatLng(38.991333,-76.936119),
new google.maps.LatLng(38.990287, -76.936108),
new google.maps.LatLng(38.990278,-76.937057),
new google.maps.LatLng(38.990495,-76.937052),
new google.maps.LatLng(38.990499,-76.936424),
new google.maps.LatLng(38.991091,-76.93643),
new google.maps.LatLng(38.991104,-76.937079)
];
var mPoint = [new google.maps.LatLng(38.991300,-76.936165)];
var AVpoly = new google.maps.Polygon({path:box,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4});
var lat = <?php echo $lat; ?>;
var lon = <?php echo $lon; ?>;
if(AVpoly.containsLatLng(new google.maps.LatLng(lat,lon), box) == true) {
document.write("Yes");
}
else
{
document.write("No");
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
This is not allowed! You may only use Google Maps Data if you are displaying a map that is publicly accessible. See section 9.1 of the TOS and 10.1.1 (g) "No Use of Content without a Google Map.":

Using Facebooks Developers API to access user's friend information

I'm currently working on a website that allows a user to login though Facebook and from that get all of their information to be used on my site.
e.g If they are single or are they interested in women men or both.
I have been looking around on the Facebook Developers side of there site and there is some sample code on there for getting information about what films they like, so I was just wondering if it is possible to change and adapt this to what I need.
Here's some of the code I have found from this page and where it explains it:
http://developers.facebook.com/blog/post/481
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#
appId=YOUR_APP_ID&xfbml=1"></script>
<fb:login-button show-faces="true" width="200" max-rows="1"
perms="user_likes, friends_likes"></fb:login-button>
FB.api('/me/friends', function(response) { });
FB.api(‘/USER_ID/movies’, function(response) { });
FB.api('/'+movieListSorted[i].id, function(response) {
var newDiv = document.createElement("DIV");
newDiv.innerHTML = "<img src='"+response.picture+"'></img><br/>";
if( response.link) {
newDiv.innerHTML+="<a href='"+response.link+"'>"+response.link
+"</a><br/>";
newDiv.innerHTML+='<iframe src="http://www.facebook.com'
+ '/plugins/like.php?'
+ 'href='+response.link+'&layout=standard&'
+ 'show_faces=true&'
+ 'width=450&action=like&colorscheme=light'
+ '&height=80"'
+ 'scrolling="no" frameborder="0" style="border:none;'
+ 'overflow:hidden;'
+ 'width:450px; height:80px;" allowTransparency="true">
+ '</iframe><br/>';
}
document.getElementById(response.id).appendChild(newDiv);
});
<html>
<head>
<title>Test Page</title>
<script>
var movieList = new Array();
var movieListSorted = new Array();
var friendCount = 0;
function showMovies() {
alert(movieList.length);
}
function compareMovies(movieA, movieB) {
if (movieA.name === movieB.name) return 0;
if (movieA.name > movieB.name) return 1;
return -1;
}
function popularMovies(movieA, movieB) {
return movieB.mCount - movieA.mCount;
}
function data_fetch_postproc() {
document.getElementById('test').innerHTML
= "Generating recommendations ... ";
movieList.sort(compareMovies);
// Now we have sorted list, dedupe and count
mCtr = 0;
for (i = 0; i < movieList.length; i++)
{
var count = 0;
movieListSorted[mCtr] = movieList[i];
for ( j = i; j < movieList.length; j++)
{
if ( movieList[i].name === movieList[j].name ) {
count++;
} else {
break;
}
}
i = i+count-1;
movieListSorted[mCtr++].mCount = count;
}
var maxResults = 100;
if( movieListSorted.length < 100) {
maxResults = movieListSorted.length;
}
movieListSorted.sort(popularMovies);
document.getElementById('test').innerHTML = "";
for( i=0; i<maxResults; i++) {
var newDiv = document.createElement("DIV");
newDiv.id = movieListSorted[i].id;
newDiv.innerHTML = movieListSorted[i].name + ' : Likes - '
+ movieListSorted[i].mCount;
document.getElementById("movies").appendChild(newDiv);
FB.api('/'+movieListSorted[i].id, function(response) {
var newDiv = document.createElement("DIV");
newDiv.innerHTML = "<img src='"+response.picture+"'>"
+ "</img><br/>";
if( response.link) {
newDiv.innerHTML+= "<a href='"+response.link+"'>"
+response.link+"</a><br/>";
newDiv.innerHTML+= '<iframe src='
+ '"http://www.facebook.com/plugins/like.php?'
+ 'href='+response.link+'&layout=standard'
+ '&show_faces=true&'
+ 'width=450&action=like&'
+ 'colorscheme=light&height=80"'
+ 'scrolling="no" frameborder="0" style="'
+ 'border:none; overflow:hidden;'
+ 'width:450px; height:80px;"'
+ 'allowTransparency="true"></iframe><br/>';
}
document.getElementById(response.id).appendChild(newDiv);
});
}
}
function get_friend_likes() {
document.getElementById('test').innerHTML = "Requesting "
+ "data from Facebook ... ";
FB.api('/me/friends', function(response) {
friendCount = response.data.length;
for( i=0; i<response.data.length; i++) {
friendId = response.data[i].id;
FB.api('/'+friendId+'/movies', function(response) {
movieList = movieList.concat(response.data);
friendCount--;
document.getElementById('test').innerHTML = friendCount
+ " friends to go ... ";
if(friendCount === 0) { data_fetch_postproc(); };
});
}
});
}
</script>
</head>
<body>
<div id="fb-root"></div>
<div id="login"></div>
<div id="test"></div>
<div id="movies"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR_APP_ID',
status : true, // check login status
cookie : true, // enable cookies
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.sessionChange', function(response) {
window.location.reload();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
get_friend_likes();
document.getElementById('login').innerHTML
='Logout<br/>';
} else {
document.getElementById('login').innerHTML
='<fb:login-button show-faces="true" width="200"'
+ ' max-rows="1" perms="user_likes, friends_likes">'
+ '</fb:login-button>';
FB.XFBML.parse();
}
});
</script>
</body>
</html>
Have you checked out the Graph API:
Facebook Graph API
You also have to make sure you have the proper permissions:
Facebook API Permissions
I'd recommend using the PHP SDK to get this information, especially if you're a beginner. You can use their functions then.
You can find the source code for this (and some documentation included) at the following URL:
https://developers.facebook.com/docs/reference/php/
First of all, in order to get anything from the Graph API, you will need to gain the authentication of the user for your application, this is documented here:
https://developers.facebook.com/docs/authentication/
Then, you can get the information that you need about the current user, using an API call. This is documented here:
http://developers.facebook.com/docs/reference/php/facebook-api/
The code of note here is below, I have edited this to provide the currently logged in user's 'interested_in' field as documented here:
try {
$user_profile = $facebook->api('/me?fields=interested_in','GET');
echo "Interested in: " . $user_profile['interested_in'];
} catch(FacebookApiException $e) {
// Failed API call
error_log($e->getType());
error_log($e->getMessage());
}

undefined value single checkbox javascript to another page

i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltbody>
&lta href="addevent.php" rel="facebox" &gtlink&lt/a&gt
&lt/body>
addevent.php
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltscript language="javascript" type="text/javascript"&gt
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i&ltelemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i &lt len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i&ltformNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i &lt max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
&lt/script&gt
&ltscript type="text/javascript"&gt
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i &lt lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") &gt -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j &lt labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
&lt/script&gt
&lt/head&gt
&ltform name="eventAgendaForm" id="eventAgendaForm" &gt
&ltul class="checklist cl3"&gt
&ltli &gt&ltlabel for="c1"&gt
&ltinput id="checkId" name="checkName" value="1" type="checkbox" &gt
&lt/label&gt&lt/li&gt&lt/ul&gt
&ltinput class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" /&gt
&lt/form&gt
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.

How to handle multiple file upload using PHP

I want to upload files using PHP but the problem is that I don't know how many files I will upload.
My question is how can I upload files if I use file[]?
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label><input type="file" name="file[]" id="file" />
<br />
<label for="file">Filename:</label><input type="file" name="file[]" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
I will add just File box and I will use JavaScript to create more file input to upload but how to handle them in PHP?
See: $_FILES, Handling file uploads
<?php
if(isset($_FILES['file']['tmp_name']))
{
// Number of uploaded files
$num_files = count($_FILES['file']['tmp_name']);
/** loop through the array of files ***/
for($i=0; $i < $num_files;$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$_FILES['file']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['file']['name'][$i].' uploaded';
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
}
}
}
}
?>
This is a preferred method of mine. It includes a mysql insert to keep a table on the images uploaded. It also moves the image to the admin image folder and copies the image to the user sites image folder.
<?php
if(isset($_FILES['image']['tmp_name']))
{
$num_files = count($_FILES['image']['tmp_name']);
for($x =0; $x< $num_files;$x++){
$image = $_FILES['image']['name'][$x];
if(!is_uploaded_file($_FILES['image']['tmp_name'][$x]))
{
$messages[] = $image.' No file uploaded."<br>"';
}
if (move_uploaded_file($_FILES["image"]["tmp_name"][$x],"images/". $image)){
$messages[] = $image .' uploaded';
}
copy("images/".$image, '../images/'.$image);
mysql_query("INSERT INTO $table_name VALUES ('NULL','$id','images/$image')");
}
}
?>
<?php /*insert this into the form*/
$count= count($messages); for ($i =0; $i < $count; $i++){echo $messages[$i]."<br>";}
?>
Try this:
if(isset($_FILES['image_file'])) {
$file = $_FILES['image_file'];
for($i = 0; $i < count($file['name']); $i++){
$image = array(
'name' => $file['name'][$i],
'type' => $file['type'][$i],
'size' => $file['size'][$i],
'tmp_name' => $file['tmp_name'][$i],
'error' => $file['error'][$i]
);
// Here is your code to handle one file
}
In your code, just use '$image' instead of '$_FILES' ...
Ajax js
(function(){
var d = document, w = window;
/**
* Get element by id
*/
function get(element){
if (typeof element == "string")
element = d.getElementById(element);
return element;
}
/**
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}
/**
* Creates and returns element from html chunk
*/
var toElement = function(){
var div = d.createElement('div');
return function(html){
div.innerHTML = html;
var el = div.childNodes[0];
div.removeChild(el);
return el;
}
}();
function hasClass(ele,cls){
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
if (document.documentElement["getBoundingClientRect"]){
var getOffset = function(el){
var box = el.getBoundingClientRect(),
doc = el.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
// for ie
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
// while others are logical. Make all logical, like in IE8.
zoom = 1;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
if (zoom > 1){
clientTop = 0;
clientLeft = 0;
}
var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
return {
top: top,
left: left
};
}
} else {
// Get offset adding all offsets
var getOffset = function(el){
if (w.jQuery){
return jQuery(el).offset();
}
var top = 0, left = 0;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
}
while (el = el.offsetParent);
return {
left: left,
top: top
};
}
}
function getBox(el){
var left, right, top, bottom;
var offset = getOffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetWidth;
bottom = top + el.offsetHeight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
}
/**
* Crossbrowser mouse coordinates
*/
function getMouseCoords(e){
if (!e.pageX && e.clientX){
// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
// while others are logical (offset).
var zoom = 1;
var body = document.body;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
return {
x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
};
}
return {
x: e.pageX,
y: e.pageY
};
}
/**
* Function generates unique id
*/
var getUID = function(){
var id = 0;
return function(){
return 'ValumsAjaxUpload' + id++;
}
}();
function fileFromPath(file){
return file.replace(/.*(\/|\\)/, "");
}
function getExt(file){
return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}
// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
if (button.jquery){
// jquery object was passed
button = button[0];
} else if (typeof button == "string" && /^#.*/.test(button)){
button = button.slice(1);
}
button = get(button);
this._input = null;
this._button = button;
this._disabled = false;
this._submitting = false;
// Variable changes to true if the button was clicked
// 3 seconds ago (requred to fix Safari on Mac error)
this._justClicked = false;
this._parentDialog = d.body;
if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
var parentDialog = jQuery(this._button).parents('.ui-dialog');
if (parentDialog.length){
this._parentDialog = parentDialog[0];
}
}
this._settings = {
// Location of the server-side upload script
action: 'upload.php',
// File upload name
name: 'userfile',
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// Html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// When user selects a file, useful with autoSubmit disabled
onChange: function(file, extension){},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function(file, extension){},
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function(file, response) {}
};
// Merge the users options with our defaults
for (var i in options) {
this._settings[i] = options[i];
}
this._createInput();
this._rerouteClicks();
}
// assigning methods to our class
AjaxUpload.prototype = {
setData : function(data){
this._settings.data = data;
},
disable : function(){
this._disabled = true;
},
enable : function(){
this._disabled = false;
},
// removes ajaxupload
destroy : function(){
if(this._input){
if(this._input.parentNode){
this._input.parentNode.removeChild(this._input);
}
this._input = null;
}
},
/**
* Creates invisible file input above the button
*/
_createInput : function(){
var self = this;
var input = d.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
var styles = {
'position' : 'absolute'
,'margin': '-5px 0 0 -175px'
,'padding': 0
,'width': '220px'
,'height': '30px'
,'fontSize': '14px'
,'opacity': 0
,'cursor': 'pointer'
,'display' : 'none'
,'zIndex' : 2147483583 //Max zIndex supported by Opera 9.0-9.2x
// Strange, I expected 2147483647
};
for (var i in styles){
input.style[i] = styles[i];
}
// Make sure that element opacity exists
// (IE uses filter instead)
if ( ! (input.style.opacity === "0")){
input.style.filter = "alpha(opacity=0)";
}
this._parentDialog.appendChild(input);
addEvent(input, 'change', function(){
// get filename from input
var file = fileFromPath(this.value);
if(self._settings.onChange.call(self, file, getExt(file)) == false ){
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit){
self.submit();
}
});
// Fixing problem with Safari
// The problem is that if you leave input before the file select dialog opens
// it does not upload the file.
// As dialog opens slowly (it is a sheet dialog which takes some time to open)
// there is some time while you can leave the button.
// So we should not change display to none immediately
addEvent(input, 'click', function(){
self.justClicked = true;
setTimeout(function(){
// we will wait 3 seconds for dialog to open
self.justClicked = false;
}, 3000);
});
this._input = input;
},
_rerouteClicks : function (){
var self = this;
// IE displays 'access denied' error when using this method
// other browsers just ignore click()
// addEvent(this._button, 'click', function(e){
// self._input.click();
// });
var box, dialogOffset = {top:0, left:0}, over = false;
addEvent(self._button, 'mouseover', function(e){
if (!self._input || over) return;
over = true;
box = getBox(self._button);
if (self._parentDialog != d.body){
dialogOffset = getOffset(self._parentDialog);
}
});
// we can't use mouseout on the button,
// because invisible input is over it
addEvent(document, 'mousemove', function(e){
var input = self._input;
if (!input || !over) return;
if (self._disabled){
removeClass(self._button, 'hover');
input.style.display = 'none';
return;
}
var c = getMouseCoords(e);
if ((c.x >= box.left) && (c.x <= box.right) &&
(c.y >= box.top) && (c.y <= box.bottom)){
input.style.top = c.y - dialogOffset.top + 'px';
input.style.left = c.x - dialogOffset.left + 'px';
input.style.display = 'block';
addClass(self._button, 'hover');
} else {
// mouse left the button
over = false;
if (!self.justClicked){
input.style.display = 'none';
}
removeClass(self._button, 'hover');
}
});
},
/**
* Creates iframe with unique name
*/
_createIframe : function(){
// unique name
// We cannot use getTime, because it sometimes return
// same value in safari :(
var id = getUID();
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
iframe.id = id;
iframe.style.display = 'none';
d.body.appendChild(iframe);
return iframe;
},
/**
* Upload file without refreshing the page
*/
submit : function(){
var self = this, settings = this._settings;
if (this._input.value === ''){
// there is no file
return;
}
// get filename from input
var file = fileFromPath(this._input.value);
// execute user event
if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
// Create new iframe for this submission
var iframe = this._createIframe();
// Do not submit if user function returns false
var form = this._createForm(iframe);
form.appendChild(this._input);
form.submit();
d.body.removeChild(form);
form = null;
this._input = null;
// create new input
this._createInput();
var toDeleteFlag = false;
addEvent(iframe, 'load', function(e){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
if( toDeleteFlag ){
// Fix busy state in FF3
setTimeout( function() {
d.body.removeChild(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
// fixing Opera 9.26
if (doc.readyState && doc.readyState != 'complete'){
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false"){
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument){
// response is a xml document IE property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = window["eval"]("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
var response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
} else {
// clear input to allow user to select same file
// Doesn't work in IE6
// this._input.value = '';
d.body.removeChild(this._input);
this._input = null;
// create new input
this._createInput();
}
},
/**
* Creates form, that will be submitted to iframe
*/
_createForm : function(iframe){
var settings = this._settings;
// method, enctype must be specified here
// because changing this attr on the fly is not allowed in IE 6/7
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.style.display = 'none';
form.action = settings.action;
form.target = iframe.name;
d.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data){
var el = d.createElement("input");
el.type = 'hidden';
el.name = prop;
el.value = settings.data[prop];
form.appendChild(el);
}
return form;
}
};
})();
jquery code for uploading
$(document).ready(function () {
var btnUpload=$('#browse');
$("#hidauto").css('display','block');
new AjaxUpload(btnUpload, {
action: '<?=site_url('brand/upload_image1/')?>',
name: 'file',
onSubmit: function(file, ext){$("#loadgif1").css("display","block");
if (! (ext && /^(jpg|jpeg|gif|png)$/.test(ext))){
// extension is not allowed
//document.getElementById("loadgif").style.display='block';
$("#loadgif1").css("display","none");
$("#image").css("display","block");
$("#image").html("only jpg,jpeg,png, images are allowed");
return false;
}
},
onComplete: function(file, response){
//alert(response);
if(response=='0'){
$("#primimage1_error").html("This image is too small please upload a bigger one");
$("#loadgif1").css("display","none");
return false;
}
$("#hidauto").css('display','block');
$("#loadgif1").css("display","none");
$("#image").html("");
var r=response;
//document.getElementById("imghid").value=response;
divid=r.replace(new RegExp(".jpg", 'g'),'');
divid=divid.replace(new RegExp(".jpeg", 'g'),'');
divid=divid.replace(new RegExp(".png", 'g'),'');
//alert(divid);
document.getElementById("imghidall").value=document.getElementById("imghidall").value+response+",";
shw='<div style="float: left; height:135px; width:147px;" id='+divid+'><img src="<?php echo base_url();?>uploads/'+response+'" width="125px" height="115px" /><div style="width: 125px;"><input type="radio" name="checkPrimary" title="Set as Primary image" value="'+divid+'" onClick="primaryimg('+"'"+r+"'"+');" style="margin:5px"><img src="<?php echo base_url();?>images/img_delete.png" width="17px" height="17px" title="delete" onClick="delete_image('+"'"+r+"'"+');" width="15px;" height="15px" style="float:right; margin-top:3px;"></div></div>';
// shw='<div style="float: left; height:135px; width:147px;" id='+divid+'><img src="<?php echo base_url();?>uploads/'+response+'" width="125px" height="115px" /><div style="width: 125px;"><input type="checkbox" id="checkPrimary" value="'+divid+'" onClick="primaryimg('+"'"+r+"'"+');" style="margin:5px"><img src="<?php echo base_url();?>images/remove.png" title="delete" onClick="delete_image('+"'"+r+"'"+');" width="15px;" height="15px" style="float:right; margin-top:2px;"></div></div>';
//alert(shw);
$("#hidauto").append( shw );
$("#primimage1_error").html("");
//location.reload();
}
});
});
HTML Code
<div class="r8_prt" style="margin-right: 0px; margin-top: 10px;">
<div class="line1">
<label style="float: left; width: 121px; margin-right:10%;">Upload images : </label><input type="file" name="browse" id="browse" multiple="true" style="float: left;">
<label class="error" for="dwn" id="allimg_error" style="display:block; color: #B94A48;font-size: 11px;font-weight: bold; text-align:center;" ></label>
<label class="error" for="dwn" id="primimage1_error" style="display:block; color: #B94A48;font-size: 11px;font-weight: bold; text-align:center;" ></label>
<label id="loadgif1" style="display:none; width:10px; float:left"><img style="margin-top:-10px" src="<?php echo base_url();?>images/ajax-loader(2).gif"></label>
<div id="image" style="float:left; width:110%; margin-top:20px; color:#F00;">
</div>
<div id="hidauto">
</div>
<input type="hidden" value="" id="imghid" name="imghid">
<input type="hidden" value="" id="imghidall" name="imghidall">
</div>
</div>
Upload function(For Codeigniter)
function upload_image1() {
$ext=$_FILES['file']['name'];
$epld=explode('.',$ext);
$nn= count($epld);$nn-=1;
$photo=date("MdyHis").".".$epld[$nn];
$data = getimagesize($_FILES['file']['tmp_name']);
$width = $data[0];
$height = $data[1]; if($width<250 || $height<250){ echo 0; die(); }
if( move_uploaded_file($_FILES['file']['tmp_name'],"./uploads/".$photo)){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '15360'; //15MB
$config['max_width'] = '0';//'2000'
$config['max_height'] = '0';//'2000'
$config['min_width'] = '250';//'2000'
$config['min_height'] = '250';//'2000'
$this->load->library('upload', $config);
echo $photo;
} }
Delete Image
function delete_image(name)
{
var answer = confirm ("Do you want to delete this image?")
if (!answer)
{
}
else{
var base_url="<?php echo base_url();?>";
$.ajax
({
type: "POST",
url: base_url+"index.php/brand/delete_image/?imgname="+name,
data:'',
success: function(view)
{
name=name+",";
allname=document.getElementById("imghidall").value;
e=document.getElementById("imghidall").value = allname.replace(new RegExp(name, 'g'),'');
divid=name.replace(new RegExp(".jpg,", 'g'),'');
divid=divid.replace(new RegExp(".jpeg,", 'g'),'');
divid=divid.replace(new RegExp(".png,", 'g'),'');
//alert(divid);
document.getElementById(divid).innerHTML="";
$("#"+divid).css('width','0px');
}
});
}
}
Delete image function
function delete_image(){
$file_name=$_GET['imgname'];
unlink(FCPATH . '/uploads/' . $file_name);
unlink(FCPATH . '/uploads/thumb/' . $file_name);
unlink(FCPATH . '/uploads/watermark/' . $file_name);
}
if (isset($_FILES['file']['tmp_name'])) {
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
if ($tmpFilePath != "") {
//. time() . $_FILES['file']['name'][$i] becomes the name of the files
$file[$i] = $newFilePath = "upload/myfolder/" . time() . $_FILES['file']['name'][$i];
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$file[$i] = $newFilePath = "upload/myfolder/" . time() . $_FILES['file']['name'][$i];
}
}
}
}
PUT THIS SIMPLE SCRIPT INTO PHP SCRIPT OR FUNCTION. NB:
$_FILES['file']
because <input type="file" name="file[]" id="file" />

Categories