replacement for async:false in $.ajax - ajax

I have a form that submits data to the database and then gets submitted to google docs.
I am using jquery ajax to achieve this.
javascript:
var name ="a";
var company = "b";
var phone = "1";
...
$.ajax({
async: false,
url: "view/templates/includes/abc.php",
//type: 'POST',
//timeout: 10000,
data: {
"name": name,
"company": company,
"phone": phone,
"email": email,
"comments": comments
},
success: function(data) {
//called when successful
alert(data);
//alert('success');
$('#php-code').html(data);
},
error: function(e) {
// alert(e.message);
//called when there is an error
//console.log(e.message);
}
});
return true;
}
abc.php is where lies my code to insert data into the DB.
Now the issue is I don't wanna use async:false since I read it should never be used because it may cause browser hangs and it destroys the purpose of using ajax. However, if I dont use async:false the form gets submitted before my ajax response comes and so it always goes to the error function.
What could I do to not to use async:false?

You may calling ajax function on submit.
You may want to stop submitting form at your event(click of button may be).
And in the ajax success method, explicitly submit the form.
(can be done using jQuery - $('#id_of_form').submit())
EX. can follow the steps,
$('#id_button_submit').click(function(event){
// this will prevent form to be submitted
event.preventDefault();
// call the function of ajax
serviceCall();
});
In the success method of ajax
success: function(data) {
$('#id_of_form').submit();
// rest of your code
},
Or A jQuery plugin http://malsup.com/jquery/form/#ajaxSubmit may be useful to you

Related

Detect browser's autofill in autocomplete method of jquery

I want a autocomplete functionality for address, for which I am using Google map api under jquery's autocomplete() method.
It is working fine for me, but the issue is when user select address from browser's autofill option, autocomplete method taking it as an input and give an ajax call.
So how I can prevent ajax call if an input is from browser's autofill?
Here is my code:
$('#address').autocomplete({
minLength: 7,
source: function(request, response){
$.ajax({
method: "GET",
url: "https://maps.googleapis.com/maps/api/geocode/json?components=country:au&address="+$('#address').val(),
dataType: "json",
success: function(data) {
// stuff on success
}
});
},
focus: function( event, ui ) {
// stuff on focus of option
},
select: function(event, ui, data) {
event.preventDefault();
// stuff on selection of an option
}
});

Selectors not working on ajax response

I'm using ajax to submit pages and return content blocks based on user action for an onboarding sequence.
If have a page which loads and get 1 content element, the user then clicks Yes or No, which loads the next content element into the same space (via ajax).
For some reason my selectors don't seem to be working on that ajax loaded html.
Here is my ajax function which gets the form:
$.ajax({
beforeSend: function() {
$("#loader").toggleClass('progress');
},
type: 'POST',
dataType: 'json',
data: data,
url: baseUrl+'welcome/user_confirmation_form',
complete: function( response ) {
$("#loader").toggleClass('progress');
},
success: function( response ) {
console.log(response);
$("div.welcome-page > .col").html(response.response);
},
error: function( response ) {
$("#next-steps").html(response.response);
}
});
I'm then trying to access the submit button (have tried doing it as a ahref and button type=submit but nothing seems to be selecting the event.
$('div.welcome-page').on('submit', "user_complete", function(e) {
e.preventDefault();
console.log('FOund form');
var user = $(this).serializeArray();
console.log(user);
});
If I view source, the ajax returned HTML is not even in the dom, but it is when viewing the UI normally.
I'm guessing this has something to do with it?
How can I select all the form data?
Any time I click on the button or ahref it just fires the same page again.
If user_complete is a class you are assigning on your submit button in your loaded html, then you are missing a .
$('div.welcome-page').on('submit', ".user_complete", function(e) {
But this will only work if you're using a submit action as this is listening for a submit event. Maybe you want to listen for a click event?
You need to bind the events to your handlers for your newly added HTML elements. Your original call to
$('div.welcome-page').on('submit' ...
Only bound the event handler for the elements that were on the page at that point in time.
You can put your handler into a function ...
var myHandler = function(e) {
e.preventDefault();
var user = $(this).serializeArray();
}
And then after you load the new HTML you need to bind the handler to the event. So, on success with the AJAX you would ...
success: function( response ) {
$("div.welcome-page > .col").html(response.response);
$('div.welcome-page').on('submit', "user_complete", myHandler);
},

AJAX loading image barely visible

I have a simple issue. I am posting data from a form to my DB using an AJAX request. I have coded in a loading GIF using the beforeSend and complete commands in my AJAX request.
<script>
$(function(){
//email the link
$("##emailTicket#get_active_tickets.ticket_id#").submit(function(){
// prevent native form submission here
$.ajax({
type: "POST",
data: $('##emailTicket#get_active_tickets.ticket_id#').serialize(),
url: "actionpages/email_dashboard_ticket.cfm",
beforeSend: function(){
$('.loader').show()
},
complete: function(){
$('.loader').hide();
},
success: function() {
$("##emailTicketResponse#get_active_tickets.ticket_id#").html("");
$("##emailTicketResponse#get_active_tickets.ticket_id#").append( "Ticket successfully sent." );
}
});
return false;
});
});
</script>
Everything seems to be working correctly however the loading GIF only flashes for a split second because the request doesn't take long at all to complete. Sometimes you can't even see it and users are confused if clicking the submit button actually did anything.
Is there a way to delay the 'complete' part of the function so that the animated GIF appears on the screen longer?
complete: function(){
$('.loader').hide();
},
I was able to achieve this by modifying my complete code in my function and adding a delay in milleseconds:
complete: function(){
$('.loader').hide(3000);
},

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

Ajax request error when changepage

guys. I have a juerymobile multi-page, and I have a button in #page-index, when click it, will send a ajax request to server, and changepage to #page-column, It run will in PC, but when i deploy the multi-page in phonegap, the button click can just run only twice, code is below:
function test()
{
$.mobile.changePage('#page_column');
$.ajax({
url: "http://192.168.168.120:8090/fcmobile/getTest",
dataType: "json"
}).done(function(data) {
alert(data.content);
});
}
I found if I remove $.mobile.changePage('#page_column');, the ajax request can be run well any times. but when I add the changePage code, it only can be run twice, in third time, ajax request can't even be send. Dose anybody know reason?
AJAX is made to be asynchronous, so no need to set async to false to get it working. Use events instead.
For example:
function test () {
$.ajax({
'url': "http://192.168.168.120:8090/fcmobile/getTest",
'dataType': 'json',
'success': function (json_data) {
$(document).trigger('test_json_data_loaded');
console.log(data);
}
});
}
$(document).on('test_json_data_loaded', function () {
$.mobile.changePage('#page_column');
});
When you set async to false, you're basically making it so that every time this AJAX request is made, the user will have to wait until all the data is fully loaded before the application/website can do/execute anything else...not good.

Resources