function uploadToServer(){
fileField = document.getElementById("uploadedFile");
var fileToUpload = fileField.files[0];
var xhr = new XMLHttpRequest();
var uploadStatus = xhr.upload;
uploadStatus.addEventListener("progress", function (ev) {
if (ev.lengthComputable) {
$("#uploadPercentage").html((ev.loaded / ev.total) * 100 + "%");
}
}, false);
uploadStatus.addEventListener("error", function (ev) {$("#error").html(ev)}, false);
uploadStatus.addEventListener("load", function (ev) {$("#error").html("sorry!")}, false);
xhr.open(
"POST",
"serverUpload.php",
true
);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", fileToUpload.fileName);
xhr.setRequestHeader("X-File-Size", fileToUpload.fileSize);
xhr.setRequestHeader("X-File-Type", fileToUpload.type);
//xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(fileToUpload);
}
$(function(){
$("#uploadButton").click(uploadToServer);
});
`
<form action="" name="uploadForm" method="post" enctype="multipart/form-data">
hi this code is working fine. but i need increase div size. but this one only showing percentage only. what i have to change to get dat one.
bellow is simple progressbar code using HTML5
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<span id="status"></span>
<h1 id="finalMessage"></h1>
<script type="text/javascript" language="javascript">
function progressBarSim(al) {
var bar = document.getElementById('progressBar');
var status = document.getElementById('status');
status.innerHTML = al+"%";
bar.value = al;
al++;
var sim = setTimeout("progressBarSim("+al+")",300);
if(al == 100){
status.innerHTML = "100%";
bar.value = 100;
clearTimeout(sim);
var finalMessage = document.getElementById('finalMessage');
finalMessage.innerHTML = "Process is complete";
}
}
var amountLoaded = 0;
progressBarSim(amountLoaded);
</script>
it may help you, fix this code in your coding.
Related
I have this code in Ajax but I want this to work in Wordpress. I just want to make a product filter in Ajax that will work in WordPress. I am just new to this. Any help and idea please?
<script>
$(document).ready(function(){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var brand = get_filter('brand');
var ram = get_filter('ram');
var storage = get_filter('storage');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
success:function(data){
$('.filter_data').html(data);
}
});
}
add_action( 'wp_ajax_action', 'filter_data' );
add_action( 'wp_ajax_action', 'filter_data' );
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
$('#price_range').slider({
range:true,
min:1000,
max:65000,
values:[1000, 65000],
step:500,
stop:function(event, ui)
{
$('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
$('#hidden_minimum_price').val(ui.values[0]);
$('#hidden_maximum_price').val(ui.values[1]);
filter_data();
}
});
});
</script>
How can I make an ajax call in wordpress without use of plugin?
Ajax code
<script type="text/javascript">
function filter_data(){
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var brand = get_filter('brand');
var ram = get_filter('ram');
var storage = get_filter('storage');
var data = {
action:action, minimum_price:minimum_price,
maximum_price:maximum_price, brand:brand, ram:ram,
storage:storage
};
$.post('/wp-admin/admin-ajax.php',data,function(response){
$('.filter_data').html(data);
});
}
</script>
In you function.php file
add_action('wp_ajax_fetch_data','filter_data'); // for loggedin user
add_action('wp_ajax_nopriv_fetch_data', 'filter_data'); // for non loggedin user
function filter_data()
{
$minimum_price = $_POST['minimum_price'];
$maximum_price = $_POST['maximum_price'];
$brand= $_POST['brand'];
$ram= $_POST['ram'];
$storage= $_POST['storage'];
// here your product filter code
}
I'm using ReactJS(Flux) and Laravel framework. I need to pass a variable from blade template to React components. I'm trying to use data-x attribute.
My question are..
How can I get the data in React(or Flux architecture)?
Do you have the best practice to store the data in Flux. Is app.js the best place to do it?
Thanks,
index.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ReactJS</title>
</head>
<body>
<section id="react" data-domain="{{env("DOMAIN")}}"></section>
<script src="{{ elixir('js/bundle.js') }}"></script>
</body>
</html>
/app.js
var React = require('react');
var SampleApp = require('./components/SampleApp.react');
React.render(
<SampleApp />,
document.getElementById('react')
);
/components/SampleApp.react
var React = require('react');
var SampleApp = React.createClass({
render: function() {
return (
<div>
Hello
</div>
);
}
});
module.exports = SampleApp;
===================================================
Edit 1
I could pass data by using {this.props.domain}. Next step is how to store the data as Flux way.
/app.js
var React = require('react');
var SampleApp = require('./components/SampleApp.react');
var react = document.getElementById('react');
React.render(
<SampleApp domain={react.dataset.domain}/>,
react
);
/components/SampleApp.react
var React = require('react');
var SampleApp = React.createClass({
render: function() {
return (
<div>
Hello {this.props.domain}
</div>
);
}
});
module.exports = SampleApp;
===================================================
Edit 2
Fixed
/index.blade.php
/app.js
/components/SampleApp.react.js
/actions/SampleActionCreators.js
/constans/SampleConstants.js
/dispatcher/SampleAppDispatcher.js
/stores/SampleStore.js
index.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ReactJS</title>
</head>
<body>
<section id="react" data-domain="test.example.com"></section>
<script src="{{ elixir('js/bundle.js') }}"></script>
</body>
</html>
/app.js
var React = require('react');
var SampleApp = require('./components/SampleApp.react');
React.render(
<SampleApp />,
document.getElementById('react')
);
/components/SampleApp.react.js
var React = require('react');
var SampleActionCreators = require('../actions/SampleActionCreators');
var SampleStore = require('../stores/SampleStore');
function getSampleState() {
return {
domain: SampleStore.getDomain()
};
}
var SampleApp = React.createClass({
getInitialState: function() {
return getSampleState();
},
componentDidMount: function() {
SampleStore.addChangeListener(this._onChange);
var domain = document.querySelector('#react').dataset.domain;
SampleActionCreators.initData(domain);
},
componentWillUnmount: function() {
SampleStore.removeChangeListener(this._onChange);
},
render: function() {
return (
<div>
Hello {this.state.domain}
</div>
);
},
_onChange: function() {
this.setState(getSampleState());
}
});
module.exports = SampleApp;
/actions/SampleActionCreators.js
var SampleAppDispatcher = require('../dispatcher/SampleAppDispatcher');
var SampleConstants = require('../constants/SampleConstants');
var ActionTypes = SampleConstants.ActionTypes;
module.exports = {
initData: function(domain) {
SampleAppDispatcher.dispatch({
type: ActionTypes.SAMPLE_INIT_DATA,
domain: domain
});
},
};
/constans/SampleConstants.js
var keyMirror = require('keymirror');
module.exports = keyMirror({
ActionTypes: keyMirror({
SAMPLE_INIT_DATA: null
})
});
/dispatcher/SampleAppDispatcher.js
var Dispatcher = require('flux').Dispatcher;
module.exports = new Dispatcher();
/stores/SampleStore.js
var SampleAppDispatcher = require('../dispatcher/SampleAppDispatcher');
var SampleConstants = require('../constants/SampleConstants');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var CHANGE_EVENT = "change";
var _domain = "";
var SampleStore = assign({}, EventEmitter.prototype, {
getDomain: function() {
return _domain;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
});
SampleAppDispatcher.register(function(action) {
switch (action.actionType) {
case SampleConstants.SAMPLE_INIT_DATA:
_domain = action.domain;
SampleStore.emitChange();
break;
default:
// no op
}
});
module.exports = SampleStore;
Your second edit is "correct" Flux way, same one I used on several large scale projects.
More simpler, alternative approach would be to get domain in app.js and pass it to your SampleApp as prop. This requires for DOM from your blade template to be loaded before JS executes. Since you are already putting your JS on bottom you should be good but I added window.onload event just to make it sure.
var React = require('react');
var SampleApp = require('./components/SampleApp.react');
function getDomain() {
return document.getElementById('react').dataset.domain;
}
function initReact() {
var params = {
domain: getDomain()
};
React.render(
<SampleApp {...params} />,
document.getElementById('react')
);
}
window.onload = function() {
initReact();
};
Now you can use {this.props.domain} to access your domain value in SampleApp.reatc.js
I am facing problem here as in phonegap image is uploaded to the server once u select a picture.I don't want to upload image before submitting form. Image is uploaded automatically to server which is something i don't want.I want to upload image with the form, where form contains many more fields which is required to send along with image. What are the possible ways to submit with form?
<!DOCTYPE HTML >
<html>
<head>
<title>Registration Form</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// Do cool things here...
}
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://yourdomain.com/upload.php", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
</script>
</head>
<body>
<form id="regform">
<button onclick="getImage();">select Avatar<button>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="text" id="workPlace" name="workPlace" class="" />
<input type="submit" id="btnSubmit" value="Submit" />
</form>
</body>
</html>
Create two functions you can call separately. One function for just getting the image, and another function to upload the image.
You can do something like below.
<!DOCTYPE html>
<html>
<head>
<title>Submit form</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Show the selected image
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageURI;
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function uploadPhoto() {
//selected photo URI is in the src attribute (we set this on getPhoto)
var imageURI = document.getElementById('smallImage').getAttribute("src");
if (!imageURI) {
alert('Please select an image first.');
return;
}
//set upload options
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.params = {
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value,
workplace: document.getElementById("workplace").value
}
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
}
// Called if something bad happens.
//
function onFail(message) {
console.log('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert("Response =" + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>
</head>
<body>
<form id="regform">
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Select Photo:</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
First Name: <input type="text" id="firstname" name="firstname"><br>
Last Name: <input type="text" id="lastname" name="lastname"><br>
Work Place: <input type="text" id="workplace" name="workPlace"><br>
<input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();">
</form>
</body>
</html>
You're already sending custom fields in your example.
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
Just populate params with your form fields.
I also faced same problem, but I have done using two server side calls on one click. In this, in first call submit data and get its id in callback using JSON then upload image using this id. On server side updated data and image using this id.
$('#btn_Submit').on('click',function(event) {
event.preventDefault();
if(event.handled !== true)
{
var ajax_call = serviceURL;
var str = $('#frm_id').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: str,
dataType: "json",
success: function(response){
//console.log(JSON.stringify(response))
$.each(response, function(key, value) {
if(value.Id){
if($('#vImage').attr('src')){
var imagefile = imageURI;
$('#vImage').attr('src', imagefile);
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url+'&Id='+Id+'&mode=upload', win, fail, options);
/* Image Upload End */
}
}
});
}
}).done(function() {
$.mobile.hidePageLoadingMsg();
})
event.handled = true;
}
return false;
});
On server side using PHP
if($_GET['type'] != "upload"){
// Add insert logic code
}else if($_GET['type'] == "upload"){
// Add logic for image
if(!empty($_FILES['vImage']) ){
// Copy image code and update data
}
}
I could not get these plugins to upload a file with the other answers.
The problem seemed to stem from the FileTransfer plugin, which states:
fileURL: Filesystem URL representing the file on the device or a data URI.
But that did not appear to work properly for me. Instead I needed to use the File plugin to create a temporary file using the data uri to get me a blob object: in their example, writeFile is a function which takes a fileEntry (returned by createFile) and dataObj (blob). Once the file is written, its path can be retrieved and passed to the FileTransfer instance. Seems like an awful lot of work, but at least it's now uploading.
This is my first time working with AJAX, and I cant seem to figure out WHY the .txt file will NOT load? but instead goes to a new page with just that text displayed) ie: not loading in the same page:
my index.html page:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<script src="js/main.js"></script>
</body>
</html>
here is my main.js script:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onClick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.readystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
};
};
})();
alert(message);
in my ajax.txt file.. I just have some random plain text: This is Ajax text to be loaded.
I am NOT running this locally, but through localhost using WAMP web server..
What am I missing? or overlooking here?
Tutorial link: tutsplus.com/lesson/the-simplest-ajax-script
to solve your problem:
Make this replacement to your code:
onClick -> onclick (js is case sensitive)
readystatechange -> onreadystatechange
then put this piece of code out of the onreadystatechange function:
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
This is the new main.js:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onclick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.onreadystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
return false;
};
//open the request
xhr.open("GET", "files/ajax.txt?aiai", true);
//send the request
xhr.send(null);
return false;
};
})();
alert(message);
I think its easier to do it like that:
first, HTML:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<div id="textFiles"><!-- files display here --></div>
</body>
</html>
JS:
<script>
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function loadText() {
var message = "Test";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("textFiles").innerHTML = xmlhttp.responseText;
alert(message);
}
else{
document.getElementById("textFiles").innerHTML = "Loading Files...";
}
};
xmlhttp.open("POST",'files/ajax.txt',true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
Is there any way to reload the same image using mootools. I have a camera that gives me image, but I have to refresh it. I wrote this, but it doesn't work so well:
var url = "some valid url to some image.jpg";
var timer = 10;
var periodical;
var camera_container;
var refresh = (function() {
var loader = new Asset.image(url, {
onLoad : function() {
camera_container.empty();
camera_container.inject(loader);
}
});
});
window.addEvent('domready', function() {
// the periodical starts here, the * 1000 is because milliseconds required
refresh.periodical(timer * 1000, this);
camera_container = $('camera-image');
});
Any help appreciated. Thanks.
why not add a seeding bit to the url?
(function() {
var url = "some valid url to some image.jpg?";
this.timer = 10;
var counter = 0;
this.refresh = (function() {
var loader = new Asset.image(url + counter, {
onLoad: function() {
camera_container.empty();
camera_container.inject(loader);
counter++;
}
});
});
})();
window.addEvent('domready', function() {
// the periodical starts here, the * 1000 is because milliseconds required
refresh.periodical(timer * 1000, this);
this.camera_container = $('camera-image');
});
this way the url will always be path/image.jpg?n where n changes and will force the browser to re-fetch it.
I think something like this also can work:
<div id="image-holder">
<img src="http://www.image.com/image.jpg"/>
</div>
var srcImage = 'http://www.image.com/image.jpg';
var reloadTime = 4000;
var holder = document.id('image-holder');
var imageReload = function(){
holder.empty();
var newImage = new Element('img',{
id:'image',
src:srcImage ,
alt:'image new'
}).inject(holder);
}
var start = function() {
interval = imageReload.periodical(reloadTime);
};
start();