Success not being called on ajax upload - javascript

My script is an upload page which has a progress bar.
The file is uploading correctly to the server and the progress bar is working.
The on success isn't being executed though and I have no idea why.
The console has no errors and the xhr response is "file moved do logic" so why isn't the success being called?
<script type="text/javascript">
$(document).ready(function() {
$('#progressbar').progress();
$('#uploadForm').submit(function(e) {
//return Validate();
var ext = $('#userImage').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg','pdf']) == -1) {
alert('We only acccept PNG, JPG, JPEG, GIF or PDF files');
return false;
}
if($('#userImage').val()) {
e.preventDefault();
//$('#loader-icon').show();
$(this).ajaxSubmit({
target: '#targetLayer',
beforeSubmit: function()
{
$("#progress-bar").width('0%');
},
uploadProgress: function (event, position, total, percentComplete){
$('#progressbar').progress({
percent: percentComplete
});
$('#progresslabel').html(percentComplete + '% Uploaded')
},
success:function (data){
alert (data);
},
resetForm: true
});
return false;
}
});
});
</script>
<div class="ui page grid">
<div class="fifteen wide column">
<div class="ui segment">
<div class="upload">
<h3>Upload <?php echo $pdf['UPLOADTITLE']; ?></h3>
<form name="uploadform" id="uploadForm" action="upload.php" method="post">
<div>
<label>Upload Image File:</label>
<input name="userImage" id="userImage" type="file" class="demoInputBox" />
</div>
<div>
<input type="submit" id="btnSubmit" value="Submit" class="btnSubmit" />
</div>
<input type="hidden" value="<?php echo $pdf['UPLOADSTUDENT']?>" name="studentid">
<input type="hidden" value="<?php echo $pdf['UPLOADTITLE'] ?>" name="filetype">
<input type="hidden" value="<?php echo $pdf['UPLOADID']; ?>" name="uploadid">
</form>
</div>
<div class="ui teal progress" id="progressbar">
<div class="bar"></div>
<div class="label" id="progresslabel">0% Uploaded</div>
</div>
</div>
</div>
</div>

The problem was with :
target: '#targetLayer',
As soon as I removed this the onSuccess was called.

Related

Unique comment section per dynamic modal

I have a webpage with dynamically loaded cards that pop up into individual modals to display more data. These modals all have their unique id in order to pop up the correct one.
I am attempting to put a unique comment section for each modal. What I have implemented works only for the first modal & doesnt even show the comments on the second modal onwards.
I would appreciate some direction in how to make them display per modal & how to make them unique. I am assuming I echo $test[id] just like I used for the modals. Need a little assistance in script side of things.
<div id="myModal<?php echo $test['id']; ?>" class="modal">
<div class="modal-content">
<div class="container">
<form method="POST" id="comment_form">
<input type="hidden" id="id" name="id" value="<?php echo $test['id']; ?>">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment<?php echo $test['id']; ?>"></div>
</div>
</div>
</div>
<script>
var data = 1;
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
UPDATE:
Going with the response received, I made certain changes & noticed that even though the comment form is visible on all modals, the posted comments itself
only appear on the first modal. With a bit of hardcoding I am able to tell that the display_comment(id) in html & script needs to be same. The HTML id updates as per console, but I am unable to pass the correct id to $('#display_comment'+myData1).html(data); (it is always 1).
<div id="myModal<?php echo $test['id']; ?>" class="modal">
<div class="modal-content">
<div class="container">
<form method="POST" id="comment_form">
<input type="hidden" id="id" name="id" value="<?php echo $test['id']; ?>">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment<?php echo $test['id']; ?>"></div>
</div>
<div id="dom-target" style="display: none;" data-id="<?php echo htmlspecialchars($test['id']);?>">
<?php
echo htmlspecialchars($test['id']);
?>
</div>
</div>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
var myData1 = $("#dom-target").data("id");
console.log('#display_comment'+myData1);
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment'+myData1).html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
I have also tried the following & simply receive undefined as the value in console for myData2:
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {
myData2: $("#dom-target").data("id")
},
you should loop all the content according to your $test['id'].
each loop will generate each $test['id'], modals, form.
therefore, you will have multiple form according to each modals.
regarding the name of the input box (name="comment_id","comment_name" etc), just use the same name, as this will affect your backend on how you will process those input ($_POST['']).
this shouldn't be an issue if you area using same input name as user can only submit 1 form on each request.
just the value will be changing based on the form.

AJAX call PHP same page and reload option values

i have an html form with a date input and a multiselect.
When loading page I load the options of the multiselect through a php function.
What i want to do is to capture onChange event of the date input with a js script and launch the php script to reload the option values of the select using the new date.
This is the php code
<?php
//DEFINE
$dateMinimumInput = "";
// Handle AJAX request for changing DateMinimumInput(start)
if(isset($_POST['ajax']) && isset($_POST["dateMinimumChanged"]) ){
echo "Inside function dateMinimumChanged: " .$_POST['dateMinimumChanged'];
$dateMinimumInput = verify_input($_POST['dateMinimumChanged']);
}
$stationList = selectStations($dateMinimumInput); ?>
This is the javascript
<script>
$(document).ready(function(){
$("#dateMinimumInput").change(function(){
//Selected value
inputValue = $(this).val();
console.log(inputValue);
$.ajax({
type: 'POST',
url: '',
data: {ajax: 1, dateMinimumChanged: inputValue},
success: function(data){
console.log('works');
console.log(data);
$('body').append(response);
},
error: function(){
alert('something went wrong');
}
});
});
});
</script>
and this is the html form
<form class="" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="dateMinimumInput" class="col-form-label col-sm-4">Date Minimum:</label>
<div class="col-sm-8">
<div class="form-group">
<input type="date" class="form-control <?php if ( $dateMinimumInputErr !== "") { echo 'is-invalid'; }?>" id="dateMinimumInput" name="dateMinimumInput" placeholder="Enter date minimum" value="<?php echo $dateMinimumInput;?>">
<div class="invalid-feedback"> <?php if ( $dateMinimumInputErr !== "") { echo 'Please, ' .$dateMinimumInputErr; } ?> </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="stationInput" class="col-form-label col-sm-4">Station:</label>
<div class="col-sm-8">
<select id="stationInput" name="stationInput[]" class="form-control" multiple>
<?php
foreach($stationList as $station){
if($station['numberofmeasurements'] == 0){
echo '<option disabled="true" value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}else{
echo '<option value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
The fragments of code are all from the same page.
The problem is that when I change the date, the javascript captures the event but the PHP script is not executed and the options are not reload.
Any help about what I'm doing wrong?
Thank you

jquery onclick function not defined

I have an ajax script and I am trying to post from a function. I am using a onlick href but its not coming up as undefined. This is using wordpress. I have tried to move the code around inside and outside the scope but I still cant seem to get it to work.
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name"/>
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>"/>
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
Submit Comment
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function(){
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/get_chat.php"
}).done(function(html){
$('#displayComments').html(html);
});
}, 2000);
function submitComment(){
$.ajax({
method: "POST",
url: "template-live.php",
data: {submitComment:$('#chatBox').val(),submitName:$('#nameBox').val(),submitEmail:$('#emailBox').val()}
}).done(function(html){
alert('Your comment has been submitted, and will be displayed after approval.');
$('#chatBox').val('');
});
}
});
</script>
Thank you :)
When you do javascript:submitComment() that's calling a the global function submitComment. Since the submitComment is defined in the jQuery(function($) { ... }) function, it is not a global. Therefore, window.submitComment is undefined (hence undefined is not a function).
The globals are stored in the window object.
Therefore, you can expose that submitComment as a global:
window.submitComment = function () {...}
Note that you should avoid using globals as much as possible. In this case you can do that by adding:
$("#submit").click(submitComment);
// In this case, you shouldn't declare submitComment as a global anymore
And since you are in a form, you want to stop the default browser behavior when clicking the a element, by using return false at the end of the function.
Alternatively to #Ionică Bizău's solution.
You could use onclick="submitComment()" instead of href.
<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name" />
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>" />
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function() {
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/get_chat.php"
}).done(function(html) {
$('#displayComments').html(html);
});
}, 2000);
window.submitComment = function(){
console.log('submitComment called!');
$.ajax({
method: "POST",
url: "template-live.php",
data: {
submitComment: $('#chatBox').val(),
submitName: $('#nameBox').val(),
submitEmail: $('#emailBox').val()
}
}).done(function(html) {
alert('Your comment has been submitted, and will be displayed after approval.');
$('#chatBox').val('');
});
}
});
</script>

Ajax success function not working on the second time

Aim: Continue to display any form validation errors through json callback
Problem: When I submit on the form with invalid input it shows an error message in a div element. If all inputs are valid it will process the ajax request and show a success message in a div element. After which, the form resets but the modal remain open. When I try to again validate the input in doesn't show any error message. When I try to test the valid input still the same no message shown.
In short: Ajax success function not working on the second time.
Here's my code:
Bootstrap Modal (where my form inputs placed)
<div class="modal fade" id='frmModal'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class='close' data-dismiss='modal'>×</button>
<h4 class='title'>Add new data</h4>
</div>
<div class="modal-body">
<?php echo form_open('Employee/save',array('id'=>'frm', 'class'=>'form-horizontal')); ?>
<div id="message"></div>
<div class="form-group">
<label for='fname' class='col-md-3 control-label'>First Name:</label>
<div class="col-md-9">
<input type="text" name="fname" id='fname' class='form-control' placeholder='First Name...'>
</div>
</div>
<div class='form-group'>
<label for='lname' class='col-md-3 control-label'>Last Name:</label>
<div class="col-md-9">
<input type="text" name="lname" id='lname' class='form-control' placeholder='Last Name...'>
</div>
</div>
<div class='form-group'>
<label for='age' class='col-md-3 control-label'>Age:</label>
<div class="col-md-9">
<input type="text" name="age" id='age' class='form-control' placeholder='Age...'>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary action" type='submit'><i class='glyphicon glyphicon-floppy-disk'></i> Save Data</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).on('submit','#frm',function(e){
e.preventDefault();
var form = $('#frm');
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
encode: true,
data: form.serialize(),
success: function(data) {
if (!data.success) {
if (data.errors) {
$('#message').html(data.errors).addClass('alert alert-danger');
}
} else {
reloadData();
$('#message').html("<span class='glyphicon glyphicon-ok'></span> " + data.message).removeClass('alert alert-danger').addClass('alert alert-success');
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
$('#frm')[0].reset();
}
}
});
});
CodeIgniter Controller:
$this->form_validation->set_rules('fname','First Name', 'required|trim');
$this->form_validation->set_rules('lname','Last Name', 'trim|required');
$this->form_validation->set_rules('age','Age', 'trim|numeric|required');
if($this->form_validation->run()===FALSE)
{
$info['success'] = false;
$info['errors'] = validation_errors();
}
else
{
$info['success'] = true;
$data = array(
"firstname" => $this->input->post('fname'),
"lastname" => $this->input->post('lname'),
"age" => $this->input->post('age'),
);
$this->Employee_model->save('ci_table', $data);
$info['message'] = 'Successfully saved data';
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
I think I understand... The form still works but the messages do not appear? If so then try the below...
You are removing the #message element instead of clearing it... try:
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).empty();
This way you are emptying the #message element instead of removing it completely..

Using jQuery AJAX and PHP to create a progress bar for file uploading

First off I want everyone to understand I did look at all of the other examples on stackoverflow, but none have worked for me at all. What I want to do is create a progress bar which shows the how much of the file has been uploaded out of 100%. I have 3 scripts: upload.php which houses the form, fileUpload.php which is script for uploading the file, and script.js which holds the jQuery AJAX code.
Nothing seems to work. With the code I have below, the Ajax returns a success message, however the progress bar doesn't change, nothing is uploaded to the folder and the file itself remains in the file input. The problem lies within the ajax code inside script.js since I can upload a file without the ajax code.
/* upload.php
--------------------------------------------------------*/
<div class="form-wrapper">
<form method="post" id="uploadForm" action="fileUpload.php" role="form" enctype="multipart/form-data">
<legend>Upload</legend>
<div class="form-group">
<label for="fileUpload">File</label>
<input type="file" id="fileUpload" name="fileUpload"/>
</div>
<button type="submit" id="uploadBtn" class="btn btn-success">Submit</button>
</form>
<br>
<div id="progress" class="progress">
<div id="progress-bar" class="progress-bar progress-bar-striped active" role="progressbar"
aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
</div>
</div>
<span id="sr-only"></span>
</div>
/* fileUpload.php
--------------------------------------------------------*/
<?php
if ($_FILES['fileUpload']['size'] != 0) {
$name = $_FILES['fileUpload']['name'];
$data = $_FILES['fileUpload']['tmp_name'];
$fileDir = "C:\\wamp\\www\\Business\\Images\\$name";
move_uploaded_file($data, $fileDir);
}
?>
/* script.js
--------------------------------------------------------*/
$(document).ready(function() {
$("#progress").hide();
$("#uploadForm").on('submit', function(e){
e.preventDefault();
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
beforeSend:function() {
$("#progress").show();
},
uploadProgress:function(event, position, total, percentageComplete) {
$("#progress-bar").attr("value", percentageComplete);
$("#progress-bar").width(percentageComplete + "%");
},
success:function() {
$("#sr-only").html("Success");
}
});
});
});
See jQuery Progress Bar for PHP AJAX File Upload, this will do the job.
File Upload Form showing Progress Bar
<form id="uploadForm" action="upload.php" method="post">
<div>
<label>Upload Image File:</label>
<input name="userImage" id="userImage" type="file" class="demoInputBox" />
</div>
<div><input type="submit" id="btnSubmit" value="Submit" class="btnSubmit" /></div>
<div id="progress-div"><div id="progress-bar"></div></div>
<div id="targetLayer"></div>
</form>
<div id="loader-icon" style="display:none;"><img src="LoaderIcon.gif" /></div>
jQuery Form Submit
$(document).ready(function() {
$('#uploadForm').submit(function(e) {
if($('#userImage').val()) {
e.preventDefault();
$('#loader-icon').show();
$(this).ajaxSubmit({
target: '#targetLayer',
beforeSubmit: function() {
$("#progress-bar").width('0%');
},
uploadProgress: function (event, position, total, percentComplete){
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete +' %</div>')
},
success:function (){
$('#loader-icon').hide();
},
resetForm: true
});
return false;
}
});
});
http://phppot.com/jquery/jquery-progress-bar-for-php-ajax-file-upload/

Categories

Resources