Uploading a file using ajax and php - php

I want to implement file uploading using ajax and php. I have a form input tag. I want that onchange event of the input tag, file will be uploaded to the server and I will get the path of the file in a variable in javascript! So, I want to remain on the same page and upload the file, get the file path in the javascript variable.
Any pseudo code, examples, or tutorials would be greatly appreciated.

Demo url:--
http://jquery.malsup.com/form/progress.html
You can download jQuery files from this url and add in html <head> tag
http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js
http://malsup.github.com/jquery.form.js
Try this:
This is my html markup:
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
My php code:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>

This is one way and how I did it. Working with XHR. I have it up and running as we speak
Using HTML5 file uploads with AJAX and jQuery
http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface
$(':file').change(function(){
var file = this.files[0];
name = file.name;
size = file.size;
type = file.type;
if(file.name.length < 1) {
}
else if(file.size > 100000) {
alert("File is to big");
}
else if(file.type != 'image/png' && file.type != 'image/jpg' && !file.type != 'image/gif' && file.type != 'image/jpeg' ) {
alert("File doesnt match png, jpg or gif");
}
else {
$(':submit').click(function(){
var formData = new FormData($('*formId*')[0]);
$.ajax({
url: 'script', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // progressbar
}
return myXhr;
},
//Ajax events
success: completeHandler = function(data) {
/*
* workaround for crome browser // delete the fakepath
*/
if(navigator.userAgent.indexOf('Chrome')) {
var catchFile = $(":file").val().replace(/C:\\fakepath\\/i, '');
}
else {
var catchFile = $(":file").val();
}
var writeFile = $(":file");
writeFile.html(writer(catchFile));
$("*setIdOfImageInHiddenInput*").val(data.logo_id);
},
error: errorHandler = function() {
alert("NĂ¥got gick fel");
},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
}, 'json');
});
}
});

you should probably check out some of the cool jQuery plugins, that can do the job for you, the two popular plugins are.
http://www.uploadify.com/
http://www.plupload.com/

Related

On the click of the image it is not removing in jQuery

Selecting the multiple image from the input tag after that I am previewing the selected image but when I click on that image it should delete from the input tag it does not select that picture any more. But in my case that picture is removing only in preview not in input. And save it into database
Here is the code
<?php
include_once 'Functions.php';
$connect=new Connection();
$link=$connect->Connect();
print_r($_FILES['fil']['name']);
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var image=('')
('input[type="file"]'). change(function(e){
var fileName = e. target. files[0]. name;
alert('The file "' + fileName + '" has been selected.' );
});
$(function() {
var imagesPreview = function(input,placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="picture" width="70" name="multipic">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
$('.picture').click(function(){
$(this).remove();
});
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this,'div.gallery');
});
});
});
</script>
</head>
<body>
<form name="update" enctype='multipart/form-data' method="POST">
<input type="file" name="fil[]" multiple id="gallery-photo-add" class="a1">
<div class="gallery"></div>
<input type="submit" name="btnupdate" value="Update" />
</form>
</body>
</html>
Here is HTML Code :
<div class="container">
<form id="fileupload" action="#" method="POST" enctype="multipart/form-data">
<div class="row files" id="files1">
<h2>Files 1</h2>
<span class="btn btn-default btn-file">
Browse <input type="file" name="files1" multiple />
</span><br/>
<ul class="fileList"></ul>
</div>
<div class="row">
<button type="x" id="uploadBtn" class="btn primary start">Start upload</button>
</div>
<div class="row">
<div class="span16">
<table class="zebra-striped"><tbody class="files"></tbody></table>
</div>
</div>
</form>
</div>
Here is CSS Code :
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}
Here is jQuery Code :
$.fn.fileUploader = function (filesToUpload, sectionIdentifier) {
var fileIdCounter = 0;
this.closest(".files").change(function (evt) {
var output = [];
for (var i = 0; i < evt.target.files.length; i++) {
fileIdCounter++;
var file = evt.target.files[i];
var fileId = sectionIdentifier + fileIdCounter;
filesToUpload.push({
id: fileId,
file: file
});
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + fileId + "\">Remove</a>";
output.push("<li><strong>", escape(file.name), "</strong> - ", file.size, " bytes. ", removeLink, "</li> ");
};
$(this).children(".fileList")
.append(output.join(""));
//reset the input to null - nice little chrome bug!
evt.target.value = null;
});
$(this).on("click", ".removeFile", function (e) {
e.preventDefault();
var fileId = $(this).parent().children("a").data("fileid");
// loop through the files array and check if the name of that file matches FileName
// and get the index of the match
for (var i = 0; i < filesToUpload.length; ++i) {
if (filesToUpload[i].id === fileId)
filesToUpload.splice(i, 1);
}
$(this).parent().remove();
});
this.clear = function () {
for (var i = 0; i < filesToUpload.length; ++i) {
if (filesToUpload[i].id.indexOf(sectionIdentifier) >= 0)
filesToUpload.splice(i, 1);
}
$(this).children(".fileList").empty();
}
return this;
};
(function () {
var filesToUpload = [];
var files1Uploader = $("#files1").fileUploader(filesToUpload, "files1");
$("#uploadBtn").click(function (e) {
e.preventDefault();
var formData = new FormData();
for (var i = 0, len = filesToUpload.length; i < len; i++) {
formData.append("files", filesToUpload[i].file);
}
$.ajax({
url: "",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("DONE");
files1Uploader.clear();
},
error: function (data) {
alert("ERROR - " + data.responseText);
}
});
});
});
Try above code. Hope this will help

Passing JavaScript Variables from JavaScript to PHP using AJAX

I am having some problems with my PHP file. So basically I am working on a project that takes two addresses from the user, then it uses javascript to show their route and once they click submit, I want to pass these two variables to PHP file. I researched a lot and found that I would need AJAX call. The problem I am running into is that AJAX call works perfectly, but when I go to PHP file it throws me an error that variables are not defined. Someone, please explain to me what I am doing wrong here.
JavaScript code:
/* ============================================================================================
Reference: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-directions
==============================================================================================
*/
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 41.881832, lng: -87.623177},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var submit_button = document.getElementById('button-to-submit');
/*var modeSelector = document.getElementById('mode-selector');*/
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
/*this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');*/
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(submit_button);
/*this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);*/
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
/* AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
}; */
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
origin_addr = document.getElementById('origin-input').value;
//console.log(origin_addr);
destination_addr = document.getElementById('destination-input').value;
//console.log(destination_addr);
//var place_id = document.getElementById('origin-input');
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
$("#button-to-submit").click(function() {
$.ajax({
url: "Database/save-points.php",
type: "POST", //send it through get method
data: {
origin_address: origin_addr,
destination_address: destination_addr
},
success: function(response) {
//Do Something
console.log("Succeed");
location.href="Database/save-points.php";
},
error: function(xhr) {
//Do Something to handle error
}
});
});
PHP code:
<?php
$origin_address = $_POST['origin_address'];
$destination_address = $_POST['destination_address'];
echo $origin_address;
echo $destination_address;
?>
/* maps.php */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr" dir="ltr">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js" type="text/javascript"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#origin-input,
#destination-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 200px;
}
#origin-input:focus,
#destination-input:focus {
border-color: #4d90fe;
}
#mode-selector {
color: #fff;
background-color: #4d90fe;
margin-left: 12px;
padding: 5px 11px 0px 11px;
}
#mode-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
</head>
<body>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination location">
<div id="mode-selector" class="controls">
<input type="radio" name="type" id="changemode-walking" checked="checked">
<label for="changemode-walking">Walking</label>
<input type="radio" name="type" id="changemode-transit">
<label for="changemode-transit">Transit</label>
<input type="radio" name="type" id="changemode-driving">
<label for="changemode-driving">Driving</label>
<input type="submit" id="button-to-submit" value="SAVE !" />
</div>
<div id="map"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOU_KEY&libraries=places"></script>
<script type="text/javascript">
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var modeSelector = document.getElementById('mode-selector');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
/************************************/
$(document).ready( function() {
$("#button-to-submit").click(function() {
origin_addr = $("#origin-input").val();
destination_addr = $("#destination-input").val();
$.ajax({
type: "POST",
url: "maps.exe.php",
data: {
origin_address: origin_addr,
destination_address: destination_addr
},
success: function(response){
alert(response);
window.location.href = 'test-resp.php?'+response;
}
});
return false;
});
});
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMap" async defer></script>
</body>
</html>
/* maps.exe.php */
<?php
$origin_address = $_POST['origin_address'];
$destination_address = $_POST['destination_address'];
echo"origin=$origin_address&destination=$destination_address";
?>
/* test-resp.php */
<?php
$origin_address = $_GET['origin'];
$destination_address = $_GET['destination'];
echo"[ origin : $origin_address / destination = $destination_address ]";
?>
I have an example of me passing JS variable to PHP.
JS (url and content are JS variables) :
var data_to_send = {
filepath: ""+url,
filecontent: ""+content
};
jQuery.ajax({
url:"php/dynamic.php",
data: data_to_send,
cache: false,
async: true,
type:'post',
timeout:3000//purely optionnal, check jQuery's Doc to learn more about ajax optionnal parameters/settings
});
In dynamic.php :
<?php
$vars = serialize($_POST); /*easier access*/
$file_path = "../".$vars["filepath"];
$file_content = $var["filecontent"]; /*example of assigning a JS var's value to a PHP var*/
$fh = fopen($file_path, 'w+') or die("could not open file");
fwrite($fh, $file_content."\n");
fclose($fh);
?>
PS: I use jQuery for POST, I dunno the pure javascript way to do the same :/

angularjs file upload on file select with php

I wanted to upload an image after the selection without submit button.
I used danialfarids plugins from GitHub.
I suppose he made the server with C#, which I wanted to change to php. I'm having problems writing the php file handler.
This is my script files.
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadPic = function(file) {
file.upload = Upload.upload({
method:'POST',
url: 'http://localhost/angular/upload.php',
data: {file: file, username: $scope.username}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
And this is my html file
<form name="myForm" >
<fieldset>
<legend>Upload on file select</legend>
<br>Photo:
<input type="file" ngf-select="uploadPic(picFile)" ng-model="picFile" name="picFile"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFiles">
<img ng-show="myForm.file.$valid" ngf-thumbnail="picFile" class="thumb">
<br>
<button ng-disabled="!myForm.$valid"
ng-click="uploadPic(picFile)">Submit</button>
<div class="con">
<div class="pg" style="width:{{picFile.progress}}%" ></p></div>
</div>
<p ng-bind="picFile.progress + '%'"></p>
<span ng-show="picFile.result">Upload Successful</span>
<span class="err" ng-show="errorMsg">{{errorMsg}}</span>
</fieldset>
</form>
This is the css
<style>
.thumb {
width: 240px;
height: 240px;
float: none;
position: relative;
top: 7px;
}
form .progress {
line-height: 1px;
}
.progress {
display: inline-block;
width: 300px;
}
.con{
width:300px;
}
.pg {
font-size: smaller;
background: #000000;
width:0px;
height:1px;
}
</style>
And this is the rudimentary upload.php (found in localhost/angular/) and I don't think it works.
<?php if ( !empty( $_FILES ) ) {
$tempPath = $_FILES[ 'picFile' ][ 'tmp_name' ];
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'picFile' ][ 'name' ];
move_uploaded_file( $tempPath, $uploadPath );
$answer = array( 'answer' => 'File transfer completed' );
$json = json_encode( $answer );
echo $json; } else {
echo 'No files'; } ?>
My xampp server is working. And I also included angular files, angularjs, ng-file-upload-shim.min.js and ng-file-upload.min.js from danialfarid.
I Found the answer to this question, the problem was not on the code, the problem happened because I was making XMLHttpRequest to a different domain than I was in. And the easy way to solve this problem is by adding extension to chrome. Cors extension. This solved the problem.

trouble passing php variable to modal window

Hi I'm using the following code to load the file modal_window.php into a modal window on the current page.
<style>
* {
margin:0;
padding:0;
}
#overlay {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
background:#000;
opacity:0.5;
filter:alpha(opacity=50);
}
#modal {
position:absolute;
background:url(tint20.png) 0 0 repeat;
background:rgba(0,0,0,0.2);
border-radius:14px;
padding:8px;
}
#content {
border-radius:8px;
background:#fff;
padding:20px;
}
#close {
position:absolute;
background:url(close.png) 0 0 no-repeat;
width:24px;
height:27px;
display:block;
text-indent:-9999px;
top:-7px;
right:-7px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script>
var modal = (function(){
var
method = {},
$overlay,
$modal,
$content,
$close;
// Center the modal in the viewport
method.center = function () {
var top, left;
top = Math.max($(window).height() - $modal.outerHeight(), 0)
/ 2;
left = Math.max($(window).width() - $modal.outerWidth(), 0)
/ 2;
$modal.css({
top:top + $(window).scrollTop(),
left:left + $(window).scrollLeft()
});
};
// Open the modal
method.open = function (settings) {
$content.append(settings.content);
$modal.css({
width: settings.width || 'auto',
height: settings.height || 'auto'
})
method.center();
$(window).bind('resize.modal', method.center);
$modal.show();
$overlay.show();
};
// Close the modal
method.close = function () {
$modal.hide();
$overlay.hide();
$content.empty();
$(window).unbind('resize.modal');
};
// Generate the HTML and add it to the document
$overlay = $('<div id="overlay"></div>');
$modal = $('<div id="modal"></div>');
$content = $('<div id="content"></div>');
$close = $('<a id="close" href="#">close</a>');
$modal.hide();
$overlay.hide();
$modal.append($content, $close);
$(document).ready(function(){
$('body').append($overlay,
$modal);
});
$close.click(function(e){
e.preventDefault();
method.close();
});
return method;
}());
// Wait until the DOM has loaded before querying the document
$(document).ready(function(){
varid = '<?php if(isset($_GET['id'])); ?>';
$('a#testmodal').click(function(e){
$.get('modal_window.php?id=varid', function(data){
modal.open({content: data});});
e.preventDefault();
});
});
</script>
</head>
<body>
<a id="testmodal" href="modal.php?id=1">Test</a>
While doing so I'm attempting to pass the variable $id to modal_window.php using :
varid = '<?php if(isset($_GET['id'])); ?>';
and then
$('a#testmodal').click(function(e){
$.get('modal_window.php?id=varid', function(data){
modal.open({content: data});});
e.preventDefault();
});
Instead of the actual value of $id (1 in this case) getting passed to modal_window.php what is getting passed is the name of the java script variable (varid). So "varid" is what is being displayed by modal_window.php. Does anyone see the mistake I'm making? Thanks!
In your get call you have id equal to the literal varid. Instead maybe
$.get('modal_window.php?id=' + varid, function(data){
modal.open({content: data});});
e.preventDefault();
});

progress bar with $.ajax and php

I'm trying to make a progress bar which works with $.ajax(jquery) and php for a file uploader but I dont know how to assemble it. I know there is a progress bar working with jQuery UI; how ever, it just change while receiving a value. And that's the point. How can I get a dinamic value for the byte uploded?
By the way, this is my code:
fx_file.js
/*This function gets Data from the form and send it to server*/
function fiEnviarDatos2(){
$("form#data").click(function(){
/*Some DOM'S animations*/
});
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "PHP/Core/Archivos/upload.php",
type: 'POST',
data: formData,
async: false,
success: function (data) {
/*After actions**/
},
progress:function(data){
alert(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});`
upload.php
<?php include ("Class_upload.php");
/*Variables*/
$i=0;
$archivos=0;
/*Contains numbers of file sent*/
$archivos=((count($_FILES,1)-6)/5);
/*Contains the user's session name*/
session_start();
$sUsuario=$_SESSION['usuario'];
/*Use the information of each file to create a new class Upload*/
for($i=0;$i<$archivos;$i++){
/*FileSize*/
$tamaArchivo = $_FILES['formUploader']['size'][$i];
/*Filename*/
$nombArchivo = strtolower($_FILES['formUploader']['name'][$i]);
/*Filetemp*/
$tmpArchivo = $_FILES['formUploader']['tmp_name'][$i];
/*It creates class Upload*/
$archivo_subir=new Upload($nombArchivo,$tamaArchivo,$tmpArchivo,$sUsuario);
/*It validates each file and returns a status*/
$estatus=$archivo_subir->enviarData();
/*Returns if file's been uploaded or not*/
$resultFile=$archivo_subir->resultFile($estatus);
echo "<br>";
if($estatus>0){
echo "<div class='resultDeny'>".$resultFile."</div>";
}else{
if($resultFile=="ServerError"){
echo "<div class='resultServer'>".$resultFile."</div>";
}else{
echo "<div class='resultSuccess'>".$resultFile."</div>";
}
}
}
I hope I can found some help from you, guys. I know you all are expert. I'm new working with jquery and php; however , i've seen "their power together" and i want to learn more about them.
Thanks for all.
PDT: Sorry for my english, it's not my mother language. JQ &PHP will be.
Check this page out:
http://www.johnboy.com/php-upload-progress-bar/
http://www.johnboy.com/php-upload-progress-bar/upload_frame.phps
basically
function(data) //return information back from jQuery's get request
{
$('#progress_container').fadeIn(100); //fade in progress bar
$('#progress_bar').width(data +"%"); //set width of progress bar based on the $status value (set at the top of this page)
$('#progress_completed').html(parseInt(data) +"%"); //display the % completed within the progress bar
}
)},500);
after investigating almost all day , I achieved what I wanted.
I found this plugin called JQUERY Form Plugin.
[http://malsup.com/jquery/form/][1]
Maybe some of you have used it. It has almost all the necessary options to built a progressbar and to introduce code before and after submitting the form.
So, check it out. Maybe someone finds it useful
Btw , this is how my code looks like now
accountUser.html
<html>
//...
...//
<style>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; margin-top:-200px }
.bar { background-image:url(Imagenes/index/pbar-ani.gif); width:0%; height:20px; border- radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
<script language="javascript" src="Scripts/jquery_min_1.8.js"></script>
<script language="javascript" src="Scripts/fx_file.js"></script>
<script language="javascript" src="Scripts/jquery.form.js"></script>
//...
..//
<form action="#" method="post" enctype="multipart/form-data" id="formu">
<input name="formUploader[]" type="file" multiple id="archivo"/>
<input class="button" type="submit" alt="Upload" value="Subir" id="btn_cargar"/>
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
//...
..//
</html>
fx_file.js
$(document).ready(function() {
// prepare Options Object
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
var options = {
url: "upload.php",
type: 'POST',
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$(bar).animate({width:percentVal});
percent.html(percentVal);
},
success: function(data){
//After actions
}
};
// bind 'formu' and provide a simple callback function
$('#formu').ajaxForm(options);
});
upload.php
<?php include ("Class_upload.php");
/*Variables*/
$i=0;
$archivos=0;
/*Contains numbers of file sent*/
$archivos=((count($_FILES,1)-6)/5);
/*Contains the user's session name*/
session_start();
$sUsuario=$_SESSION['usuario'];
/*Use the information of each file to create a new class Upload*/
for($i=0;$i<$archivos;$i++){
/*FileSize*/
$tamaArchivo = $_FILES['formUploader']['size'][$i];
/*Filename*/
$nombArchivo = strtolower($_FILES['formUploader']['name'][$i]);
/*Filetemp*/
$tmpArchivo = $_FILES['formUploader']['tmp_name'][$i];
/*It creates class Upload*/
$archivo_subir=new Upload($nombArchivo,$tamaArchivo,$tmpArchivo,$sUsuario);
/*It validates each file and returns a status*/
$estatus=$archivo_subir->enviarData();
/*Returns if file's been uploaded or not*/
$resultFile=$archivo_subir->resultFile($estatus);
echo "<br>";
if($estatus>0){
echo "<div class='resultDeny'>".$resultFile."</div>";
}else{
if($resultFile=="ServerError"){
echo "<div class='resultServer'>".$resultFile."</div>";
}else{
echo "<div class='resultSuccess'>".$resultFile."</div>";
}
}
}//End For
<?php>

Categories