Pass value into dropzone sending option after ajax is complete - php

So I am working with dropzone, and everything uploads fine, but now I am to the part of adding the image paths to a database. What I am having a problem with is I first want to submit a form with ajax, after that successfully completes I would like to pass the newly created ID on the database into the sending option of dropzone. Everything works separately, but I can not figure out how to get the new ID into the sending option of dropzone. Here are my 2 pieces of code that are relevant.
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#dropzonePreview", {
url: "list/post-image",
parallelUploads: 6,
autoProcessQueue: false,
processing: function(){
this.options.autoProcessQueue = true;
},
sending: function(file, xhr, formData) {
formData.append("_token", $('[name=_token]').val());
}
});
and here is the ajax call. I thought I would try the myDropzone.options.sending, but I can figure out how to attach the formData like in the above code.
var form = $('form', wizard).serialize();
$.ajax({
type: "POST",
url: 'list',
data: form,
success: function(data) {
if (data.success)
{
myDropzone.options.sending(null, null, formData)
{
formData.append("propertyID", $('[name=propertyID]').val(data.propertyID));
}
}
}
});
hopefully it is just something small that I am missing. Thanks for your help in advance.

I just did some tinkering around, and some google searching and I found the answer. Instead of using the sending option, there is an option for params which makes a hidden field. Here is my ajax piece of code that got it working.
$.ajax({
type: "POST",
url: 'list',
data: form,
success: function(data) {
if (data.success)
{
myDropzone.options.params = {'propertyID': data.propertyID};
}
myDropzone.processQueue();
}
});

You have to put ur dropzone proceess queue out of the ajax succeess: like this:
Dropzone.options.dropzoneJsForm = {
autoProcessQueue: false,
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg,.pdf,.rar,.zip",
maxFilesize: 2,
maxFiles: 5,
addRemoveLinks: true,
init: function () {
var submitButton = document.querySelector("#btnReg");
myDropzone = this; //closure
submitButton.addEventListener("click", function () {
var coursenameID = $('#coursenameID').val();
var coursetypecodeID = $('#courseTypeCodeID').val();
var hdcourseexecuterID = $('#hdCourseExecuterID').val();
//var coursecreationDateID = $('#courseCreationDateID').val();
var selectedpersons = [];
$("#doublerow input:checked").each(function () { selectedpersons.push($(this).val()) });
$.ajax({
url: '#Url.Action("InsertToDB", "Course")',
type: "POST",
dataType: "json",
traditional: true,
data: { "coursenameID": coursenameID, "coursetypecodeID": coursetypecodeID, "hdcourseexecuterID": hdcourseexecuterID, "selectedpersons": selectedpersons },
beforeSend: function () {
$('#savingdata').addClass('show');
},
success: function (Response) {
console.log(Response);
if (Response > 0) {
courseid = Response;
console.log(Response);
$('#savingdata').addClass('hide');
}
}
});
myDropzone.options.params = { 'propertyID': courseid };
myDropzone.processQueue();
});
}
};

Related

After changing form to FormData in Ajax, codeigniter form validation didn't work

I wrote some code in CodeIgniter3 framework. I wrote a code that shows form validations with Ajax right after input fields. However, I added "upload image" function, for this reason, changed my ajax file from:
$(document).ready(function() {
$("#continueregistrationform").unbind('submit').bind('submit', function() {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
async : false,
cache : false,
processData : false,
dataType: 'json',
success:function(response) {
console.log(response);
if(response.success) {
$("#messages").html(response.messages);
$("#continueregistrationform")[0].reset();
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
location.href = "http://localhost/edu-center/";
}
else {
$("#messages").html(response.messages);
$.each(response.messages, function(index, value) {
var element = $("#"+index);
$(element).parent('div').find('.text-danger').remove();
$(element).after(value);
});
}
} // /success
}); // /ajax
return false;
});
});
to :
$(document).ready(function() {
$("#continueregistrationform").unbind('submit').bind('submit', function() {
var formData = new FormData($('#continueregistrationform')[0]);
$.ajax({
url: formData.attr('action'),
type: formData.attr('method'),
data: formData,
async : false,
cache : false,
contentType: false,
processData : false,
dataType: 'json',
success:function(response) {
console.log(response);
if(response.success) {
location.href = "http://localhost/edu-center/";
}
else {
$("#messages").html(response.messages);
$.each(response.messages, function(index, value) {
var element = $("#"+index);
$(element).parent('div').find('.text-danger').remove();
$(element).after(value);
});
}
} // /success
}); // /ajax
return false;
});
});
Now instead of showing errors like before under the input fields, it shows them in a new blank white page. Where can be the problem? Thanks in advance!
I would personally not use formData.attr to set the action and method. You may want to verify that the values of formData.attr('action') and formData.attr('method') are what you expect them to be.
From my own personal experience doing exactly what you're doing, this is how I added the image and post variables to the ajax request:
// Add file
var formData = new FormData();
var fileInput = $('#your_image_upload_field')[0];
var file = fileInput.files[0];
formData.append('userfile[]', file); // MUST HAVE [] OR PHP HAS NO $_FILES !!!
// Add post vars
formData.append('a', a);
formData.append('b', b);
formData.append('c', c);
// Do post
$.ajax({ //...

Pass data from ajax to laravel 5.1 Controller in order to save to mysql?

I need to pass data from jquery (version 1.9.1) to my Controller (Laravel 5.1) and then save it to mysql.
How to do that and pass the variable slot? It didn't work so far. For any further details, please asked me.
jquery:
$(".tic").click(function(){
var slot = $(this).attr('id');
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { _token: {{ csrf_token() }}, moves: slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
Controller:
public function addhistory(Request $request)
{
$history = new History();
$history->game_id = Game::orderBy('id', 'desc')->first()->id;
$history->moves = $request->moves;
$history->save();
return redirect()->back();
}
Routes:
Route::post('/addhistory', 'GameController#addhistory');
Errors in console:
(index):198 Uncaught ReferenceError: HAmcYRScL9puItnUGbd2kHx.... is not defined
at HTMLAnchorElement.<anonymous> ((index):198)
at HTMLAnchorElement.dispatch (191.js:3)
at HTMLAnchorElement.v.handle (191.js:3)
191.js file is the jquery version of 1.9.1
You can use this code, it may works
$(".tick").click(function (event) {
event.preventDefault();
$('.loading').show();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert("Data has been saved successfully.");
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
Try this code-
$(".tic").click(function(){
var slot = $(this).attr('id');
var token= $("input[name='_token']").val();
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { '_token': token, 'moves': slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
And in your controller you don't need return redirect because the request is asynchronous. So I am returning true. Make sure you include History model at the top of your controller
public function addhistory(Request $request)
{
$game_id=Game::orderBy('id', 'desc')->first()->id;
History::create([
'game_id'=>$game_id,
'moves'=>$request->moves
]);
return true;
}

jQuery GET request in loop

I have a script that works like this:
when you go to url
localhost/geocinema/index.php?movie=606
it will download the movie number 606 on my server with this script:
$.ajax({
url: link,
type: 'GET',
beforeSend: function() {
console.log("Downloading "+title);
},
complete: function() {
},
success: function(result) {
console.log("Download Success for "+title);
}
});
where the "link" is the php file that handles the download.
now I need to download movies from 1 to 600, so I need to somehow to loop through all that URL-s.
I tried sending get requests from another file, like this:
$.ajax({
url: 'http://localhost/geocinema/index.php?movie={1-600}',
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
but since I use the get request in index.php also it doesn't work (it doesn't wait until the file is downloaded).
So the only way I can download all files is if I manually enter the URL-s from 1 to 600 in the browser and wait for the download, which is not very convenient.
Any help will be appreciated, thanks.
You might want to create a queue of ajax requests, so each waits until the previous is finished. If you just initiate all ajax request in a for loop, then all of them will fire at the same time. In case we are uploading 600 videos it is going to be a very hard load. So one solution is to use for loop with ajax async flag: false.
for (var i = 1; i <= 600; i++) {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
async: false,
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
}
Another is do define a function which recursively calls itself when finished uploading.
var currentMovie = 0;
var lastMovie = 600;
function getMovie() {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie='+currentMovie,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
currentMovie++;
if (currentMoview<=lastMovie) {
getMovie();
}
},
success: function(result) {
console.log("Download Success ");
}
});
}
getMovie();
Use a for loop:
for (var i = 1; i <= 600; i++) {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
}
Do something like this, it will call the same function after completing the previous call
var i = 1;
function ajaxCall(){
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
if(i++ <= 600){ ajaxCall(); }
}
})
}
ajaxCall();
I solved it like this:
var url = window.location.href;
var ind = url.indexOf("=")+1;
var res = url.substr(ind)
res = parseInt(res);
res = res+1;
var nxurl = "http://localhost/geocinema/index.php?movie="+res;
$.ajax({
url: link,
type: 'GET',
beforeSend: function() {
console.log("Downloading "+title);
},
complete: function() {
},
success: function(result) {
console.log("Download Success for "+title);
window.location = nxurl;
}
});

Stop previous ajax when new request is made

I have a script
$('#postinput').on('keyup',function(){
var txt=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt='+txt,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
Suppose someone types a ,ajax runs . Immediately he types b c and so on. Ajax runs everytime. Is there a way to stop previous request when new is made ?
You can use the abort() method of the xhr. Try this:
var currentXhr;
$('#postinput').on('keyup',function(){
currentXhr && currentXhr.readyState != 4 && currentXhr.abort(); // clear previous request
var txt = $(this).val();
var currentXhr = $.ajax({
type: "POST",
url: "action.php",
data: 'txt=' + txt,
cache: false,
context:this,
success: function(html) {
alert(html);
}
});
});
If you don't want to use a global variable, you could store the xhr in a data-* attribute of the #postinput element.
Another method is to only fire the AJAX request when the user has stopped typing:
var timer;
$('#postinput').on('keyup',function(){
clearTimeout(timer);
var txt = $(this).val();
var timer = setTimeout(function() {
$.ajax({
type: "POST",
url: "action.php",
data: 'txt=' + txt,
cache: false,
context:this,
success: function(html) {
alert(html);
}
});
}, 100); // sends request 100ms after typing stops.
});
You can do like this with Jquery-
jaxRequests = new Array();
queueRequest = function(whatever, you, want) {
if(ajaxRequests[ajaxRequests.length - 1]) {
ajaxRequests[ajaxRequests.length - 1].abort();
}
ajaxRequests[ajaxRequests.length] = //Insert New jQuery AJAX call here.
}

Upload file via ajax jquery php api

I am having the code with the below format.
PHP file :
<form action="http://clientwebapi.com/createEvent" id="form_createEvent" method="post" enctype="multipart/form-data">
<input type="text" name="image_title" />
<input type="file" name="media" accept="image/*,video/*"/>
</form>
JQUERY file:
$('#form_createEvent').submit(function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
xhrFields: {
withCredentials: true
},
data: form.serialize()
}).done(function () {
showCurrentLocation();
alert('Event created successfully..');
location.reload();
}).fail(function () {
alert("fail!");
});
event.preventDefault();
});
The above Jquery code is submitting. Also While I am submitting the below format, It will redirect to the "http://clientwebapi.com/createEvent" and Event created successfully.
Form Submit and redirect to client page:
$('#form_createEvent').submit(function () {
var fd = new FormData();
fd.append('media', input.files[0]);
$.ajax({
url: form.attr("action"),
data: fd,
processData: false,
contentType: false,
type: form.attr("method"),
success: function (data) {
alert(data);
}
});
event.preventDefault();
});
Here How can I prevent while submit the form and create the event with the given image. Kindly help
You forgot to add event as argument to the submit function:
$('#form_createEvent').submit(function (event) {
I found the Answer for this. I made some mistake here. I resolved by using the below code..
$('#form_createEvent').submit(function() {
var form = new FormData($(this)[0]);
$.ajax({
url: 'http://clientwebapi.com/createEvent/',
type: 'POST',
xhrFields: {
withCredentials: true
},
async: false,
cache: false,
contentType: false,
processData: false,
data: form,
beforeSend: function () {
$("#output_process").html("Uploading, please wait....");
},
success: function () {
$("#output_process").html("Upload success.");
},
complete: function () {
$("#output_process").html("upload complete.");
},
error: function () {
//alert("ERROR in upload");
location.reload();
}
}).done(function() {
alert('Event created successfully..');
}).fail(function() {
alert("fail!");
});
event.preventDefault();
});
you can stop the form submission by return false;
$('#form_createEvent').submit(function () {
// some code
$.ajax({
// some code/objects
});
return false; // here, it will stop the form to be post to the url/action
});

Categories