I'm using formstone drag and drop file upload in my ajax powered form. using $(".uploadImage").upload("start") and $(".uploadDocs").upload("start") for initializing upload section for image and document separately after ajax function response. Each function working but I want to pass a custom variable, something like folder name to formstone and create a folder with that name and upload image and doc to that folder. how to do that?
Ajax function in which the insertion happens and return the id
$.ajax({
type: 'POST',
url: base_url + 'innovation/addProcess',
dataType: "html",
data: $('#add_innovation').serialize(),
success: function(result) {
var res = result.split("#");
if (res[0] == 'success') {
$(".uploadImage").upload("start",postData: {"ideaId":10});// sending custom value to formstone, which is not working as of now
$(".uploadDocs").upload("start",postData: {"ideaId":10});
} else {
showNotification('alert-danger', result);
}
},
error: function(error) {
console.log('error');
}
});
Formstone initialization
Formstone.Ready(function() {
$(".uploadImage").upload({
maxSize: 1073741824,
beforeSend: onBeforeSend,
autoUpload: false,
//postData: {"ideaId":50} // this is working. but don't want this here
}).on("start.upload", onStart)
.on("complete.upload", onComplete)
.on("filestart.upload", onFileStart)
.on("fileprogress.upload", onFileProgress)
.on("filecomplete.upload", onFileComplete)
.on("fileerror.upload", onFileError)
.on("queued.upload", onQueued);
$(".uploadDocs").upload({
maxSize: 1073741824,
beforeSend: onBeforeSend,
autoUpload: false,
}).on("start.upload", onStart)
.on("complete.upload", onComplete)
.on("filestart.upload", onFileStart)
.on("fileprogress.upload", onFileProgress)
.on("filecomplete.upload", onFileComplete)
.on("fileerror.upload", onFileError)
.on("queued.upload", onQueued);
});
function onCancel(e) {
console.log("Cancel");
var index = $(this).parents("li").data("index");
$(this).parents("form").find(".upload").upload("abort",
parseInt(index, 10));
}
function onCancelAll(e) {
console.log("Cancel All");
$(this).parents("form").find(".upload").upload("abort");
}
function onBeforeSend(formData, file) {
console.log(formData.get("ideaId")); // here i need the posted data. currently its not getting here
formData.append("ideaId", ideaId);
return ((file.name.indexOf(".jpg") <= -1) && (file.name.indexOf(".png") <= -1)) ? false : formData; // cancel all jpgs
}
function onQueued(e, files) {
console.log("Queued");
var html = '';
for (var i = 0; i < files.length; i++) {
html += '<li data-index="' + files[i].index + '"><span class="content"><span class="file">' + files[i].name + '</span><span class="cancel">Cancel</span><span class="progress">Queued</span></span><span class="bar"></span></li>';
}
$(this).parents("form").find(".filelist.queue")
.append(html);
}
function onStart(e, files) {
$(this).parents("form").find(".filelist.queue")
.find("li")
.find(".progress").text("Waiting");
}
function onComplete(e) {
console.log("Complete");
// All done!
}
function onFileStart(e, file) {
console.log("File Start");
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]")
.find(".progress").text("0%");
}
function onFileProgress(e, file, percent) {
console.log("File Progress");
var $file = $(this).parents("form").find(".filelist.queue").find("li[data-index=" + file.index + "]");
$file.find(".progress").text(percent + "%")
$file.find(".bar").css("width", percent + "%");
}
function onFileComplete(e, file, response) {
console.log("File Complete");
if (response.trim() === "" || response.toLowerCase().indexOf("error") > -1) {
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]").addClass("error")
.find(".progress").text(response.trim());
} else {
var $target =
$(this).parents("form").find(".filelist.queue").find("li[data-index=" + file.index + "]");
$target.find(".file").text(file.name);
$target.find(".progress").remove();
$target.find(".cancel").remove();
$target.appendTo($(this).parents("form").find(".filelist.complete"));
}
}
function onFileError(e, file, error) {
console.log("File Error");
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]").addClass("error")
.find(".progress").text("Error: " + error);
}
HTML where i used formstone control
<div class="uploadImage" style="height:100px;border:1px dashed #000;" data-upload-options='{"action":"<?php echo base_url();?>innovation/uploadImage","chunked":true}'></div>
<div class="uploadDocs" style="height:100px;border:1px dashed #000;" data-upload-options='{"action":"<?php echo base_url();?>innovation/uploadDocs","chunked":true}'></div>
Try this...
.ajax({
type: 'POST',
url: base_url + 'innovation/addProcess',
dataType: "html",
data: $('#add_innovation').serialize(),
success: function(result) {
var res = result.split("#");
if (res[0] == 'success') {
$(".uploadImage").upload("defaults", {postData: {"ideaId":10}});
$(".uploadImage").upload("start");
$(".uploadDocs").upload("defaults", {postData: {"ideaId":10}});
$(".uploadDocs").upload("start");
} else {
showNotification('alert-danger', result);
}
},
error: function(error) {
console.log('error');
}
});
Before you call the method "start" you need to add the option "postData". As what I understand from the documentation the "start" method doesn't allow additional params.
CodyKL's solution works using the defaults method, or you can append extra params with the beforeSend callback:
// Var to store ID of inserted item
var resultId;
// Insertion AJAX
$.ajax({
...
success: function(result) {
// Get the id from the result
resultId = result;
// Start the upload
$(".uploadImage").upload("start");
},
...
});
// Initialize Upload
$(".uploadImage").upload({
...
beforeSend: onBeforeSend,
...
});
// Modify upload form data
function onBeforeSend(formData, file) {
formData.append('ideaId', resultId); // add resultID obtained in insertion AJAX above to form data
return formData; // Return modified formData
}
You should read up on how JS and the FormData API work: https://developer.mozilla.org/en-US/docs/Web/API/FormData.
Related
I getting undefined value when I try to get the value of coupon from coupons table from my DB but when I get the value of percentage or price it comes correct the code is written in ajax as I am new to ajax help me solve this problem.
(function() {
var path = "{{ route('validate.coupon') }}";
$('.reserve-button').click(function() {
var coupon_number = $('.coupon-number').val();
var org_price = parseInt($('#amount').val());
//alert(coupon_number);
if (coupon_number == '') {
alert("Please Enter Coupon Number");
} else {
$.ajax({
url: path,
data: {
"coupon_number": coupon_number
},
type: 'get',
success: function(result) {
if (result.percentage == 0 && result.price == 0) {
alert('Sorry Coupon Not Exists');
} else {
$("input[name='coupon']").prop('disabled', true);
$("#btn-apply-now").remove()
var disc = org_price * (result.percentage / 100.0) + result.price;
var new_price = org_price - disc;
$('.price').html('$' + new_price);
// $('#amount').val(new_price);
$('#coupon-number').val(coupon_number);
alert('!!__ Congratulations you got ' + result.percentage + '% and ' + result.price + '$ discount __!!');
$('#price_detail').append('<li class="item clearfix"><div class="title">Discount</div><span>$' + disc + '</span></li>')
}
}
});
}
});
})();
Based on your description, you get the percentage, price from coupon code input and using ajax select the db.
What you need is return the json from sql response like this:
Press F12 -> Console log to check the result.
You can check in jsfiddle
var coupon = 'asd';
$.ajax({
url : "https://api.myjson.com/bins/95yl8",
type: "get",
dataType: 'json',
data: {coupon_code: coupon},
success: function(res)
{
console.log('all result', res);
console.log('percentage', res['data']['percentage']);
},
error:function(x,e) {
if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have a code snippet for a Queue Management System here that dynamically fetch data from the database based from the number of window allowed to be shown on the screen.
var elementArray;
function fetchPayment() {
elementArray = new Array();
$('.win_id').each(function() {
// here's the moneyshot
elementArray.push(this);
});
doAjax(0);
}
function doAjax(param) {
if (typeof elementArray[param] === 'undefined') {
var win_id = 0;
} else {
var win_id = elementArray[param].value;
}
$.ajax({
type: "GET",
dataType: 'json',
// async: false,
url: "<?php echo base_url();?>queue/getCurrentTransaction/" + win_id,
success: function(data) {
param++;
if (param <= elementArray.length) {
$('.names-' + win_id).empty();
$('.names-' + win_id).append("<div class='pname'>" + data.customer_name + '<li>' + data.ref_code + '</li></div>');
doAjax(param);
} else {
console.log("!");
}
},
error: function(data) {
param++;
$('.names-' + win_id).empty();
$('.names-' + win_id).append("<div class='pname'><li></li></div>");
doAjax(param);
}
});
}
This works, however, it's too CPU intensive and it is admittedly a bad approach, I refactored my other functions to make them something like this:
(function fetchNewServiceConnection() {
setTimeout(function() {
$.ajax({
type: "GET",
dataType: 'json',
url: "<?php echo base_url();?>queue/getCurrentTransaction/" + 100,
success: function(data) {
$('.c_name').empty();
$('.c_name').append(data.customer_name + '<li>' + data.ref_code + '</li>');
fetchNewServiceConnection()
},
error: function(data) {
$('.c_name').empty();
$('.c_name').append('<li></li>');
fetchNewServiceConnection()
}
});
}, 500);
})();
This works much much faster. The problem is the code above, how do I convert it to be like the code snippet below?
Inside your
function doAjax(param) {
if (typeof elementArray[param] === 'undefined') {
var win_id = 0;
} else {
var win_id = elementArray[param].value;
}
$.ajax({
type: "GET",
// etc....
}
you have doAjax(param); in two places, one for success: and one for error:
replace doAjax(param); in both places with:
setTimeout(doAjax.bind(null, param), 500);
Note:
I'm not sure, but it looks like you're trying to do "real time data", so my suggestion is to look at WebSockets (https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API), host your own, or, eventually, providers like Pusher.com (https://pusher.com/)
I tried to upload a file via api to server.
function uploadUsing$http(file) {
file.upload = Upload.http({
url: 'api/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'Content-Type': file.type
},
data: file
});
file.upload.then(function (response) {
file.result = response.data;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
If console.log(file), there is image data, but when i send the request to server i get an empty array.
server function:
public function uploadAPI(Request $request)
{
$image = $request->file('file');
dd($image); ---------> return []/null
return response()->json('upload hit server');
}
What's the problem here? Thanks!!
Have you tried using
Upload.upload({
url: 'upload/url',
data: {file: file, 'param1': $scope.param1}
});
Instead?
i am new to Jquery/Ajax and i am trying to have the source url for the json change based on the url parameters i setup, i have working version in PHP, but i don't know how to write it in JQuery
This is my PHP Code (what i am currently using
$id = urlencode($_GET['id']);
$page = urlencode($_GET['results']);
$url = "https://gdata.youtube.com/feeds/api/playlists/$id?alt=jsonc&v=2&max-results=25&&start-index={$results}";
This code grabs the id and includes it to alter the url of the source file used in the script
so how would i make this code act in the same way?
$(document).ready(function() {
startindex = 1;
loadmore = 20;
addMore(startindex, loadmore);
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore($('#list li').length, 20);
});
});
function addMore(startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/ID_WOULD_GO_HERE?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
Please help, Thanks!
Please try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="list"></div>
<script>
$(document).ready(function() {
startindex = 1;
loadmore = 20;
id = urlVar("id");
if (id!="") {
addMore(id, startindex, loadmore);
}
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore(id, $('#list li').size(), 20);
});
});
function urlVar(varName) {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars[varName]?vars[varName]:"";
}
function addMore(id, startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/"+ id +"?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
console.log(data);
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
</script>
To test: this_script.php?id=RD029cW4vF6U2Dc
Potentially you could also get PHP to put the variable into the URL before hand.
Example:
src = "https://gdata.youtube.com/feeds/api/playlists/<?php echo $_GET['id'];?>?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
I am trying to go through this sample https://github.com/blackberry/BB10-WebWorks-Samples/blob/master/Twitter-OAuth-1/README.md
Although, I keep getting the following error:
Error in getAuthorization: ReferenceError:Can't find variable: facebookOptions
Here is my code for my javascript OAuth.js
function initApp() {
try {
// facebook oauth setup
facebookOptions = {
clientId: '############',
clientSecret: '######################',
// we use a php script on a server because facebook doesn't allow for local:/// callbacks
// at this time. the php simply redirects us back to 'local:///index.html'
redirectUri: 'http://###########.com/redirect.php'
};
// here we check for query strings in window.location when the app loads. This is because facebook is calling back
// to our callbackUrl. When the app initializes, and there is a query string, it checks if the user
// authorized the app or not
var query = window.location.search;
authCode = null;
authCode = query.split('code=');
authCode = authCode[1] || null;
// we've got an auth code, let's exchange that for an access token
if (authCode !== null) {
getAccessToken();
}
} catch (e) {
alert('Error in initApp: ' + e);
}
}
// first, we get the user to authorize with the service and allow our app access
function getAuthorization() {
try {
showMessage('Contacting Facebook...');
window.location.replace('https://www.facebook.com/dialog/oauth?client_id=' + facebookOptions.clientId + '&redirect_uri=' + facebookOptions.redirectUri + '&scope=publish_stream,read_stream');
} catch (e) {
alert('Error in getAuthorization: ' + e);
}
}
// exchange our 'access code' for an 'access_token'
function getAccessToken() {
try {
var url = 'https://graph.facebook.com/oauth/access_token?client_id=' + facebookOptions.clientId + '&redirect_uri=' + facebookOptions.redirectUri + '&client_secret=' + facebookOptions.clientSecret + '&code=' + authCode;
$.ajax({
type: 'GET',
url: url,
success: function(data) {
var response = data;
// parse 'access_token' from the response
response = response.split('&');
accessToken = response[0].split('=');
accessToken = accessToken[1];
// get authenticated users' info for future use
getUserInfo();
},
error: function(data) {
alert('Error getting access_token: ' + data.responseText);
return false;
}
});
} catch (e) {
alert('Error in getAccessToken: ' + e);
}
}
// get users info (we're grabbing their full name for this sample)
function getUserInfo() {
try {
var url = 'https://graph.facebook.com/me?access_token=' + accessToken;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
// data.name = users full name
showMessage('Hello ' + data.name + '!');
$('#buttonSetup').hide();
$('#afterAuth').show();
},
error: function(data) {
alert('Error getting users info: ' + data.responseText);
return false;
}
});
} catch (e) {
alert('Error in getUserInfo: ' + e);
}
}
// update the users status
function postToService() {
try {
var status = $('#inputBox').val();
if (status === '' || status === 'enter your status...') {
showMessage('You didn\'t enter anything to post :(');
return false;
} else {
showMessage('Updating status...');
var url = 'https://graph.facebook.com/me/feed?message=' + status + '&access_token=' + accessToken;
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
success: function(data) {
showMessage('Status updated!!');
$('#inputBox').val('enter your status...');
// display the updated news feed to the user
setTimeout(function() {
getFeed();
}, 200);
},
error: function(data) {
alert('Error updating status: ' + data.responseText);
return false;
}
});
}
} catch (e) {
alert('Error in postToService: ' + e);
}
}
// get users news feed
function getFeed() {
try {
showMessage('Getting news feed...');
var url = 'https://graph.facebook.com/me/feed?access_token=' + accessToken;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
showMessage('Your news feed...');
var feed = data.data;
// clear the content div, and prepare to add new data to it
$('#content p').remove();
// show the last 4 items from the users news feed
// note: there are several objects that could be posted in a news feed. for simplicity
// we're only showing objects with a 'story' attribute
for (var i = 0; $('#content p').size() < 4; i++) {
if (typeof feed[i].story !== 'undefined') {
$('#content').append('<p>' + feed[i].story + '</p>');
}
}
// display the feed, after it's been parsed
$('#content').fadeIn();
},
error: function(data) {
alert('Error loading news feed: ' + data.responseText);
return false;
}
});
} catch (e) {
alert('Error in getFeed: ' + e);
}
}
// helper function for displaying a message to the user
function showMessage(msg) {
try {
if (!$('#message').is(':visible')) {
$('#message').show();
}
setTimeout(function() {
$('#message').html(msg);
}, 500);
setTimeout(function() {
$('#message').fadeOut(500, function() {
$('#message').html('');
});
}, 8000);
} catch (e) {
alert('Error in showMessage: ' + e);
}
}
the php redirect file on my web server is this:
<?php
$queryString = $_SERVER['QUERY_STRING'];
header("location: local:///index.html" . $queryString);
?>
I am not sure whether the problem is with the authorization in oauth.js or in the local redirect php file.
I have just updates all the OAuth samples to work in the newest SDK.
Get the updated sample from: https://github.com/blackberry/BB10-WebWorks-Samples
The problem is that the initApp function wasn't being executed. This is because the webworksready event wasn't being fired. Now that the samples have been update to reflect the new way of including the webworks.js file, this should no longer be an issue.