adding fields (inputs) to images - javascript

im using dropzone to upload multiple images, and works fine, untill i want to insert a brand and url to each image.
The only issue im having is when im going to get the values from the input fields, im getting in myt request from the server undefined values from the fieds (brand, url) but if im using static text it appears no problem.
Here is my code:
$('#add').on('click',function(e){
e.preventDefault();
myDropzone.processQueue();
});
Dropzone.autoDiscover = false;
// Dropzone class:
var myDropzone = new Dropzone("div#myId", {
url: "/galleries",
autoProcessQueue:false,
headers: {
'X-CSRF-TOKEN': 'vjghjghjhgjghjghjghjgLxX',
},
params: {
'brand': $('#brand').val(),
'url' : $('#url').val(),
'description': 'small detail'
},
previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n " +
"<div class=\"dz-image\"><img data-dz-thumbnail /></div>\n " +
"<input type=\"text\" id=\"brand\" name=\"dz-brand\">\n " +
"<input type=\"text\" id=\"url\" name=\"dz-url\">\n
..../div>"
}
);

EDIT: Updated all of this answer:
Your Ids are not unique, therefore you can't reliably get the input data from the ID selector.
Change your IDs on your inputs in the template to classes like this:
previewTemplate: "<div class='dz-preview dz-file-preview'>\n " +
"<div class='dz-image'><img data-dz-thumbnail /></div>\n " +
"<input type='text' class='dz-brand' value='This is the text'> \n " +
"<input type='text' class='dz-url'>\n </div>"
Then add the parameters with the sending event, this will get the input values at the time of upload.
myDropzone.on("sending", function(file, xhr, formData) {
formData.append('brand' , $(file.previewElement).find('.dz-brand').val());
formData.append('url' , $(file.previewElement).find('.dz-url').val());
formData.append('description', 'small detail');
});
Refer to the Documentation here: http://www.dropzonejs.com/#event-sending

Related

Create a button that links to a html page for each item in database using javascript

Im trying to create buttons for each item shown in a list from my database. currently i have the list displayed using Ajax to a PHP file.
More info: Currently this code pulls and lists all questions from a SQL database. for every value in the list the code displays it in the "DOM" div class. I would like to include a button that links to advice.html for every item in the list.
HTML:
<body>
<!--output of the json-->
<div>
<!--set the id to DOM to show output-->
<div id="DOM">
</div>
</div>
insert
delete
show data
login
register
</body>
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "http://localhost/api/fetchdata.php",
type: "POST",
dataType: "json",
data: "param=no",
//on success it will call this function
success: function (data) {
var DOM = $('#DOM');
$.each(data, function (key, value) {
DOM.append("<h3>" + value.Subject + "</h3><p>" + value.Description + "</p>", $('<input type="button" href="localhost/advice.html" value="respond">')););
});
//if fail it will give this error
}, error: function (e) {
alert("failed to work");
}
});
});
</script>
I guess the line
DOM.append("<h3>" + value.Subject + "</h3><p>" + value.Description + "</p>", $('<input type="button" href="localhost/advice.html" value="respond">')););
can be replaced with
DOM.append("<h3>" + value.Subject + "</h3><p>" + value.Description + "</p>", $('<button>respond</button>')););

JavaScript call function after form submit complete

I have a hidden form created with a jquery plugin and I need to run a function after the submit has happened but it doesn't appear to be getting called.
I need to get the new csrf details after the form has been posted.
After submitting the form I want to get the newly generated csrf details
$(this).on('click', function() {
$('#' + settings.title.replace(/\s+/g, '-').toLowerCase() + '-export-csv').submit();
get_csrf_details();
});
Html link with export-csv class and data which will be used in the plugin. Using smarty template.
<a href="#" class="export-csv" data-title='Landlords' data-data='{base64_encode($landlords_json)}'>
Export (CSV)
</a>
ExportCSV plugin
(function($) {
$.fn.exportCSV = function ( options ) {
return $(this).each(function() {
var settings = $.extend({
title: null,
data: null,
link: '/',
}, options);
settings.title = $(this).data('title');
settings.data = $(this).data('data');
var hidden_form = "<form id='" + settings.title.replace(/\s+/g, '-').toLowerCase() + "-export-csv' action='" + settings.link + "' method='POST' style='display: none;'>" +
"<input type='hidden' class='csrf_field' name='" + csrfName + "' value='" + csrfHash + "'>" +
"<input type='hidden' name='title' value='" + settings.title + "'>" +
"<input type='hidden' name='data' value='" + settings.data + "'>" +
"</form>";
$(this).append(hidden_form);
$(this).on('click', function() {
$('#' + settings.title.replace(/\s+/g, '-').toLowerCase() + '-export-csv').submit();
get_csrf_details();
});
});
}
}(jQuery));
$(".export-csv").exportCSV({
link: '/dashboard/export-csv'
});
// get the csrf details from server
var get_csrf_details = function get_csrf_details() {
$.get('/ajax/get-csrf-details', function(response) {
var csrfName = response.data.csrf.name;
var csrfHash = response.data.csrf.hash;
// const csrf_input1 = document.querySelector('.csrf_field');
const csrf_inputs = document.getElementsByClassName('csrf_field');
for (i = 0; i < csrf_inputs.length; i++) {
csrf_inputs[i].name = csrfName;
csrf_inputs[i].value = csrfHash;
}
});
};
There's no way to know when a submission from a <form> element has been successfully completed.
However, given what you're doing it would make much more sense to just use AJAX. This means you can control the exact logic executed when a response is received and saves having to inject a hidden form and faking a submission, which is far from ideal. Try this:
$.fn.exportCSV = function(options) {
return $(this).each(function() {
var settings = $.extend({
title: null,
data: null,
link: '/',
}, options);
settings.title = $(this).data('title');
settings.data = $(this).data('data');
$(this).on('click', function() {
var data = {
title: settings.title,
data: settings.data
};
data[csrfName] = csrfHash;
$.ajax({
url: settings.link,
type: 'POST',
data: data,
success: function(response) {
// the submission has been made, perform required logic here.
get_csrf_details();
},
error: function() {
// something went wrong, debug it!
}
});
});
});
}
A couple of things to note. Firstly, it may make more sense to return the new CSRF in the response of the first request. This will save your network traffic.
Secondly, you're always setting settings.title and settings.data to match the data attributes on the element this function was defined on, so using a settings object is pointless as it will always be overwritten, even if no data attributes are provided. You could instead amend the logic to only use the data if they exist.

Make jquery plugin work on multiple instances

I am looking to buil a jquery plugin that will transform a link to a hidden form and fill some fields.
The form will be used to post json data to a method in the back end.
The class starts the work and I can set custom settings. The issue is when I have more than one export needed on each page the settings are only using the last iteration.
See below for more clarification.
Init the plugin with the class and add the processing link
$(".export-csv").exportCSV({
link: '{$base_url}ajax/export-csv'
});
Here I have two links for exporting data.
I pass through the title and data (smarty templating system)
<li>
<a href="#" class="export-csv"
data-title='Landlords'
data-data='{$landlords_json}'>Export Landlords (CSV)</a>
</li>
<li>
<a href="#" class="export-csv"
data-title='Buyers'
data-data='{$buyers_json}'>Export Buyers (CSV)</a>
</li>
When I click either button it will give me the buyers export as it was latest in the loop.
The forms are showing the correct data when I inspect the page. It must be the settings.title and settings.data that are getting caught.
I can see its due to the position in the loop but I am unsure how to fix this.
(function($) {
$.fn.exportCSV = function ( options ) {
var settings = $.extend({
title: null,
data: null,
link: '/',
link_text: 'Export (CSV)',
}, options);
return $(this).each( function () {
settings.title = $(this).data('title');
settings.data = JSON.stringify( $(this).data('data') );
var hidden_form = "<form id='" + settings.title.toLowerCase() + "-export-csv' action='" + settings.link + "' method='POST' style='display: none;'>" +
"<input type='hidden' name='title' value='" + settings.title + "'>" +
"<input type='hidden' name='data' value='" + settings.data + "'>" +
"</form>";
$(this).append(hidden_form);
$(this).on('click', function () {
console.log( $(this) );
event.preventDefault();
$('#' + settings.title.toLowerCase() + '-export-csv').submit();
});
});
}
}(jQuery));

I keep getting this error SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

This one is making me sick.because i cant find where i am going wrong.I will
appreciate any help or hint from you. below is my javascript code.so far the server side is fine but display the actual comment on the client side is the problem. please help me.
$(document).ready(function () {
// process the form
$('form.comments_form').each(function () {
var form_to_submit = $(this);
form_to_submit.submit(function (event) {
event.preventDefault();
var posta_id = form_to_submit.find("input[type=hidden].UNIQUE_ID").val();
var tetxarea1 = form_to_submit.find("textarea.target").val();
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'http://localhost/Forepost/php/real_time_comment.php', // the url where we want to POST
data: {
posta_id: posta_id,
tetxarea1: tetxarea1
}, // our data object
dataType: 'json', // what type of data do we expect back from the server
success: (function (response) {
display_the_comment(jQuery.parseJSON(response));
console.log(response);
}),
error: function () {
alert("oops something went wrong");
// oops something went wrong
}
});
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
function display_the_comment(response) {
var comment_string = " ";
comment_string += "<li class='indiv_cmnts'>";
comment_string += "<span class='user_fname2'>'" + response.f_name + "'</span>";
comment_string += "<div class='my_msg'>'" + esponse.my_comment + "'</div>";
comment_string += "<img class='user_proff' src='" + response.profile_img + "'/>";
comment_string += "<span class='time_cmnts'>'" + response.my_comment_date + "'</span>";
//comment_string += "<span class='fa_reply'><i class='fa fa-reply' aria-hidden='true'></i> reply</span>";
comment_string += "</li>";
$("ul.comenting2").prepend(comment_string);
}
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
});
});
});
i am trying to display the list to unordered lis with the class "comenting2"
change your code from
$("ul.comenting2").prepend(comment_string);
to
$("ul.comenting2").prepend($(comment_string));
Your response value already is an object since jquery parses it automatically (you put json as datatype). You are trying to json-parse an object, of course that has illegal characters.
Yes. To make it easier to understand the problem. I believe it would be great if you also supplied the sample of your JSON response. It is usually caused by bad JSON format.
Okay. Got your sample JSON response.
Try to change your code into:
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'http://localhost/Forepost/php/real_time_comment.php', // the url where we want to POST
data: {
posta_id: posta_id,
tetxarea1: tetxarea1
}, // our data object
dataType: 'json', // what type of data do we expect back from the server
success: (function (response) {
display_the_comment(eval('('+response+')'));
console.log(response);
}),
error: function () {
alert("oops something went wrong");
// oops something went wrong
}
});
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
function display_the_comment(response) {
var comment_string = " ";
comment_string += "<li class='indiv_cmnts'>";
comment_string += "<span class='user_fname2'>‘" + response.f_name + "’</span>";
comment_string += "<div class='my_msg'>‘" + esponse.my_comment + "’</div>";
comment_string += "<img class='user_proff' src='" + response.profile_img + "'/>";
comment_string += "<span class='time_cmnts'>‘" + response.my_comment_date + "’</span>";
//comment_string += "<span class='fa_reply'><i class='fa fa-reply' aria-hidden='true'></i> reply</span>";
comment_string += "</li>";
$("ul.comenting2").prepend(comment_string);
}
Please noted the changes at ajax success and function display_the_comment(response)

Send value from an input generated by the onSubmit callback

When i add files to the queue i generate a text input for each file.
Is it possible to send this input's value to the server side?
I tried adding the value to the params object like this:
up._options.request.params.description = id;
but it only sends the id of the last image.
var up = new qq.FineUploaderBasic({
button: document.getElementById("addFiles"),
request: {
params: {
action: "upload",
},
endpoint: config.uploadURL,
},
validation: {
allowedExtensions: ["jpg", "jpeg", "png", "gif", "mkv", "mp4"],
},
autoUpload: false,
callbacks: {
onSubmit: function(id, fileName, response) {
var element = document.createElement("li");
element.setAttribute("id", "qImage-"+id);
element.setAttribute("class", "qImage");
$(".imagesList").prepend(element);
var out = "<div class='fileInfo'>";
out += "<span id='qCancel-"+id+"'>Cancel </span>";
out += fileName;
out += "</div>";
out += "<div class='fileData'>";
out += "<label for='fileDescription'>Description</label>";
out += "<input type='text' name='fileDescription' id='fileDescription'>";
out += "</div>";
$("#qImage-"+id).html(out);
$("#qCancel-"+id).on("click", function(){
up.cancel(id);
$("#qImage-"+id).remove();
});
up._options.request.params.description = id;
},
}
});
$('#startUpload').on("click", function(){
up.uploadStoredFiles();
//document.getElementById('queue-list').innerHTML = '';
});
$('#cancelUpload').on("click", function(){
up.cancelAll();
});
To expand on Ray's comment, there are two methods to my knowledge. The first may be exclusive to the S3 implementation, but I use:
uploadSuccess: {
endpoint: "link",
params: {
key: value
}
}
Or utilize setParams if you want it sent along with the file upload request itself.

Categories

Resources