Javascript not running in order - javascript

i have problem with my javascript not running in order on submit event.
i have a form more or less like this:
<form id="myForm">
<div>
<button type="submit" name="submit">Submit</button>
</div>
<div>
<div id="loading" style="display:none;"><img src="images/loading.gif"/></div>
<div id="hasil" style="display:none;"></div>
</div>
</form>
and a javascript function with ajax :
$('#myForm').submit(function() {
$('#hasil').fadeOut('fast', function() {
alert('a');
$('#loading').fadeIn('fast');
});
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
if(data=='0'){
$('#hasil').html('Code Already Exist');
$('#loading').fadeOut('fast', function() {
alert('d');
$('#hasil').fadeIn();
});
}
}
});
return false;
});
it supposed to show #loading, hide #loading, then show #hasil. at first submit, it will run with no problem. but when i submit it at second time, the script not running at orderly from top to bottom, instead from point 'd', then 'a' (alert()).
i wonder why the script run like this? did i made a mistake somewhere?

Reference to jQuery API document: http://api.jquery.com/fadeout/
the callback is fired once the animation is complete.
So, if the ajax request was completed faster than the fade out animation, point 'd' will happen first and then point 'a'.
You can place the ajax request inside the fade out callback function to solve the problem.
$('#myForm').submit(function(e) {
$('#hasil').fadeOut('fast', function() {
alert('a');
$('#loading').fadeIn('fast');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
if(data=='0'){
$('#hasil').html('Code Already Exist');
$('#loading').fadeOut('fast', function() {
alert('d');
$('#hasil').fadeIn();
});
}
}
});
});
return false;
});

Related

Loading data in select with Ajax / jQuery on click resets to the first element

Load data into a select with ajax and jQuery.
When I click on any item loaded the selection returns to the first item. Here is the code I use:
HTML:
<div class="selector-asesor-independiente">
<label class="fl ml4p sitecolor">Asesor Independiente
<select name="pol_drectivo" id="pol_drectivo" class="w100p"></select>
</label>
</div>
Javascript:
$(document).ready(function(){
$('.selector-asesor-independiente select').click(function() {
$.ajax({
type: "POST",
url: "ajax_cargaAsesorIndependiente.php",
success: function(response)
{
$('.selector-asesor-independiente select').html(response).fadeIn();
}
});
});
});
I try to change the event from .click to .change but nothing happens.
What am I doing wrong?
It is recommended to call the ajax on document.ready() method or window.load. Not on the click of the same input.
$(document).ready(function(){
//Your ajax call here
});
If this doesn't help, please post a sample of the response you are getting.
Updated code:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "ajax_cargaAsesorIndependiente.php",
success: function(response) {
$('.selector-asesor-independiente select').html(response).fadeIn();
}
});
});

Run JS after div contents loaded from AJAX

There are a ton of proposed answers to my question, but even with all the answers I have found, I can not seem to get any to work. I can make the JS work by adding a delay in execution of the code, but I can't rely on a delay to execute the JS after div has finished loading it's HTML.
I'm creating a page where users can search for an item, and the results are displayed in a div using AJAX. I need some JS to run after the div's html has finished loading. Some of the results data will be hidden until a user clicks on it. The JS code to accomplish this is what I am trying to run once the div finishes loading.
I have tried the following extensively with no luck anywhere:
.load
.ajaxComplete
.complete
.success
.done
Document.ready
I'm sure there are a few others as well, but my brain is just too beat up from dealing with this to remember everything I've tried so far.
My HTML:
<form name ="CardName" method="post" action="">
<div "class="w2ui-field">
<div> <input type="list" Name="CardName" id="CardName" style="width: 80%;"></div>
</div>
<div class="w2ui-buttons">
<input type="submit" name="search" style="clear: both; width:80%" value="Search" class="btn">
</div>
</form>
<div class="Results" id="Results" name="Results"></div>
My JS:
$(function() {
$("#CardSearch").bind('submit',function() {
var value = $('#CardName').val();
$.ajax({
method: "POST",
url: "synergies.php",
data: {value}
})
.success(function(data) {
$("#Results").html(data);
})
.complete(function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
});
return false;
});
});
If there is anything else that could help with this request just let me know!
Thanks in advance!
Note that success and failure are options that you should provide to the $.ajax call, not the returned promise. Also, bind is deprecated in favour of on since jQuery 1.7. Finally, you need to give the value that you're posting to your PHP page a key so that it can be retrieved via $_POST. Try this:
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
},
success: function(data) {
$("#Results").html(data);
},
complete: function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
}
})
});
You can then retrieve the value sent in your synergies.php file using $_POST['CardName'].
If you prefer to use the method provided by the returned promise, you can do that like the below, although the result is identical.
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
}
}).done(function(data) {
$("#Results").html(data);
}).always(function() {
alert("div updated!");
})
});
you can try Synchronous Ajax request, demo code is given below:
$(function() {
$("#CardSearch").bind('submit',function() {
e.preventDefault();
sendData = $('#CardName').val();
reqUrl = "synergies.php";
// this will wait until server request complete
var ajaxOpt = AjaxSyncRequest(reqUrl, sendData);
// after complete server request
ajaxOpt.done(function(data) {
$("#Results").html(data);
});
});
});
function AjaxSyncRequest(reqUrl, sendData) {
var ajaxData = $.ajax({
method: "POST",
url: reqUrl,
data: {
data: sendData
}
});
return ajaxData;
}

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

Call This Function Outside of Form Submit

I have a submit button at the end of my form that is labeled like this:
<button id="sendbutton" style="margin-left:25px;" class="btn btn-large btn-primary" type="submit">Send Responses</button>
This button calls this script:
<script type="text/javascript">
$(function() {
$('form').unbind('submit').bind('submit', function(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
});
});
</script>
How do I create a button outside of this form structure that will call the same function?
You may create whatever button you'd like, even if its outside of the form. And then, to get that button to do the same thing you could simply do
$('#yourNewButton').click(function(){
$('form').submit();
});
Or, why not wrap up your original logic into its own function
function submitMyForm(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
}
And then
$('#yourNewButton').click(submitMyForm);
$('form').submit(submitMyForm);
You can write a click handler to the new button and in the handler trigger the form submit using script
<button id="test" style="margin-left:25px;" class="btn btn-large btn-primary" type="button">Send Responses</button>
then
jQuery(function($){
$('#test').click(function(){
$('form').submit()
})
})
Rather than make the submit handler an anonymous function you make it a named function
function submitHandler() {
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function () {
alert('Your answers have been saved.');
}
});
return false;
}
then change your code to
$('form').unbind('submit').bind('submit', submitHandler);
That way you can call that function whenever you like simple by writing submitHandler();

How to replace .live() method with .on() method

Hei.. I have a function to load more news. Since jquery-1.9.1.min.js this function was working alright, but now I have to replace it with .on() method and I still can't get it work.
Here is the code:
// Load more news feed
$(function(){
var page = 1;
$.ajax({
type: "POST",
url: "data.php",
data: "page=profile&get_news_feed=true",
dataType:'json',
success: function(data){
$("#the_news_feed").html(data.news_feed);
if(page <= data.total_pages){
$("#the_news_feed").after('<button id="load_more_feed" class="btn btn-primary btn-large" style="width: 100%;margin-top:10px">Load More</button>');
}
}
});
$("#load_more_feed").live("click", function(){
var next = page+=1;
$.ajax({
type: "POST",
url: "data.php",
data: "page=profile&get_news_feed=true&page_num="+next,
dataType: "json",
success: function(data){
$("#the_news_feed").append(data.news_feed);
if(next == data.total_pages){
$("#load_more_feed").remove();
} else {
$("#load_more_feed").html("Load More");
}
},
beforeSend: function(){
$("#load_more_feed").html("Loading...");
}
});
});
});
I tryed to replace:
$("#load_more_feed").live("click", function()
with
$("#the_news_feed").on("click", "load_more_feed", function()
but I still can't get it work. What am I doing wrong? Thank you!
I display this function with id="news_feed" so here was the problem
<div class="tab-pane fade" id="news_feed">
<div id="the_news_feed"></div>
</div>
Final solution is $("#news_feed").on("click", "load_more_feed", function()
Thank you guys!
Actually, you're missing the # in the id selector.
$("#the_news_feed").on("click", "load_more_feed", function()
must be
$("#the_news_feed").on("click", "#load_more_feed", function()
assuming #the_news_feed is the parent of #load_more_feed.
EDIT :
From your code, you're appending this #loadmore button after #the_news_feed, so this obviously will not work. Try changing it to this :
$(document).on("click", "#load_more_feed", function()
This will bind the click to the document, which will always exist. Alternatively, you could bind it to #load_more_feed closest static parent, like an element which exists when you load your page and not dynamically created.

Categories

Resources