Prevent Default Action on Hyperlink to Run AJAX - javascript

I have a hyperlink on my page
<a id="delete-file" href="">
<img border="0" src="images/delete_.png" alt="Delete File" width="20" height="20" />
</a>
I'm trying to prevent the default action when it is clicked and run an AJAX function instead. For some reason when I click it, it just brings me to the top of the page and my my AJAX is not fired. No console error messages either.
Can someone help me with my syntax?
<!---Script to upload file link --->
<cfoutput>
<script>
$(document).ready(function() {
$('##upload-file').submit(function(event){
event.preventDefault();
$.each($('##upload')[0].files, function(i, file) {
var formData = new FormData();
formData.append('file-0', file);
ajaxUpload(formData);
});
$('##delete-file').click(function(event){
event.preventDefault();
ajaxDelete();
});
function ajaxUpload(formData) {
console.log("ajaxUpload function called");
$.ajax({
type: 'POST',
url: "actionpages/file_upload_action.cfm?ticket_id=#url.ticket_id#",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$('.loader').show();
},
complete: function(){
$('.loader').hide(3000);
},
success: function(data) {
console.log("File successfully sent.");
$("##addFileResponse").append( "File successfully sent." );
PopulateFileUploadDiv();
},
error: function(data) {
console.log(data);
}
});
}
});
function ajaxDelete() {
console.log("ajaxDelete function called");
$.ajax({
type: 'POST',
url: "actionpages/delete_attachment.cfm?ticketID=#URL.ticket_id#&file_path=#filecheck.file_path#",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$('.loader').show();
},
complete: function(){
$('.loader').hide(3000);
},
success: function(data) {
console.log("File successfully deleted.");
$("##addFileResponse").append( "File successfully deleted." );
PopulateFileUploadDiv();
},
error: function(data) {
console.log(data);
}
});
}
});
</script>
</cfoutput>

$(document).on("click","##delete-file",function(e){
ajaxDelete();
e.preventDefault();
});
Try placing any div wrapping the ##delete-file (loaded before the DOM) that you might have in place of the document.
$(document).ready(function(){
$("#wrapper-div").on("click","##delete-file",function(e){
ajaxDelete();
e.preventDefault();
});
});
If you can't get it to work with the ID because of Cold Fusion, try adding a class to the link:
<a id="delete-file" href="" class="delete-btn">
And then try
$(document).ready(function(){
$(".delete-btn").on("click",function(e){
ajaxDelete();
e.preventDefault();
});
});

This is a very long shot but I think the problem is that you are not escaping all of your hash signs. Notice at your urls:
url: "actionpages/delete_attachment.cfm?ticketID=#URL.ticket_id#&file_path=#filecheck.file_path#"
url: "actionpages/file_upload_action.cfm?ticket_id=#url.ticket_id#",
You are escaping the hash sign for your ids but not there so I'm guessing your server is malforming your Javascript, creating an error and preventing the code from executing. You should try double-pounding them too.
If it's truly an issue with the Id, then maybe you can use other jQuery Constructor like this:
jQuery ( element )
$(document.getElementById('delete-file'));

Ok, so my assumption of the error relating to the fact that my AJAX calls lost their uniqueness because the code for the AJAX was outside of my was correct. I basically had to ajust my code so that I my AJAX code was within my tag, but more importantly, that the functions were giving unique names and were passing the unique data from my output.
Here is my modified and correct code:
<cfoutput>
<table width="50%" border="0" cellpadding="5">
<tr bgcolor="##CCCCCC">
<td width="8%"> </td>
<td width="67%" ><strong>Filename</strong></td>
<td width="18%" ><strong>Actions</strong></td>
</tr>
<cfloop query="filecheck">
<tr bgcolor="###iif(currentrow MOD 2,DE('ffffff'),DE('efefef'))#" class="btnav" onmouseover="style.backgroundColor='##FFFFCC';"
onmouseout="style.backgroundColor='###iif(currentrow MOD 2,DE('ffffff'),DE('efefef'))#'">
<td><img src="images/Paper-Clip-icon.png" alt="Attachment" /><br /></td>
<td>#filecheck.file_path#
(Record-ID #ID#)
</td>
<td>
<a id="delete-file#ID#" class="delete-btn#ID#" href="">
<img border="0" src="images/delete_.png" alt="Delete File" width="20" height="20" />
</a>
<!---Script to upload file link --->
<script>
$(document).ready(function(){
$(".delete-btn#ID#").on("click",function(e){
// ajaxDelete();
console.log("Start of prevent.");
e.preventDefault();
console.log("Calling AJAX with id of #ID#.");
ajaxDelete#ID#();
});
function ajaxDelete#ID#() {
console.log("ajaxDelete function called");
$.ajax({
type: 'POST',
url: "actionpages/delete_attachment.cfm?fileID=#filecheck.ID#&ticketID=#URL.ticket_id#&file_path=#filecheck.file_path#&techID=#url.techID#&TT=#type.TT#",
data: #filecheck.ID#,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$('.loader').show();
},
complete: function(){
$('.loader').hide(3000);
},
success: function(data) {
console.log("File successfully deleted.");
$("##addFileResponse").append( "File successfully deleted." );
PopulateFileUploadDiv();
},
error: function(data) {
console.log(data);
$("##addFileResponse").append( "Something went wrong." );
}
});
}
});
</script>
</td>
</tr>
</cfloop><br />
</table>
</cfoutput>

Related

Show loader only after file is selected and hide when cancel or cross button clicked

I have been trying to show loader when file uploaded using single input element and no other element involved, but its not working.
<!-- ! ajaxLoader Begin -->
<div class="ajaxLoader" id="Loader">
<img src="~/assets/img/loader.gif" alt="">
</div>
<!-- ! ajaxLoader End -->
<input asp-for="File" id="File" type="file" class="form-control DocumentFile" accept=".pdf" title="Browse From Folder" />
Below is the javascript:
<script>
$('#File').focus(function (evt) {
$(this).change(
function () {
$('.ajaxLoader').show();
if ($(this).length === 0) {
$('.ajaxLoader').hide();
}
else{
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '#Url.Action("UpdatedDocumentFile", "Document")',
data: formData,
async: false,
processData: false,
contentType: false,
success: function(res) {
// Do some process on 'res'
$('.ajaxLoader').hide();
},
error: function(e) {
$('.ajaxLoader').hide();
}
});
}
}
);
});
</script>
It in anyway ,does not show the loader on file upload.
Although I tried using below link :
Loader while file upload
but it starts loader as soon as the input element is clicked and closes on any actions of File Upload(Upload, Cancel, Cross button click), whereas in my case it calls ajax and do some processing to finally upload file to server.
Also, I have tried with change event of input file but it does not work if I open the File Location but cancels on first attempt, it never closes the loader for first trial
How can show/Hide loader in case of File Upload, Cancel or Cross button click event?
you can use focusout, but i would prefer on click with a button, but you can also use
change
and there is beforesend in ajax, where you can start your loader
$('#File').on('change', function (evt) { // or use focusout
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '#Url.Action("UpdatedDocumentFile", "Document")',
data: formData,
async: false,
processData: false,
contentType: false,
beforeSend: function ()
{
$('.ajaxLoader').show();
},
error: function (e) {
$('.ajaxLoader').hide();
},
success: function (res) {
$('.ajaxLoader').hide();
}
});
});
or you can set a defaukt setting for all ajaxs, try this , then you don't need loader in ajax
var $loader = $('#Loader'), timer;
$loader.hide()
.ajaxStart(function()
{
timer && clearTimeout(timer);
timer = setTimeout(function()
{
$loader.show();
},
1000);
})
.ajaxStop(function()
{
clearTimeout(timer);
$loader.hide();
});

Why it's not working when I try to parse the data in ajax

I am uploading excel file using ajax and then from there receiving the state and the reason of the failure from the upload page to the PHP page ajax function using json_encode but am not able to access the data each one where as the alert of the data is showing perfectly
$(document).ready(function() {
$('#excel_file').change(function() {
$('#export_excel').submit();
});
$('#export_excel').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "excelupload.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data, status) {
alert(data); //
var datas = JSON.parse(data); // not working
$('#result').html(datas.a); //not woking
$('#reason').html(datas.b);
$('#excel_file').val('');
}
});
});
});
<tr style="background-color:#666;">
<td style="color:#FFF;">
<div id="result" style="color:red;"> </div>
</td>
<td style="color:#FFF;">
<div id="reason" style="color:red;"> </div>
</td>
</tr>
PHP:
<?php
$insertTable= mysql_query("INSERT INTO `rt_state_mst`( `OLE_STATE_NAME`, `OLE_COUNT_ID`) VALUES ( '$state' , '$country_result[0]');");
echo json_encode(array("a" => $state, "b" => "Record has been added"));
?>
excelupload.php should contain only php content. And if you want to return json_encode data from excelupload.php then use the below property in your ajax code.
dataType: "json",

How do I show a loading image while script is working?

I'm using jquery/ajax/php to log in to my website. When I check this log in functionality to my server then it's take few seconds to check log in details. So I want to show a loading image while it's check the log in details. How Can I show this loading image ?
This loading image I want to use:
<img src="images/loading-image.gif"/>
Form:
<div id="success"></div>
<form id="login_process">
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Username</td>
<td><input type="text" name="front_username" placeholder="Username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="front_password" placeholder="Password"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="LogIn" class="submit"></td>
</tr>
<tr>
<td colspan="2">Forgot your password ? Click here.</td>
</tr>
</table>
</form>
Jquery Code:
<script>
$('#login_process').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'login_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$.each( data, function( key, value ) {
if(key !== 'error') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
window.location.href = "index.php";
}, 2000);
}
}
});
});
</script>
Here you go, you just need to get the loading-image and show it before making ajax call, when call is done you just hide it.
html
<img id="loaderAnim" src="images/loading-image.gif"/>
JS
//Hide image on page load
$('#loaderAnim').hide();
$('#login_process').submit(function(event) {
event.preventDefault();
$('#loaderAnim').show(); // Show it before making ajax call
$.ajax({
type: 'POST',
url: 'login_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#loaderAnim').hide(); // Hide always after every request
$('#success').html('');
$.each( data, function( key, value ) {
if(key !== 'error') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
window.location.href = "index.php";
}, 2000);
}
}
});
Add a class to your image tag as follows,
<img class="img-loading" src="images/loading-image.gif"/>
I'm not gonna write the CSS initial hide of the loading image or the positioning of it, hope you can do it your self.
Then easiest is to change you script as follows,
<script>
$('#login_process').submit(function(event) {
event.preventDefault();
//SHOW YOUR LOADING IMAGE
$('.img-loading').show();
$.ajax({
type: 'POST',
url: 'login_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$.each( data, function( key, value ) {
if(key !== 'error') {
$('#success').append('<p>'+value+'</p>');
}
//HIDE YOUR LOADING IMAGE
$('.img-loading').hide();
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
window.location.href = "index.php";
}, 2000);
}
});
});
</script>
Use css to hide the image initially, then modify your code as follows:
HTML:
<img class="loading" src="images/loading-image.gif"/>
JS:
$('#login_process').submit(function(event) {
event.preventDefault();
$('.loading').show();
.....
......
success: function (data) {
$('.loading').hide();
....
});

Facing AJAX issue with JSP

I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});

Submit unresponsive after ajax call + fadeIn()

Good day, fellow programmers.
There's this index.php that does an Ajax call to login.php and appends the DOM elements and some javascript from inside this into the body of the index. This login.php consists out of a a single div that contains a form and a submit button, which fadeIn() as soon as it is all appended.
However: the submit button is unresponsive!
I did find, after a while, that this does not happen when you directly access login.php via URL (.../.../login.php) instead. This means it's the fact that the index appends the whole, which makes them unresponsive.
(Also: in light of this, I've added a $(document).ready(function(){ ... }); around the entire script in the login.php, but that did not seem to help at all. Instead it caused all functions to return errors...)
I'm out of ideas. Perhaps some of you might have had any experience with these matters?
As always, thank you for the time!
Here's the (simplified) code:
index.php
$('#logInButton').click(function(){
loadContent('/login/login.php', 'body');
});
loadContent();
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
}
});
}
}
login.php (deleted some styling. If you want some specific info, just ask!)
<style>
// some styling
</style>
<div id="loginBlack">
<div class="login" style="z-index:9999;">
<form id="myform1" name="myform1">
<div>
<img src="images/inputEmail.png" />
<div id="emailOverlay">
<input id="email" type="text"/>
</div>
</div>
<input id="iets" name="iets" type="submit"/>
</form>
</div>
</div>
<script type="text/javascript">
// $(document).ready(function(){ // <-- been trying this out.
$('#loginBlack').fadeIn(t)
// some functions pertaining to logging in and registering
// });
</script>
Use jquery on() instead of click()
$('body').on('click', '#logInButton' ,function(){
loadContent('/login/login.php', 'body');
});
That should make the elements behave properly
Note: you can also replace body selector with something nearer to the click button ( its nearest parent )
EDIT::
With this you can have the styling in your normal css file. Put it outside of the login.php
And your js goes into into the success handlers. So just leave the php with the actual html
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
}
});
}
}

Categories

Resources