JQuery call not working after Ajax call succeeds - javascript

I have an Ajax call that looks like this:
$("#start-upload-btn").click(function(){
$.ajax({
type: "post",
url: "",
data: {
newProjectName: $('#project-name').val(),
csrfmiddlewaretoken: csrfToken
},
success: function(data){
$("#file-upload").click();
}
})
});
Upon success I want to perform a click on the element with id #file-upload to launch the file selection dialogue, but putting the code in success function fails to work. It works anywhere else. Is there something special about the scope of the Ajax success function? I really cannot figure this out.
Thanks

There is nothing inherently problematic about issuing a click on any normal element (including a button) from an ajax success callback.
The problem is that a file-input dialog is not a "normal element". It has some specific security limitations - one of which clearly limits your interaction with it.
This is demonstrated by the following fiddle: https://jsfiddle.net/qhfwobpz/
You'll see that issuing a click on the file-upload directly works without a problem. Doing it from an ajax callback yo'll see the callback is called, but the file dialog never shows.
This answer gives more detail as to the "why" and it boils down to you can open the dialog from an event issued by the user but not purely programatically.

Related

AJAX response caching / onclick-event inside of a function

I´m using AJAX to execute some server-side actions and refresh a table inside the page without reloading the page itself. All works fine at first view. But I wrote a function in PHP to send an email and execute it via AJAX. When I´m starting this action for a second time old responses gets triggered.
What exactly happens:
I´m clicking a Button to execute the "Sendmail-Action"
a Modal asks me if I want to execute the action and I´m clicking yes
a PHP-Script gets executed and sends the email
the Modal gets closed after the PHP-Script finishes (~2s)
the table (with emails and so on) gets refreshed and the status updated
What happens next:
I´m clicking a Button to execute the "Sendmail-Action" for the same
or another entry in my table
a Modal asks me if I want to execute the action and I´m clicking yes
the Event triggers twice / 4xAjax-Request instead of 2 (I can see it in my Chrome-Console)
the Modal closes and 2 Mails sended
What I´ve tried to get rid of this behaviour:
checked my JS with JSHint
checked my PHP-Code (no errors in apache error.log)
redesigned the PHP-Script (Sendmail), now the AJAX executes a function
tried different browsers
deactivated AJAX-Caching
completely deactivated Caching with Apache (correct Headers)
deactivated Session-Caching in my php.ini (I don´t use sessions)
unset all variables in PHP
cleared the cache for all of my browsers
checked all headers
searched several hours for solutions
More information about my setup:
jQuery 2.1.4
php 5.4
Apache 2.2
I can´t find a solution to my problem and maybe this is caused because I´m adding the content dynamically to the table. I had the same problem in the past and I´m thinking the Modal (which is also dynamic) triggers the click on the "Yes-Button" twice.
You can put your ajax click handler outside of that function:
$(document).on('click', '.email-resend, .email-send, .show-doc, .show-acc, .more-acc, .no, .yes, .termin', function(){
$.fn.doAction(classname, comEntry);
});
As you mentioned that you have placed this in the function. Instead you should put this outside of it:
$(document).on('click', '.bt-ok', function(){
$.ajax({
....
});
});
Edit by #pandora: Or just use a second function (in my case) like this:
$(document).on('click', '.bt-ok', function(){
$.fn.sendRequest($('#modal').attr('data-1'), $('#modal').attr('data-2'));
});
Then I can call the function like this and execute the AJAX:
$.fn.sendRequest = function(data1, data2) {
$.ajax({
url: 'target.php',
cache: false,
data: { gimme1 : data1, gimme2 : data2 },
success: function(response) {
// Show Error
if(response.length > 0){
alert(response);
}
// Reload Content
$.fn.Reload('','');
// Close Modal
$('#modal').css({'display' : 'none'});
}
});
};

Commenting System - Showing posted comment without page reload

working on a commenting system using PHP.
Everything works, the insert, the validation and also the ajax call.
Currently i am doing a .load() on the container that holds the page content.
However, this causes issues when trying to post comments again. The javascript doesnt work, some of the javascript functions linked with the comments also dont work and little things like that.
How should i be dealing with comments, every time a user posts one.
Like on facebook for example, you post a comment and the new one is just placed underneath the last.
The only thing i can think of i using .append() and appending the new comment to the list.
In my PHP page i could set a JSON return of the username, the comment, the users profile picture etc and then append all of that data back?
Otherwise is there a better method of simply 're-loading' the div container after the success ajax call?
Thanks, what i have works... but i want to be learning things the CORRECT way.
Craig.
You can use $.ajax to load new comments and use .append() or prepend() to insert the new comments in the container. If you wrap the call in a function you can call the function over and over (for instance every 2 seconds) to check for new comments.
If I remember correctly .load() will only execute when the element is ready after browser refresh.
What things are not working? Remember that events and data must be bound after succesful AJAX call. Meaning if you bound events to links when the page loaded they are obviously still in effect. But if you insert a link later on it does not have any events.
What I would normally do is something like this:
$.ajax({
url: 'ajax.php',
data: { 'parameters': 'yada yada' },
dataType: 'json',
success: function( data ) {
$('.links').unbind().click(function() { alert('hello!'); });
}
});
The reason for the .unbind() is that you will otherwise bind several events on the existing links - and you don't want that ;-)

Display Ajax response in HTML

I'm calling a PHP file, and it's returning the response when I view it in Firebug. However, it's not displaying on my page. I'm not sure if the success is actually firing, because I can't even run an alert, but it is working because the PHP code is firing and returning what it's supposed to.
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$.ajax({
type: "GET",
url: 'https://www.example.com',
dataType: 'jsonp',
contentType: "text/html",
crossDomain:'true',
success: function (data) {
$(".result").html(data);
}
});
</script>
<div class="result"></div>
You need to make the ajax call on load or document ready. The div may not exist at the time of response (page is interpreted top down).
Just a little lesson about what your are doing.
When working with any form of Ajax (or JavaScript in general), it is usually imperative to have your console open. You will be able to see your request, your response, and whole other useful information.
I usually work with Firefox and Chrome from time to time.
You can open your console by right clicking on the page anywhere and inspect an element with Firebug (on Firefox).
And inspect element in Chrome.
Once you see the Ajax call, click the + and see its content.
You should see something like:
Headers Post Response JSON Cookies or something alike.
I hope that helps.

Callback when web page download completes

When the user click on a tab in a web page, the tab opens and its corresponding page downloads from the server.
I want to add some UI in this page through JavaScript or jQuery. I know how I can add this but problem is if I execute my JavaScript function for adding UI on click of the tab, it does not work because the corresponding page has not been downloaded yet.
Basically, what I want to know such function that is called when the page completely downloads.
Have you used JQuery success ?? success handler will be called only after your response is ready.
Try this :
$.ajax({
url: "test.html",
context: document.body,
success: function(){
//Do the stuff here, hence downloading has been completed and response from server is ready
$(this).addUI("done");
}
});
add this in the body of your page..
<body onload="init()">
</body>
Basically your calling your init function -- which initiates all the other functions which you want only after the body of the webpage is loaded..
I have face this problem too.. Problem here is your content is not yet available before you could work on it.
any reference you give will result in returning Null
The solution can be .bind() & .live()
suppose this is your dynamic content
$('body').append('<div class="clickme">Another element</div>');
you can bind the element by,
$('.clickme').bind('click', function() {
// Bound handler called.
});
or register it for live content, by
$('.clickme').live('click', function() {
// Live handler called.
});
when no longer needed, you may unsubscribe the event on dynamic content by .die()
you may also find .delegate() & undelegate() useful as there are little issues with .live() & .die().
Check http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/ for choosing the one you need for your application.
Remember not to forget you ensure that content is loaded by ajax success as programmer_1 here, mentioned.
Good luck :)
Any further clarifications pls comment.

jQuery live doesn't works as expected

i have problems with ajax requests and simple <input type="submit"/>.
i use to load views inside other views, modular i mean, with jquery using .load(url) from one view to another.
so the problem is that if i load view_2 inside view_1 and the js script for view_2 is inside view_1 i need to use live('click') for example to launch an xhr request from view_2, so when i try it launches 3 (multiple) xhr at same time, instead of only 1 at time, don't know why.
the only thing i know is:
using live('click') in view_1 it launches 3 multiple XHR.
using click() in view_1 it doesn't work(obviously i think).
using click() directly inside view_2 it works (but i can't use js
in loaded views, i can use js only in "parents" views)
the functions are really simple, really don't know why i have this problem (i also disabled submit in ajax beforeSend) check this is a view_1 code which runs on loaded view_2 and launches 3 XHR for click :|
$(document).ready(function(){
$('#save-doc').live('click',function(){
var _title = $('#doc-title').val();
var _doc = $('#doc-doc').val();
update_doc(url_update_doc,{'title':_title,'doc':_doc,'id_doc':_choosed_doc,'id_project':id_project},this);
});
});
function update_doc(_url,_data,_starter){
$.ajax({
type:'POST',
data:_data,
url:_url,
dataType:'json',
beforeSend:function(){
$('.ajax-loading').show();
$(_starter).attr('disabled','disabled');
},
error:function(){
$('.ajax-loading').hide();
$(_starter).removeAttr('disabled');
},
success:function(json){
$('.ajax-loading').hide();
$(_starter).removeAttr('disabled');
if(json.error){
$('#error-title').html(json.error_title);
$('#error-doc').html(json.error_doc);
$.scrollTo('.append-form-edit-doc','fast');
}
if(json.confirm){
$.scrollTo('#top','fast');
$.gritter.add({
title:'Document Saved',
text:json.confirm
});
}
}
});
}
If that's a submit button inside the form then unless you prevent the default action, the form will be submitted. (That'd account for 2 POSTs, but not three.)
Remember that .live() is binding the event handler to the document itself. With that in mind, it is searching for #save-doc throughout the document on every click.
If there are multiple elements in the document with the 'save-doc' ID then they'll all be triggered.
However, what I bet is happening to you is you may have multiple forms layered which are all being executed by this one input.
Edit: Third possibility, is what Pointy mentions. Executing a submit via your event handler and another submit occurring because of browser behavior.
Please provide the HTML and what is being loaded into them.

Categories

Resources