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();
});
Related
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 :/
I am trying to pass a JQuery variable into PHP code within a single page. It appears that the JQuery variable is firing (I get the confirmation alert back), but it is not being read by the PHP. How do I fix this? *edited for clarity
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").click(function(){
var pastDATE = $(this).text();
$.post("testclick.php", 'pastDATE', function() {
alert(pastDATE, "post success");
});
});
});
/*
var pastDATE = (div.calendar-head
$.ajax({
type: "POST",
url: "testclick.php",
data: {pastDATE: pastDATE},
success: function(data){
alert(data);
}
});
*/
</script>
<style>
.calendar-head {
display: block;
line-height: 32px;
font-weight: bold;
text-align: center;
background: #2F4F4F;
color: #2F4F4F;
background: rgba(0, 0, 0, 0.35);
}
</style>
<body>
<div class="calendar-head">This</div>
<?php
/*attempted to start a session so when page is refreshed the variable remains*/
session_start();
$_SESSION['pastDATE'] = $pastDATE;
$pastDATE = $_POST['pastDATE'];
if(isset($_POST['pastDATE'])){
$pastDATE = $_POST['pastDATE'];
echo "set";
}
echo "$pastDATE";
?>
</body>
</html>
$.post("testclick.php", { pastDATE: pastDATE }, function() {
alert(pastDATE, "post success");
});
Should do the trick
Change JavaScript code to:
$(document).ready(function(){
$("div").click(function(){
var pastDATE = $(this).text();
$.post("testclick.php", { data:pastDATE }, function(result) {
alert(pastDATE, "post success");
});
});
});
And read on PHP like $_REQUEST['data']
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>
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/
i have a big problem , im trying to build a website around the one page template system so hear is how it works..... a user clicks a link: ..... but the problem is i have more then 100 php generated links on one page that is attached to a listener and for some strange reason, every time a link gets clicked, and a user returns back to the main page it doubles the request....
in other words : a user click links.... go to a page ..... and he see's a ton of links.... the user clicks a link..... go to a page. but if a user goes back the ajax call doubles????
ex. 1 post , ... 2 post ..... 4 post.... 8 post ..... 16 post..... 32 post ...... 64 post.....
im trying to debug with chrome, and it shows how many post to the network(HTTP Request) that are made every time one has been called and it shows how many post being made and its doubling
Html Markup :
<script>
// main menu
$('header a').addClass('lvl1Links');
// classifeds
$('#9090 a').addClass('lvl1Links');
//states - citys - cats ads
$('#selectable a').addClass('lvl1Links');
// re-install link management
$(function(){
$('.lvl1Links').click(function(event) {
event.preventDefault();
$('pload').html('<img src="source/image/lbl.gif">');
var page = $(this).attr('id');
var huh = $('input:hidden').val();
var data = 'pop='+huh+'&page='+page;
$.post('source/php/bots/authorize.php',data,function(data){
$('#pager_master_div').html(data).slideDown();
$('pload').html('');
});
});
});
// speacial style on certain input boxes
$('input').addClass('input');
$('#op').removeClass('input');
$('#sp').removeClass('input');
$('button').button();
//$("#BUser_Home_Wrapper a .lvl1Links").removeClass("lvl1Links");
</script><div id="9090"><ol id="selectable"><li class="ui-state-default">
<div class="contr">Alabama</div><div class="citys">Birmingham<br>Montgomery<br>Mobile<br>Huntsville<br>Tuscaloosa<br><li class="ui-state-default">
<div class="contr">Alaska</div><div class="citys">Anchorage<br>Juneau<br>Fairbanks<br>Sitka<br>Ketchikan<br></ol></div><style>
.contr{
}
.citys{
display:none;
position:absolute;
height:110px;
width:100px;
top:30px;
left:-5%;
right:-5%;
z-index:100;
background:#FFF;
border-radius:5px;
border:5px #0099FF solid;
font-size:10px;
}
.cityz{
display:none;
position:absolute;
height:200;
width:100px;
top:-100px;
left:-5%;
right:-5%;
z-index:100;
background:#FFF;
border-radius:5px;
border:5px #0099FF solid;
font-size:10px;
}
.citys a{
font-size:15px;
}
.cityz a{
font-size:15px;
}
#selectable li a{
font-size:14px;
}
#selectable li city a{
}
#selectable {
list-style-type: none; margin: 0; padding: 0;
}
#selectable li {
margin:5px;
position:relative;
border-radius:10px;
padding: 1px;
float:left;
width: 100px;
height: 25px;
text-align: center;
}
</style>
<script>
$('.ui-state-default').mouseenter(function(e) {
$('.citys', this).slideDown(); // added this
}).mouseleave(function(e) {
$('.citys', this).toggle(); // added this
});
// bttom rows
$('.ui-state-default').mouseenter(function(e) {
$('.cityz', this).slideDown(); // added this
}).mouseleave(function(e) {
$('.cityz', this).toggle(); // added this
});
</script>
<results></results><input type="hidden" id="fortknox" name="fortknox" value="c4ca4238a0b923820dcc509a6f75849b"><results></results><input type="hidden" id="fortknox" name="fortknox" value="c4ca4238a0b923820dcc509a6f75849b">
<script>
$('input').addClass('input');
$('button').button();
// click event for all links
$(function(){
$('.lvl1Links').click(function(event) {
event.preventDefault();
$('pload').html('<img src="source/image/lbl.gif">');
var page = $(this).attr('id');
var huh = $('input:hidden').val();
var data = 'pop='+huh+'&page='+page;
$.post('source/php/bots/authorize.php',data,function(data){
$('#pager_master_div').html(data).slideDown();
$('pload').html('');
});
});
});
</script>
php code:
<?
case 'class':
require('functions/cats.php');
classie($p);
break;
function classie($p){
connect();
$state = explode(':',$p[2]);
$total = count($state);
$s = md5('?').'.class.';
$sid = $state[1];
$state = $state[0];
echo "$state";
echo "<ol id=\"selectable\">";
if(isset($p[3])){
$city = explode(':',$p[3]);
$cid = $city[1];
$city = $city[0];
echo " : $city";
$sqlca = mysql_query("SELECT * FROM `cats` WHERE `cityId`= ".$cid." ");
while($rowsy = mysql_fetch_array($sqlca)){
echo " : ".$rowsy['name']."";
}
}
?>
you can solve your problem using unbind click to prevent double clicking and causing
multiple entry. Take a look my revision about your code on JS below:
$(function(){
$('.lvl1Links').bind(''click,function(event) {
event.preventDefault();
$('pload').html('<img src="source/image/lbl.gif">');
var page = $(this).attr('id');
var huh = $('input:hidden').val();
var data = 'pop='+huh+'&page='+page;
$.post('source/php/bots/authorize.php',data,function(data){
$('#pager_master_div').html(data).slideDown();
$('pload').html('');
});
$(this).unbind(event);
});
});