Dropzone not loading on AJAX - javascript

I have an environment where I have two forms on one page. One of them is loaded via an AJAX request and the other one exists on page load.
Now, both of them have a dropzone. Note that the IDs of the forms and dropzones are different so there is no ID conflict.
I am using Laravel 5.4 if that matters.
test.blade.php
<form id="show-edit-form" name="show-edit-form" class="form-horizontal" role="form" method="post"
enctype="multipart/form-data" action="{{url('editLocation')}}">
{{csrf_field()}}
<input type="hidden" id="location_id" name="location_id" value="{{$location->id}}">
<div class="form-group">
<div class="col-xs-12">
<div class="dropzone" id="editfiles"></div>
</div>
</div>
<div class="clearfix form-actions">
<div class="col-md-3 col-md-9">
<button class="btn btn-success btn-edit-submit" type="submit" id="edit-submit-all">
<i class="ace-icon fa fa-save fa-fw bigger-110"></i> Save changes
</button>
</div>
</div>
</form>
<div class="form-test">
</div>
javascript
jQuery(function ($) {
Dropzone.options.editfiles = {
url: 'laravel route',
...
};
$(document).on('click', '.btn-test', function () {
$.ajax({
url: "my url",
success: function(data) {
$('.form-test').html(data); // Form returned here
Dropzone.options.files = {
url: 'another laravel route',
...
};
}
});
)};
)};
The problem is that, the other dropzone which is created after an AJAX request is not rendered even though I have specified it.
Some help would be appreciated. Thanks.

So, what I did is changed the way I initialize dropzones.
Instead of this:
Dropzone.options.editfiles = {
url: 'laravel route',
...
};
I used:
var first = new Dropzone("#editfiles", {
url: 'laravel route',
...
};
And I used Dropzone.autoDiscover = false; as the first line in the jQuery function.
This seems to work.

Related

AJAX post data from cloned forms in one submit

I am posting multiple forms in one submit for a 'Refer a Friend' page. There is initially just 2 forms, one for the referrer and one for a referral. Users can 'add' more referral forms by clicking a plus sign which clone()s the referral form and append it to the container.
<div class="form-wrap">
<form id="referrer-form" role="form" action="<?=$_SERVER['REQUEST_URI'];?>" method="post" >
inputs...
</form>
<form id="first-ref" class="referral-form" role="form" action="<?=$_SERVER['REQUEST_URI'];?>" method="post">
inputs...
</form>
</div>
<div class="buttons">
<a id="plus" class="btn btn-primary" href=""></a>
<a id="minus" class="btn btn-danger" href=""></a>
<button id="submit" class="btn btn-warning btn-lg form-control">SUBMIT</button>
</div>
With my current jQuery, the 2 forms that are loaded with the page markup post just fine. However, the ones that have been clone()d are not posting. All the attributes appear the same.
// AJAX post on each form
var form = $('form');
$("#submit").click(function () {
$('#referrer', '#referrer-form').val('what is posted to leadsource field');
$(form).each(function () {
if ($(this).attr("id") != "referrer-form") {
$('#referrer', this).val('Referred by: ' + $('#referrer-form #name').val());
}
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
});
});
alert("form submitted");
$('form input').val('');
});
$("#plus").click(function () {
$("#first-ref").clone().appendTo(".form-wrap");
$(".referral-form").last().attr('id', '');
$(".referral-form").last().find('input').val('');
load_phoneMask_js();
});
$("#minus").click(function () {
$(".referral-form").last().remove();
});
</script>
jQuery's clone() has an argument in the form of .clone( [withDataAndEvents ] ), meaning if you want to keep data and events, you pass true
$("#first-ref").clone(true).appendTo(".form-wrap");
And make sure you get those forms inside the event handler
$("#submit").click(function () {
var form = $('form');
... etc

Logging in via modal using AJAX and PHP

to be fair, I'm fairly new in the AJAX area (newbie to be more precise) and i think that i took quite a large bite entering that field.So, I'm struggling for a several days now trying to implement AJAX with my PHP script. Before you flag this question as duplicate please consider that I've tried every posted question from this site and not one solution pop out. That being said, here is what I want to achieve: I want to show some sort of message after PHP script was successful or unsuccessful, something like picture below:
If there was successful show me msg, and redirect me (after 2 sec) to admin site, and if not show me error!
So, here is code for modal form:
<div class="modal fade" id="test" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">test</h4>
</div>
<div class="modal-body">
<form id="myform" method="POST" role="form">
<div class="form-group">
<label for="user">User:</label>
<input name="user" type="text" class="form-control" placeholder="Unesi korisnika">
</div>
<div class="form-group">
<label for="pass">Password:</label>
<input name="pass" type="password" class="form-control" placeholder="Unesi lozinku">
</div>
<div id="error">
<div class="alert alert-danger"> <strong>Error, try again!</strong> </div>
</div>
<div id="thanks">
<div class="alert alert-success"> <strong>Logging in..</strong></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="reset" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" id="submitForm">Login!</button>
</form>
</div>
Here is my javascript block of code: Here I tried loging in using my php script but nothing happens, it's only showing me #thanks div when I start typing
$('#test').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
$(':input', '#myform').val("");
});
$("#thanks").hide();
$("#error").hide();
$("#myform").click(function (e) {
var url = "login.php";
$.ajax({
type: "POST",
url: url,
data: $('#myform').serialize(),
success:
$("#thanks").show(),
error: function () {
$("#error").show();
}
});
e.preventDefault();
});
Here is my PHP doLogin() function inside myAuth class:
static function doLogin() {
if(
!empty($_POST['user'])
&&
!empty($_POST['pass'])
) {
if(!session_id()) session_start();
// check and retrive user with sended pass
$user = self::_fetchUserWithPassDB();
// if user found log in
if($user) {
// security
$token = md5(rand(100000,999999));
// save token in session
$_SESSION["auth"] = $token;
// save user in session
$_SESSION["user"] = $user[0]["user"];
// save role in session
$_SESSION["role"] = $user[0]["role"];
// postavi validity and token in cookie, session in base
self::_setCookieSessionDBTokenValidity();
// redirect on admin.php
header( "refresh:2;url=admin.php" );
}
else {
header('Location:index.php');
}
if(!$user) {
header("refresh:1;url=index.php" );
}
} // od if POST
and finally here is my login.php
<?php
// login.php
require_once('init.php');
myAuth::doLogin();
?>
Is it problem in in doLogin() function or is there problem with javascript, I really don't know? If there is any help, when I use this script without AJAX it works normal without any problems.
Like this:
<form action="login.php" id="myform" method="POST" role="form">
....<!--rest of the modal form-->
UPDATE 1.
I've tried something like this, but it does not work. Also, I've removed redirect from doLogin () and added in AJAX call but without any luck
$("#myform").submit(function(e) {
var url = "login.php";
$.ajax({
type: "POST",
url: url,
data: $('#myform').serialize(),
success: function() {
$("#thanks").show(), setTimeout(function() {
window.location.href = "admin.php";
}, 2000);
},
error: function() {
$("#error").show();
}
});
e.preventDefault();
});
Try moving
<form id="myform" method="POST" role="form">
outside of
<div class="modal fade" id="test" role="dialog">
i.e.
<form id="myform" method="POST" role="form">
<div class="modal fade" id="test" role="dialog">
...
</div>
</form>
Currently, your HTML is not valid (the start of <form ... lies inside <div class="modal-body"> but the end of it is after the modal-body has ended. Your browser is probably cutting off the <form at the end of modal-body to follow valid HTML.

jquery (ajax) click makes php script to run multiple times

I'm having a button, and when is clicked, it renders (with the help of ajax), the content of a php script (basically it's a contact form). My problem is that when the button is clicked, this calls the php script twice or more times. I've tried many solutions, but none worked.
HTML
<ul class="nav navbar-nav navbar-right">
<li>CONTACT</li>
</ul>
JavaScript
$(document).ready(function(){
$('#contact').off();
// the above line I've replaced it with:
// 1. $('#contact').off('click');
// 2. $('#contact').unbind();
// 3. $('#contact').unbind('click');
$('#contact').click(function(e){
$.ajax({
type: "POST",
url: "contact.php",
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
});
The response I get when I run the page which contains the HTML and JS:
The contact.php receives the data send with ajax (from index.php - the page which contains the above code), and then sends the new contact to another php script (which is a class), who stores the new contact in the database, and gives back (to contact.php) a response.
contact.php
<form id="form">
<div class="form-group col-xs-12 col-md-4">
<input type="text" class="form-control" id="nume" value="<?php echo Escape::esc($nume);?>" style="pointer-events:none;background:#EFEFEF;"/>
</div>
<div class="col-xs-12"></div>
<div class="form-group col-xs-12 col-md-4">
<input type="text" class="form-control" id="prenume" value="<?php echo Escape::esc($prenume);?>" style="pointer-events:none;background:#EFEFEF;"/>
</div>
<div class="col-xs-12"></div>
<div class="form-group col-xs-12 col-md-10">
<textarea class="form-control" id="mesaj" rows="20" data-toggle="mesaj" data-placement="bottom" title="Va rog introduceti mesajul dvs."></textarea>
</div>
<div class="col-xs-12"></div>
<div style="clear:both"></div>
<button class="btn btn-default" onclick="return validate();" style="margin-left:15px;">TRIMITE</button>
</form>
<script type="text/javascript">
function validate(){
var nume = $('#nume').val();
var prenume = $('#prenume').val();
var mesaj = $('#mesaj').val().trim();
if (mesaj == '' || mesaj.length < 3){
$(function(){
$('[data-toggle="mesaj"]').tooltip();
document.getElementById('mesaj').focus();
});
return false;
}
$('#form').off();// here I tried to unbind all the previous submit events too
$('#form').on('submit',function(e){
$.ajax({
type: "POST",
url: "../../app/classes/Contact.php",
data: {nume:nume, prenume:prenume, mesaj:mesaj},
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
}
</script>
Any tip is welcomed! Thank you!
From what I understand, JavaScript does not execute functions sequentially by nature. In your first jQuery snippet it looks like your code assumes that it will first unbind any events bound to $('#contact') and then create a new binding, but that's not necessarily true.
Also, the off() command only works if you bound the event to the element using a corresponding on() command, but your code uses click() instead of on().
You may want to try something like this instead:
$(document).ready(function(){
$('#contact').on('click', function(e){
$.ajax({
type: "POST",
url: "contact.php",
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
});
Using $('#contact').on('click', function(e) ... will allow you to call $('#contact').off() after the e.preventDefault(); if you want to try to use that to troubleshoot the double-posting problem.
I'm not sure that will fix your issue, but hopefully it's a step in the right direction.

Issues getting CasperJS to upload image to file field - tried CasperJS fill() and PhantomJS uploadFile()

I'm trying to use CasperJS to upload images to a web-form.
My form looks something like this:
<form action="" method="POST" enctype="multipart/form-data" class="form-vertical">
...
<legend>Campaign Banner</legend>
<div class="control-group image-field ">
<label class="control-label">Now Large</label>
<div class="controls">
<div class="file-field"><input id="id_now_large_image" name="now_large_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Medium</label>
<div class="controls">
<div class="file-field"><input id="id_now_medium_image" name="now_medium_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Small</label>
<div class="controls">
<div class="file-field"><input id="id_thumbnail_image" name="thumbnail_image" type="file"></div>
<div class="image-preview now-small"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
The submit button looks like this:
<div class="form-actions">
<button type="submit" class="btn btn-small ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">Save changes</span></button>
</div>
I've put a Gist of the full HTML here: https://gist.github.com/victorhooi/8277035
First, I've tried using CasperJS's fill method:
this.fill('form.form-vertical', {
'now_large_image': '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg',
}, false);
this.click(x('//*[#id="content-wrapper"]//button/span'));
I also did a this.capture(), and I saw that the file field had been filled in:
I'm not using the fill method's inbuilt submit, but I'm clicking on the submit button myself:
this.click(x('//*[#id="content-wrapper"]//button/span'));
I then do another capture, and I can see that the form has been submitted:
However, the image doesn't seem to have been uploaded at all.
I've also tried using PhantomJS's uploadFile() method:
this.page.uploadFile('input[name=now_large_image]', '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg');
and then clicking on the submit button as well.
Same issue - the form field gets filled in - however, the image itself doesn't seem to get submitted.
Any ideas on how I can get the images to upload correctly here?
Since you are filling and submitting successfully, try a Wait command on the click.
casper.then(function() {
//+++ form fill here
//waits 1 sec
this.wait(1000, function() {
this.click(x('//*[#id="content-wrapper"]//button/span'));
});
});
Try this.
casper.thenOpen('about:blank', function(){
this.evaluate(function(){
var action = 'upload.php'
var html = '<form action="'+action+'" method="post" enctype="multipart/form-data">'
html += '<input type="file" name="files[]" multiple="multiple">'
html += '<button type="submit">Submit</button>'
html += '</form>'
document.write(html)
})
this.fill('form',{
'files[]': 'file.txt'
}, true)
this.waitFor(function(){
var uri = casper.evaluate(function(){
return document.documentURI
})
if ( 'about:blank' === uri ){
return false
}
return true
})
})

How to get the form object using jquery when using twitter bootstrap

I have a model object from twitter bootstrap which is as follows
<!-- Name Edit div -->
<div id="form-content" class="modal hide fade in" tabindex="-1">
<form name="form" action="<c:url value="/editname" />" method="post">
<div class="modal-header">
<h4>Edit Name</h4>
</div>
<div class="modal-body">
<div class="control-group">
<div class="controls">
<ul class="nav nav-list">
<li class="nav-header">First Name</li>
<li><input type="text" placeholder="First Name" name="firstName" id="firstName" class="input-xlarge help-inline"></li>
<li class="nav-header">Last Name</li>
<li><input type="text" placeholder="Last Name" name="lastName" id="lastName" class="input-xlarge help-inline"></li>
</ul>
</div>
</div>
</div>
<div class="modal-footer">
<button id="submit" class="btn btn-success">Update</button>
<button class="btn" data-dismiss="modal" >Close</button>
</div>
</form>
</div>
and my ajax script is like follows:
$(function() {
//twitter bootstrap script
$("button#submit").click(function(){
var $form = $(this).closest("form").attr('id');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(msg){
$("#thanks").html(msg);
$("#form-content").modal('hide');
},
error: function(){
//alert("failure");
}
});
});
});
But the request is not firing. I checked in firebug and it looks like it's not able to get the form object and the request is not going to the controller. How can i make it work. I will have multiple forms in the same page in future.
I would suggest you use the .submit() function:
$(function() {
$('#form_id').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function(msg){
$("#thanks").html(msg);
$("#form-content").modal('hide');
},
error: function(){
//alert("failure");
}
});
});
});
Set the form id to something and change the javascript to match
You can also add a data-ajax="true"to all the forms you want to submit bia ajax and then use:
var forms = $('form[data-ajax="true"]');
forms.submit(function(e){
e.preventDefault();
// do ajax
});
<form name="form" action="<c:url value="/editname" />" method="post">
One thing is that you did not given a id for form.
var $form = $(this).closest("form").attr('id');
And if the id exist(if u adding it through code), then above $form will contain the id of the form. That is a string.
So use like this,
var $form = $(this).closest("form");
instead
var $form = $(this).closest("form").attr('id');
All HTML form input controls (input, select, button, etc) has a reference to their owner. This makes it possible to do:
var $form = $(this.form);
But I think oleron´s answer with using submit event is the correct way to do it.
Your form doesn't have an id attribute. Give it one and it might work.
so
var $form = $(this).closest("form").attr('id');
will not return a value.

Categories