angularjs file upload on file select with php - 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.

Related

AJAX : Pass an image and data through Single AJAX [duplicate]

This question already has answers here:
How to send image to PHP file using Ajax?
(5 answers)
jQuery AJAX file upload PHP
(5 answers)
jQuery / ajax upload image and save to folder
(3 answers)
Upload image using jQuery, AJAX and PHP
(2 answers)
Closed 4 years ago.
I want to pass some text data and file through one ajax code
Here is my code's index.php :-
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Karthikeyan K">
<title>POST</title>
<!-- Bootstrap CSS file -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<style type="text/css">
body {
padding: 45px;
}
footer {
margin: 10px 0;
}
.photo {
margin-bottom: 10px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mentionsInput.css">
<style type="text/css">
#status-overlay {
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.50);
position: fixed;
top: 0;
left: 0;
z-index: 99999;
overflow: hidden;
}
#highlight-textarea {
background: #fff;
}
.form-control:focus {
box-shadow: 0 0 0 2px #3399ff;
outline: 0;
}
h2 {
font-size: 20px;
}
</style>
<style>
#upload_button {
display: none;
border: 0px;
background: linear-gradient(180deg, #f44, #811);
border-radius: 5px;
color: #fff;
padding: 5px;
}
</style>
</head>
<body>
<div id="status-overlay" style="display: none"></div>
<form method="POST" class="form" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" id="title" class="form-control" placeholder="Post title..."><br>
<div id="highlight-textarea">
<textarea onclick="highlight();" name="postText" class="form-control postText mention" cols="10" rows="8" placeholder="What's going on?" dir="auto"></textarea>
</div><br>
<select class="form-control" name="type" id="type" required>
<option value="">Choose Post Type</option>
<option value="Closet">Closet</option>
<option value="Follower">Follower</option>
<option value="Group">Group</option>
</select><br>
<p><button id="upload_button">Click here to select file</button></p>
<p><input id="upload_input" name="upfile" type="file"/></p>
</div>
<input type="button" value="Post" class="btn btn-primary pull-right postMention">
</form>
<!-- Bootstrap Script file -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src='https://cdn.rawgit.com/jashkenas/underscore/1.8.3/underscore-min.js' type='text/javascript'></script>
<script src='js/lib/jquery.elastic.js' type='text/javascript'></script>
<script type="text/javascript" src="js/jquery.mentionsInput.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('textarea').on('click', function(e) {
e.stopPropagation();
});
$(document).on('click', function (e) {
$("#status-overlay").hide();
$("#highlight-textarea").css('z-index','1');
$("#highlight-textarea").css('position', '');
});
});
function highlight()
{
$("#status-overlay").show();
$("#highlight-textarea").css('z-index','9999999');
$("#highlight-textarea").css('position', 'relative');
}
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
//post text in jquery ajax
var post_data = "text="+encodeURIComponent(post_text);
var val1 = $('#title').val();
var val2 = $('#type').val();
//var val3 = $('#upload_input');
//var post_title = $('#title').val();
var form = new FormData(document.getElementById('.postMention'));
//append files
var file = document.getElementById('upload_input').files[0];
if (file) {
form.append('upload_input', file);
}
$.ajax({
type: "POST",
data: post_data+'&title='+val1+'&type='+val2+'&upload_input='+form,
url: 'ajax/post.php',
success: function(msg) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
}
});
} else {
alert("Post cannot be empty!");
}
});
});
//used for get users from database while typing #..
$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('ajax/get_users_json.php', function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
});
</script>
</body>
</html>
<?php } ?>
here's a code of my php file to insert data into database ajax/post.php
. . . .
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
if(isset($_POST) && !empty($_POST['text']) && $_POST['text'] != '')
{
include '../config/config.php';
$user = $uid; //w3lessons demo user
$postid=mt_rand();
$text = strip_tags($_POST['text']); //clean the text
$title= $_POST['title'];
$type= $_POST['type'];
define('FIRST_MATCH_GROUP', 1);
preg_match_all("/#\[(.+)\]/U", $text, $tags); // Value under #[]
$tags = implode(',', $tags[FIRST_MATCH_GROUP]);
$upfile_name = $_FILES['upload_input']['name'];
$upfile_size =$_FILES['upload_input']['size'];
$upfile_tmp =$_FILES['upload_input']['tmp_name'];
$upfile_type=$_FILES['upload_input']['type'];
$upfile_t = explode(".", $_FILES["upload_input"]["name"]);
$upfile_name = mt_rand() . '.' . end($upfile_t);
if($upfile_type == "image/jpg" && $upfile_type == "image/png" && $upfile_type == "image/jpeg" && $upfile_type == "video/mp4"){
echo "<script>window.alert('extension not allowed, please choose a JPG or PNG or MP4 file.');</script>";
}
else {
if($upfile_size > 10485760){
echo "<script>window.alert('File size must be Less 10 MB');</script>";
}
else {
move_uploaded_file($upfile_tmp,"../../uploads/".$upfile_name);
$DB->query("INSERT INTO posts(post_id,title,content,user_id,type,tags,image) VALUES(?,?,?,?,?,?,?)", array($postid,$title,$text,$user,$type,$tags,$upload_input));
?>
<div class="media">
<div class="media-left">
<img src="https://cdn.w3lessons.info/logo.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">w3lessons</h4>
<p><?php echo getMentions($text); ?></p>
</div>
</div>
<hr>
<?php
} } } else {
echo "1"; //Post Cannot be empty!
}
function getMentions($content)
{
global $DB;
$mention_regex = '/#\[([0-9]+)\]/i'; //mention regrex to get all #texts
if (preg_match_all($mention_regex, $content, $matches))
{
foreach ($matches[1] as $match)
{
$match_user =$DB->row("SELECT * FROM register WHERE id=?",array($match));
$match_search = '#[' . $match . ']';
$match_replace = '<a target="_blank" href="' . $match_user['profile_img'] . '">#' . $match_user['first_name'] . '</a>';
if (isset($match_user['id']))
{
$content = str_replace($match_search, $match_replace, $content);
}
}
}
return $content;
}
}?>
When i submit form data was passing at my php page but images index is goes undefined...
change the way you pass data in request
try this
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
var formData = new FormData($('.form')[0]);
formData.append('text',encodeURIComponent(post_text));
$.ajax({
url: 'ajax/post.php',
type: 'POST',
data: formData,
success: function (data) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
},
cache: false,
contentType: false,
processData: false
});
} else {
alert("Post cannot be empty!");
}
});
});
and input name
<input id="upload_input" name="upload_input" type="file"/>

z-index is not working when script send from controller to jquery ajax

i'm having a problem to set z-index between image and div (i prepare this div to save the edit (reupload new image) and delete button.
for your information i'm using ajax and codeigniter to handle an image upload, and after the image uploaded, i want to view the image with the edit and delete button on it.
and this is my html
<div class="writecontainer">
<div class="dropable">
<input class="ufile" type="file" accept="image/*" id="file" name="file"/>
<p class="italic tcenter" style="margin-top:-120px;color:#a6a6a6;z-index:0">
<img src="<?php echo base_url().'images/login/2camera48.png';?>"/>
<br>
click or drop your image here
</p>
</div>
</div>
the css style
.writecontainer{
margin-top:30px;
width:600px;
margin-left:auto;
margin-right:auto;
}
.dropable{
background:#e0ebeb;
border-radius:10px;
text-align:center;
}
.writecontainer > .dropable > img.uploadtemp{
width:100%;
border-radius:10px;
}
.writecontainer .dropable input.ufile{
display:block;
width:100%;
height:150px;
border:1px solid yellow;
border-radius:10px;
opacity:0;
}
and the ajax (jquery)
$('#file').on('change',function(){
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/login/index.php/dashboard_main/upload_file',
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('.dropable').html(response);
$('.dropable').removeAttr('style');
$(".dropable").css("height:auto");
$(".dropable div.editcontainer").css({"z-index":"99"});
$(".dropable > img").css({"z-index":"-1"});
},
error: function (response) {
alert(response);
}
});
});
and the method in the controller is
public function upload_file() {
$xx['userData'] = $this->session->userdata('userData');
//upload file
$config['upload_path'] = 'images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_filename'] = '5000000';
$config['encrypt_name'] = FALSE;
$config['max_size'] = '1024000'; //1 MB
$config['file_name'] = $xx['userData']['oauth_uid'].'_'.$_FILES['file']['name'];
if (isset($_FILES['file']['name'])) {
//$new = 'xyz'.$_FILES['file']['name'];
if (file_exists('images/' . $config['file_name'])) {
echo 'File already exists in the desire destination';
} else {
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo '<img class="uploadtemp" src="'.base_url().'images/' . $config['file_name'].'"><div class="editcontainer" style="height:45px; margin-top:-50px;border:1px solid red;"></div>';
}
}
//echo $_FILES['file']['name'];
} else {
echo 'Image upload unsuccessful';
}
}
first, i set z-index in controller, but nothing happen. so i think maybe it must be set after i print out the html data in ajax, but z-index still error. any help will be appreciated, thank you
If you want to pass an html in ajax from your controller, just add the css in the style tag like this and add !important. z-index: 9999 !important. Example z-index: 9999 !important
echo '<img class="uploadtemp" src="'.base_url().'images/' . $config['file_name'].'"><div class="editcontainer" style="height:45px; margin-top:-50px;border:1px solid red;z-index: 9999 !importantz-index: 9999 !important"></div>';

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>

Javascript error: Uncaught SyntaxError: Unexpected token }

I am creating a chat for my site. It works fine, but a function isn't working inside of a HTML button. I have 3 files I use for it, and one line isn't working.
Before, I had an issue where I set the Javascript function, create the button, and it would say the function doesn't exist. I fixed that, by putting the function below the buttons.
Each button shows an online member, who is on your friends list.
The error I get in confusing me, as I have no idea how this is being caused.
Error: 'Uncaught SyntaxError: Unexpected token } users.php:3'
(users.php is the page I was on, if I change it that changes to the page name.)
With chrome, I can click on the error, that brings up this: 'window.script1357688207590=1;'
Scripts (sorry for being so long):
Script 1: (main script):
var username = '[error]';
$.ajax({
url: 'bchat.php',
type: 'post',
data: { method: 'method2' },
success: function(data){
username = data;
}
});
$.ajax({
url: 'bchat.php',
type: 'post',
data: { method: 'method1' },
success: function(data){
if(data!='do not show chat'){
function ToggleChat(tof){
if(tof == true){
$('#chatWindow').css('visibility','visible');
}else{
$('#chatWindow').css('visibility','hidden');
}
}
$('body').append('\
<div id=chatWindow style="background:white; visibility
:hidden; position: fixed; bottom: 0; right: 0; margin-top:-30px; width:200px; height:350px;">\
<div style="width:100%; height:100%; border:solid black 1px;">\
<div style="hieght:20px; background:rgb(40,40,40); color:white;">\
'+data+'<span> </span>'+username+'\
<button id=chat_close style="float:right; background:rgba(0,0,0,0); border:none; color:white;">\
Close\
</button>\
</div>\
<div id=chatOnline style="overflow:auto;">\
</div>\
</div>\
</div>\
<div id=chat__window style="background:white; visibility:hidden; position: fixed; bottom: 0; right: 200; margin-top:-30px; margin-left:-400px; width:200px; height:350px;">\
\
</div>\
<div id=chat style="position: fixed; bottom: 0; right: 0;">\
<button id=chat_open style="border:none; padding:5px; color:whiteSmoke; background-image: -ms-linear-gradient(bottom, #4A4A4A 0%, #00070A 100%);background-image: -moz-linear-gradient(bottom, #4A4A4A 0%, #00070A 100%);background-image: -o-linear-gradient(bottom, #4A4A4A 0%, #00070A 100%);background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #4A4A4A), color-stop(1, #00070A));background-image: -webkit-linear-gradient(bottom, #4A4A4A 0%, #00070A 100%);background-image: linear-gradient(to top, #4A4A4A 0%, #00070A 100%); width:200px; height:30px;">\
'+data+' <span> </span>Chat\
</button>\
</div>');
$('#chat_open').click(function() {
ToggleChat(true);
});
$('#chat_close').click(function() {
ToggleChat(false);
});
}
}
});
//
//update online users
//
function updateOnline(){
$.ajax({
url: 'bchat.php',
type: 'post',
data: { method: 'method3' },
success: function(data){
$('#chatOnline').html(data);
}
});
}
updateOnline();
setInterval(updateOnline,5000);
Script 2 (function script):
function chatWith(url,un){
$('#chat__window').html('<div style="width:100%; height:100%; margin-top:-30px; border:solid black 1px;"><div style="hieght:20px; background:rgb(40,40,40); color:white;">'+url+'<span> </span>'+un+'<button id=chat_chatting_close style="float:right; background:rgba(0,0,0,0); border:none; color:white;">Close</button></div><div id=chat_chats style="overflow:auto;"></div></div>');
$('#chat__window').css('visibility','visible');
}
PHP script (bchat.php):
<?php
include_once("./login_manager_php_file.php");
if($username&&$userid){
$method = $_POST['method'];
if($method){
if($method=='method1'){
$url = $images['logged_in'];
$html = "<img src='".$url."' width=7.5 height=7.5/>";
}elseif($method=='method2'){
echo $username;
}elseif($method=='method3'){
$friends_q = mysql_query("SELECT * FROM friends WHERE `with`='$username' OR `friender`='$username'");
$thtml = '';
if($friends_q){
while($friend = mysql_fetch_assoc($friends_q)){
if($friend['with']==$username){
$usern = $friend['friender'];
}else{
$usern = $friend['with'];
}
$url = '';
if(ifLoggedIn($usern)===true){
$url = $images['logged_in'];
}else{
$url = $images['logged_out'];
}
if(ifLoggedIn($usern)===true && $usern != $username){
$on = $url;
$html = "
<button onClick='
chatWith('$url','$usern');
'
style='border:none; background:rgba(0,0,0,0);'><img src='".$url."' width=7.5 height=7.5/>";
$thtml = $thtml.$html.$usern.'</button><br/>';
}
}
}
echo $thtml;
}elseif($method==='method4'){
if($_POST['usrn']){
$url = '';
if(ifLoggedIn($_POST['usrn'])===true){
$url = $images['logged_in'];
}else{
$url = $images['logged_out'];
}
echo "<img src='".$url."' width=7.5 height=7.5/>";
}else{
echo '[error]';
}
}
}
}else{
echo 'do not show chat';
}
?>
Try to change the php to add an id attribute to the button, or class if there is going to be more than one. Also, remove the onclick attribute
<button class="btnChat" ...
Just realized you will need to add in the parameters as well. I would add those to data attributes on the button.
<button class="btnChat" data-url="$url" data-usern="$usern"
You will need to make sure the $url and $usern are escaped properly
then in the script 2 file you can hook up the click event for that button:
$(function(){
$('body').on('click','.btnChat',function(){
chatWith($(this).data('url'),$(this).data('usern'));
});
});

Uploading a file using ajax and 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/

Categories