Submit unresponsive after ajax call + fadeIn() - javascript

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');
}
});
}
}

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();
});

Javascript used for random button

I am a beginner in JavaScript means and programming, and I encountered a problem for a personal project. I made an anime fight website getting some information from MySQL Database each anime has ten videos and photos, through a random button it randomly takes one link for a video and photo. The problem is that it only work only one time if I random again nothing happens. I know that in order to make that work I have to rewrite the code again after the success of the first random for getting a second random but this will create an infinite loop. Can somebody help me solve this issue.
This is the code used:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
$('#random').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
})
}
});
})
});
</script>
I understand that $.ajax request overwrites initial .imgResponsive element, am I right? Along with overwritten .imgResponsive you permanently lose click event attached to this element.
In that case you need to attach event to element container, eg.
$(document).on('click', '.imgResponsive', function() {....
...
}
instead of
$('.imgResponsive').click(function(){ ....
You have to register EventListener in order to proceed.
Try this:
<script>
var showImage = function(e){
e.preventDefault();
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
};
$(document).ready(function () {
$('document').on('click', '.imgResponsive', showImage);
$('document').on('click','#random', showImage);
});
</script>
The way your code is written, you're handling only a single AJAX response (aside from the first one) with no way to handle more AJAX requests triggered by clicking the #random button. You need to write functions for handling button clicks and the AJAX responses instead of using anonymous functions; that way it's modular enough that you can listen for and handle more button clicks in the future.
Something like this:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
$('#random').click(handleButtonClick);
});
function handleButtonClick(e){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
}
function handleResponse(response){
$('#hiddenPage').html(response);
}
});
</script>
Edit: Another thing that might be happening is that your #random element is being overwritten every time you do $('#hiddenPage').html(response);. In that case you would need to attach a new event handler to the new #random element every time you handle an AJAX response:
function handleResponse(response){
$('#hiddenPage').html(response);
$('#random').click(handleButtonClick);
}

how to turn off reload of page after sending ajax to php and how to fix this code

How to turn off reload of page after sending AJAX to PHP? The page reloads every time when I press submit. Is it possible to send some picture without form?
<script>
$(document).ready(function (e){
$("#uploadForm").on('submit', (function(e){
e.preventDefault();
$.ajax({
url: "/class/pdo/add_new_field.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}));
$('#uploadForm').submit(function () {
return false;
});
});
</script>
<form id="uploadForm" method="POST">
<div style="margin-left: 75px;">
<div class="save_divs">picture<input type="file"></div>
<div class="save_divs">name:</div>
<div class="save_divs">date</div>
<div class="save_divs">short_info</div>
<div class="save_divs">long info<input type="submit"></div>
</div>
</form>
Do i need slash (/) in $.ajax url?
too many event handlers. Remove the second one unless sendContactForm(); is important. If it is, update your question with it.
syntax error in the event handler, remove the ( from before (funtion in the submit and one of the ) from the }));
If class is the top folder in your hierarchy you can use the /class, if it is under the form location, then no. Use "class/..."
like this
<script>
$(function(){
$("#uploadForm").on('submit',function(e){
e.preventDefault();
$.ajax({
url: "/class/pdo/add_new_field.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}); // also a ) too many here
});
</script>
Ok, First problem is : -
You have submit binded twice once with on, once with submit(), use only one.
Now the error is coming due to the second binding,
There is some error in sendContactForm(), due to which it never gets to the line return false and default page is submitted and is reloaded, check for console errors, also, to prevent confusion in future, you could probably use e.preventDefault(); at the start of the function to stop further propogation. (thanks #rory)
$('#uploadForm').submit(function (e) {
e.preventDefault();
sendContactForm();
return false;
});

FormData ajax upload on IE8 -> alternatives and how it works

I'm tyring to upload a picture with ajax, so I'm using FormData, but it's not working with IE8. I've looked about it and it's not possible to use FormData with IE8, but I've found nothing I've been able to use instead in order to make it work on IE8 and other browser. Could someone tell me what to do please, and how to do it ?
The form I'm trying to submit
<form id="addImgForm" name="addImgForm" method="post" action="#URL(Action('ChiliTest-ImageUpload'))#" enctype="multipart/form-data">
<input id="newImage" type="file" name="newImage">
<input type="hidden" name="MAX_FILE_SIZE" value="12345">
<span id="addImage" class="button-addImage" type="submit"><isTradConstant keyword="l_customizationsChiliEditor_AddImageButtonTitle" template="CustomizationsChiliEditor" init="Ajouter"></span>
</form>
Called on addImgForm submit
$.ajax({
url: myUrl,
type: "POST",
data: new FormData($(this).parent()[0]),
contentType : false,
async: false,
processData: false,
cache: false,
success: function(data) {
//do something
}
});
return false;
Ideally when i faced this issue, i checked for FormData in browser and if that returns undefined, then i went for form submission via an iframe.
We have used jquery plugin for the same and got resolved this issue.
It is too simple just use
$('#myForm').ajaxForm(function() {
});
instead of below call, it set all options automatically.
$.ajax({
url: myUrl,
type: "POST",
data: new FormData($(this).parent()[0]),
contentType : false,
async: false,
processData: false,
cache: false,
success: function(data) {
//do something
}
});
Hope this will work out, let me know if any hurdles during implementation. Make sure you added jquery plugin before using ajaxform function. Do not need to do anything for other browser it works for IE and other both.
You can use [jQuery Form Plugin][1] to upload files via ajax in IE 8 and your example code should be like this:
[1]:
$(document).ready(function() {
var options = {
beforeSend: function() {
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete) {
$("#bar").width(percentComplete + '%');
$("#percent").html(percentComplete + '%');
},
success: function() {
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response) {
$("#message").html("<font color='green'>" + response.responseText + "</font>");
},
error: function() {
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
<script src="http://malsup.github.io/min/jquery.form.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<form id="myForm" action="/demo/Upload" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div>
</div>
<br/>
<div id="message"></div>

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;
});

Categories

Resources