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

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

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"/>

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 :/

Updated the jquery array to the hidden field using jquery

I Have Multi-selcet Box. this my Html code:
<section class="container">
<div>
<select id="leftValues" name="leftValues[]" size="5" multiple>
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
<input type="hidden" id="txtLeft" name=txtLeft/>
</div>
<div>
<input type="button" id="btnLeft" value="<<" />
<input type="button" id="btnRight" value=">>" />
</div>
<div>
<select id="rightValues" name=rightValues[] size="4" multiple>
<option value="x">9</option>
<option value="y">8</option>
<option value="z">7</option>
</select>
<div>
<input type="hidden" id="txtRight" name=txtRight/>
</div>
</div>
</section>
<button type="submit" id="value" class="blue">Save</button>
This what the jQuery I have tried. I want the all the value in the array addedLeftValues to be updated to txtLeft and values in addedRightValues to be updated to txtRight when I click on the Save button.
<script>
var left;
var right;
var newLeft;
var newRight;
var addedLeftValues = new Array();
var addedRightValues = new Array();
$(document).ready(function() {
SaveOldValues();
});
function SaveOldValues()
{
left = new Array();
right = new Array();
$('#leftValues .left').each(function(){
left.push($(this).val());
});
$('#rightValues .right').each(function(){
right.push($(this).val());
});
}
function UpdatedValues()
{
newLeft = new Array();
newRight = new Array();
$('#leftValues .left').each(function(){
newLeft.push($(this).val());
});
$('#rightValues .right').each(function(){
newRight.push($(this).val());
});;
}
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$(selectedItem).attr("class","left");
$("#leftValues").append(selectedItem);
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected");
$(selectedItem).attr("class","right");
$("#rightValues").append(selectedItem);
});
$("#rightValues").change(function () {
var selectedItem = $("#rightValues option:selected");
});
$("#value").on("click",function(){
UpdatedValues();
$(newLeft).each(function(k,value){
if($.inArray(value, left) == -1)
{
alert("new value in left is: " + value);
addedLeftValues.push(value);
$("#txtLeft").val(function(i, v) {
arr.push(addedLeftValues);
});
}
});
$(newRight).each(function(k,value){
if($.inArray(value, right) == -1)
{
alert("new value in Right is: " + value);
addedRightValues.push(value);
$("#txtRight").val(function(i, v) {
arr.push(addedRightValues);
});
}
});
});
And this is my CSS code:
<style>
SELECT, INPUT[type="text"] {
width: 160px;
box-sizing: border-box;
}
SECTION {
padding: 8px;
background-color: #f0f0f0;
overflow: auto;
}
SECTION > DIV {
float: left;
padding: 4px;
}
SECTION > DIV + DIV {
width: 40px;
text-align: center;
}
</style>
it seems to works when you put all your codes inside the dome ready method
$(function () {
var left;
var right;
var newLeft;
var newRight;
var addedLeftValues = new Array();
var addedRightValues = new Array();
SaveOldValues();
function SaveOldValues() {
left = new Array();
right = new Array();
$('#leftValues .left').each(function () {
left.push($(this).val());
});
$('#rightValues .right').each(function () {
right.push($(this).val());
});
}
function UpdatedValues() {
newLeft = new Array();
newRight = new Array();
$('#leftValues .left').each(function () {
newLeft.push($(this).val());
});
$('#rightValues .right').each(function () {
newRight.push($(this).val());
});;
}
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$(selectedItem).attr("class", "left");
$("#leftValues").append(selectedItem);
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected");
$(selectedItem).attr("class", "right");
$("#rightValues").append(selectedItem);
});
$("#value").click(function () {
UpdatedValues();
$(newLeft).each(function (k, value) {
if ($.inArray(value, left) == -1) {
alert("new value in left is: " + value);
addedLeftValues.push(value);
$("#txtLeft").val(function (i, v) {
arr.push(addedLeftValues);
});
}
});
$(newRight).each(function (k, value) {
if ($.inArray(value, right) == -1) {
alert("new value in Right is: " + value);
addedRightValues.push(value);
$("#txtRight").val(function (i, v) {
arr.push(addedRightValues);
});
}
});
});
});
but then you'll be faced by a new error on line 54 and line 64 arr.push(addedRightValues); ReferenceError: arr is not defined
check it on fiddlejs http://jsfiddle.net/p6MKv/

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();
});

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