I have this code in client side:
fileUpload: function monkey(){
var file = t.gI("photoFile"); //get element by photoFile
var formData = new FormData();
console.log(file.files.length);
formData.append("upload", file.files[0]);
var req = t.gR(); //XMLHTTPRequest
req.open('POST', 'php/fileupload.php', true);
req.setRequestHeader("Content-Type", "multipart/form-data", true);
req.send(formData);
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status == 200 && req.status < 300) {
t.gI("eventBox").innerHTML = req.responseText; //eventbox error handler
adminHandler.eventBox();
}
}
}
},
And this in server side:
<?php
header('Content-Type:multipart/form-data');
echo $_FILES['upload']['tmp_name'];
?>
And I got this error msg:
[15-Jun-2015 12:03:21 UTC] PHP Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0
[15-Jun-2015 12:03:21 UTC] PHP Notice: Undefined index: upload in /home/webprogb/public_html/php/fileupload.php on line 4
What can I do to fix it?
You can use this code for file uploading with ajax in pure javascript. Change this "#fileUploader" according to file field ID.
var AjaxFileUploader = function () {
this._file = null;
var self = this;
this.uploadFile = function (uploadUrl, file) {
var xhr = new XMLHttpRequest();
xhr.onprogress = function (e) {
//error
};
xhr.onload = function (e) {
//error
};
xhr.onerror = function (e) {
//error
};
xhr.open("post", uploadUrl, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
};
};
AjaxFileUploader.IsAsyncFileUploadSupported = function () {
return typeof (new XMLHttpRequest().upload) !== 'undefined';
}
if (AjaxFileUploader.IsAsyncFileUploadSupported) {
ajaxFileUploader = new AjaxFileUploader();
$("form").submit(function () {
var uploader = $("#fileUploader")[0];
if (uploader.files.length == 0) {
return;
} else {
ajaxFileUploader.uploadFile(
"/YourUploadUrl",
uploader.files[0]);
}
return false;
});
}
Related
I downloaded one jquery crop image module it is working fine,actually i want now that original image value,from this code i got only for cropped image value,when i upload one image means i want store that image in without crop,actually i don't know how to get that value in this code reference URL http://fengyuanchen.github.io/cropper/v1.0.0/
$(function () {
'use strict';
var console = window.console || { log: function () {} };
var $body = $('body');
// Tooltip
// $('[data-toggle="tooltip"]').tooltip();
// $.fn.tooltip.noConflict();
// $body.tooltip();
// Demo
// ---------------------------------------------------------------------------
(function () {
var $image = $('.img-container > img');
console.log($image);
var $actions = $('.docs-actions');
var $download = $('#download');
//console.log($download);
var $dataX = $('#dataX');
var $dataY = $('#dataY');
var $dataHeight = $('#dataHeight');
var $dataWidth = $('#dataWidth');
var $dataRotate = $('#dataRotate');
var $dataScaleX = $('#dataScaleX');
var $dataScaleY = $('#dataScaleY');
var options = {
aspectRatio: 16 / 9,
preview: '.img-preview',
crop: function (e) {
$dataX.val(Math.round(e.x));
$dataY.val(Math.round(e.y));
$dataHeight.val(Math.round(e.height));
$dataWidth.val(Math.round(e.width));
$dataRotate.val(e.rotate);
$dataScaleX.val(e.scaleX);
$dataScaleY.val(e.scaleY);
}
};
$image.on({
'build.cropper': function (e) {
//console.log(e.type);
},
'built.cropper': function (e) {
//console.log(e.type);
},
'cropstart.cropper': function (e) {
//console.log(e.type, e.action);
},
'cropmove.cropper': function (e) {
//console.log(e.type, e.action);
},
'cropend.cropper': function (e) {
//console.log(e.type, e.action);
},
'crop.cropper': function (e) {
// console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY);
},
'zoom.cropper': function (e) {
console.log(e.type, e.ratio);
}
}).cropper(options);
// Methods
$actions.on('click', '[data-method]', function () {
var $this = $(this);
var data = $this.data();
var $target;
var result;
if ($this.prop('disabled') || $this.hasClass('disabled')) {
return;
}
if ($image.data('cropper') && data.method) {
data = $.extend({}, data); // Clone a new one
if (typeof data.target !== 'undefined') {
$target = $(data.target);
if (typeof data.option === 'undefined') {
try {
data.option = JSON.parse($target.val());
} catch (e) {
//console.log(e.message);
}
}
}
result = $image.cropper(data.method, data.option, data.secondOption);
if (data.flip === 'horizontal') {
$(this).data('option', -data.option);
}
if (data.flip === 'vertical') {
$(this).data('secondOption', -data.secondOption);
}
if (data.method === 'getCroppedCanvas' && result) {
$('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
if (!$download.hasClass('disabled')) {
$download.attr('href', result.toDataURL());
console.log(result.toDataURL());//data:base64 ans
$(document).ready(function(){
$('#crop').click(function(){
//console.log('ok');
$.ajax({
type:'POST',
url: "crop_image_insert.php",
data: ({'crop': result.toDataURL()}),
success:function(data){
console.log(data);
if(data == 'SUCCESS'){
window.location.assign('php/timeline.php?id=<?php echo $ssmid;?>');
}
},
error:function(error){
alert('n');
}
});
});
});
}
}
if ($.isPlainObject(result) && $target) {
try {
$target.val(JSON.stringify(result));
} catch (e) {
}
}
}
});
// Keyboard
$body.on('keydown', function (e) {
if (!$image.data('cropper') || this.scrollTop > 300) {
return;
}
switch (e.which) {
case 37:
e.preventDefault();
$image.cropper('move', -1, 0);
break;
case 38:
e.preventDefault();
$image.cropper('move', 0, -1);
break;
case 39:
e.preventDefault();
$image.cropper('move', 1, 0);
break;
case 40:
e.preventDefault();
$image.cropper('move', 0, 1);
break;
}
});
// Import image
var $inputImage = $('#inputImage');
var URL = window.URL || window.webkitURL;
var blobURL;
if (URL) {
$inputImage.change(function () {
var files = this.files;
var file;
if (!$image.data('cropper')) {
return;
}
if (files && files.length) {
file = files[0];
if (/^image\/\w+$/.test(file.type)) {
blobURL = URL.createObjectURL(file);
$image.one('built.cropper', function () {
URL.revokeObjectURL(blobURL); // Revoke when load complete
}).cropper('reset').cropper('replace', blobURL);
$inputImage.val('');
} else {
$body.tooltip('Please choose an image file.', 'warning');
}
console.log($inputImage.val(''));
}
});
} else {
$inputImage.prop('disabled', true).parent().addClass('disabled');
}
}());
});
function uploadFile() {
var fd = new FormData();
var count = document.getElementById('image').files.length;
for (var index = 0; index < count; index ++)
{
var file = document.getElementById('image').files[index];
fd.append('myFile', file);
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.open("POST", "savetofile.php", false);
xhr.send(fd);
}
function updateProgress(evt) {
/* This event is raised when the server send back a response */
$.mobile.showPageLoadingMsg();
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
$.mobile.hidePageLoadingMsg()
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
I am using Jquert mobile framework and in this XMLHttpRequest I am uploading a file to the server and it takes around 5-6 seconds to complete.I have read that to add and remove the page load(spinner) for jquery mobile just add $.mobile.showPageLoadingMsg() [to load] and $.mobile.hidePageLoadingMsg()[to remove]. Have I placed the function in the wrong positions? or did I make some other mistake ?
Found on solution
function uploadFile() {
//ad this code
$.mobile.loading('show', {
theme: "a",
text: "yoo",
textonly: true,
textVisible: true
});
//end
var fd = new FormData();
var count = document.getElementById('image').files.length;
for (var index = 0; index < count; index ++)
{
var file = document.getElementById('image').files[index];
fd.append('myFile', file);
}
I want to send and receive data from php files. What is the best possible way to do this?
What is the best replacement for GDownloadUrl in Google Map V3?
Here is my existing function to check if I inserted successfully:
function checkSaveGeoFenceData(data,code)
{
//var geoFenceDataJson = eval('(' + json + ')');
if(code===200)
{
//alert("JSON VALUE : "+data+"test");
if(data=="SMGFE\n")
{
alert("Geo Fence " +
document.getElementById("geoFenceName").value +
" Already Exist");
}
else {
alert("Successfully Inserted");
window.opener.location.reload();
window.close();
}
}
else
{
alert("Fail to insert");
}
}
Existing function to grab data from php:
function processtViewData(json)
{
dataJson = eval('(' + json + ')');
var totalData = dataJson.data1.length;
}
There is no equivalent to GDownloadUrl in the API V3. Loading data via AJAX is a general javascrip task that is not specific to the API or to Google Maps.
Here's a function that will do the same:
function ajaxLoad(url,callback,postData,plain) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType && plain) {
http_request.overrideMimeType('text/plain');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
eval(callback(http_request));
}
else {
alert('Request Failed: ' + http_request.status);
}
}
};
if (postData) { // POST
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.setRequestHeader("Content-length", postData.length);
http_request.send(postData);
}
else {
http_request.open('GET', url, true);
http_request.send(null);
}
}
Make sure your server responds with a content-type:text/plain header
Call it with postdsata:
var postdata = 'a=1&b=2';
ajaxLoad(serverUrl,myCallback,postdata);
function myCallback(req){
var txt = req.responseText;
// optional, if needed to evaluate JSON
eval(txt);
}
In Js file I've created a function which has to send an id and return boolean value to php file which returns false or true; but how can I do it?
JS function
function findDB(id)
{
}
PHP side
include_once("kutuphane/inc.php");
$id = $_POST['tipi'];
$sql= "select count(id) from bolge_db where parent_id=$id";
$faz2= $_SESSION["VT"]->doQuery($sql);
$flag=false;
if($faz2>0)
{
$flag= true;
}
else
{
$flag= false;
}
It's simple AJAX! Try out this code in js:
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
keep in mind that you have to echo something in php! eg: echo 1; echo 0;
Or using jQuery
var data = {
var1 : "string or another var"
};
$.post('url.php',data , function(data) {
var response = data;
//Do What Ever You Want
});
<script type="text/javascript">
function mehdi(rno)
{
alert(rno);
return rno * 10;
}
</script>
<input type="button" name ="submit" value="ثبت و تایید" onclick= " mehdi('10')">
<?php
?>
how can i use from returned value from mehdi() function?
In this case you can't since PHP is used only to render HTML.
You will have to use AJAX (AHAH) for it:
http://en.wikipedia.org/wiki/Ajax_%28programming%29
You can't! Javascript runs on the browser, after your PHP script has finished executing.
You can't PHP is processed first and then page executes javascript.
you can send Ajax request thought to your PHP scripts.
You can't do it directly. You have to use AJAX.
Once code comes to client side and it executes there, your server side script would have terminated already.
If you do need to send JavaScript return values, pass them back to server using AJAX.
you could do an ajax request within the medi function and the request could sent it via post to an file like "mehdi_js_result.php" :)
var ajaxify = function(obj) {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e) {
xmlHttp = null;
}
}
}if (xmlHttp) {
obj.method = obj.method.toUpperCase();
xmlHttp.open(obj.method, obj.url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if(obj.method == 'POST') {
if(typeof(obj.params) != 'undefined') {
xmlHttp.setRequestHeader("Content-length", obj.params.length);
}
}
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
var json = eval(xmlHttp.responseText);
if(json.success) {
if(typeof(obj.success) == 'function'){obj.success(xmlHttp.responseText);}
}
else {
if(typeof(obj.failure) == 'function') {obj.failure(xmlHttp.responseText);}
}
}
};
if(obj.method == 'POST' && typeof(obj.params) != 'undefined') {
xmlHttp.send(obj.params);
}
else {
xmlHttp.send(null);
}
}
};
function ajax(mehdi_result) {
ajaxify({
method: 'POST',
url: 'mehdi_js_result.php',
params: 'result='+result,
success: function(response) {
var json = eval(response);
alert('success callback function! '+json.data);
},
failure: function(response) {
var json = eval(response);
alert('failure callback function! '+json.data);
}
});
}