the opposite function for the done function in ajax/jQuery - javascript

I want to send a form via Ajax, with jQuery.
On submitting the form, a loading image will be shown on the data transferring.
In pure JS I used this code :
var myForm = document.getElementById('myForm');
var xhr = new XMLHttpRequest();
myForm.addEventListener('submit', function(e){
var formData = new FormData(myForm);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200) {
loading.style = "visibility:hidden;";
alert('Authentification réussi.\n' + xhr.responseText );
}else{
loading.style = "visibility:visible;";
}
};
xhr.open("GET", "authentification.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(formData);
e.preventDefault();
}, false);
And this is what I tried using jQuery :
var jqxhr = $.ajax({
type : $('#myForm').attr('method'),
url : $('#myForm').attr('action'),
data : $('#myForm').serialize(),
dataType : 'html'
});
$(function(){
$('#myForm').submit(function(event){
jqxhr.done(function(data){
$('#loading').hide();
alert(data);
});
//Here the other method
});
event.preventDefault();
});
The problem is I don't know what it the function that will be executed on sending data, in pure JS I just used the else statement for : xhr.readyState == 4 && xhr.status == 200.
So, what is the function which is responsible for that ?
Edit :
The solution was to use the attribute beforeSend as the following :
jqxhr = $.ajax({
type : $(this).attr('method'),
url : $(this).attr('action'),
data : $(this).serialize(),
dataType : 'html',
beforeSend : function(){
$('#loading').show();
},
complete : function(){
$('#loading').hide();
}
})

You need to sent the ajax request within the submit handler... when you say $.ajax(..) the ajax request is sent and the since you have placed the code in global context this refers to the window object.
var jqxhr;
$(function () {
$('#myForm').submit(function (event) {
jqxhr = $.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'html'
}).done(function (data) {
$('#loading').hide();
alert(data);
}).always(function () {
jqxhr = undefined;
});
//Here the other method
});
event.preventDefault();
});

It might work. You can use beforeSend to show your loading image and hide it on done.

Related

Using AJAX GET request to pass the value of <option> tags to the URL

I want to pass options' values to the URL whenever the users select an option. For example these are the options:
Option 1
Option 2
Option 3
And this is the URL: http://example.com/products
When he selects an option among those 3, the URL changes into this: http://example.com/products?option=option1
I tried vanilla Javascript XMLHttpRequest for this, and this is my code:
function ajaxFormValidate(_method, _url, _callback, _fallback, _sendItem) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState < 4) {
return;
}
if(xmlHttp.status !== 200) {
_fallback(xmlHttp.response);
return;
}
if(xmlHttp.readyState === 4) {
_callback(xmlHttp.response);
}
};
xmlHttp.open(_method, _url, true);
xmlHttp.send(_sendItem);
} //Set a function for AJAX Request
//Actual performance
window.addEventListener('load', function(){
var _sort = document.getElementById('sort'), _filter = document.getElementById('filter'); //Get the elements
_sort.addEventListener('change', function(){ //If the value of the field changes
var _frmData = new FormData(); //Create a new FormData object
_frmData.append('sort', _sort.value); //Append the value to this object
ajaxFormValidate('GET', location.href, function(response){
//Perform the redirection here (without reloading the page)
}, function(response){
alert("Request cannot be sent!");
}, _frmData);
}, false);
});
Recently, I don't have any ideas for this. Any help is appreciated. Thanks
This is a good way of using GET in pure Javascript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "example.com/products.php?option=YOUR OPTION VALUE GOES HERE", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
console.log(data);
}
}
And this is the jQuery way (my preferred method):
var myOption = $('.your-elenet-calss-name').val();
var myurl = "http://example.com/products.php";
var dataString="&option="+myOption+"&check=";
$.ajax({
type: "GET",
url: myurl,
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function(){//Do some stuff here. Example: you can show a preloader///},
success: function(data){
if(data =='success'){
alert('done deal...');
}
}
});

Need to be able to run an ajax call with element loaded after document.ready()

I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});

Show modal form before ajax cal and get data from it

I have an ajax function something like this:
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
$.ajax({
type: 'POST',
url: 'script.php',
dataType: 'json',
data: "id="+e+"&mod="+e1+"&curc="+curc,
beforeSend: function() {
$('#mform').show();
},
complete: function() {
$('#fountainG').hide();
},
success: function(data) {
document.getElementById("itog").innerHTML = data.d+data.a;
},
error: function(xhr) {
document.getElementById("itog").innerHTML = '123';
}
});
}
I need to show some modal form to user, and get the data from it in ajax script. I tried to add show function to ajax beforeSend - but I do not understand how to wait for user form submit, and get data from modal form. Ajax function call in html: href="javascript:void(0)" onclick="javascript:foo(3800064420557,1,138)
You just need to re-arrange your logic. Instead of trying to show the modal "within" the ajax request, hold off on sending the ajax request until you have gotten the necessary data from the modal. Here is a rough outline, presuming that your modal element $('#mform') has a form in it with an id of myform which is the form you want to get data out of.
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
var modal = $('#mform');
var form = $('#myform', modal);
form.on( 'submit', function(){
$('mform').hide();
// make your ajax call here the same way, and inside the
// onsuccess for this ajax call you will then have access to both
// the results of your ajax call and the results of the form
// data from your modal.
$.ajax({ ... });
});
}
To get form data, you can try with below code
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
form_values = {}
$('mform').show();
$('#myForm').submit(function() {
var $inputs = $('#myForm :input');
$inputs.each(function() {
form_values[this.name] = $(this).val();
});
console.log("form data:", form_values)
// with form_values continue with your coding
$.ajax({
type: 'POST',
url: 'script.php',
dataType: 'json',
data: "id="+e+"&mod="+e1+"&curc="+curc,
success: function(data) {
$('mform').show();
document.getElementById("itog").innerHTML = data.d+data.a;
},
error: function(xhr) {
document.getElementById("itog").innerHTML = '123';
}
});
});
}
Hope it will help you :)

showing loader image with submition using ajax

$(document).ready(function(){
$('#registration_form').on('submit',function(e){
/// e.preventDefault();
$("#loading").show();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if(email == ''){
$("#email").addClass('error');
error_flag = 1;
}
if(checkEmail<3 || checkEmailDot<9){
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"green");
$("loading").hide();
}
else{
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"red");
}
}
});
e.preventDefault();
});
});
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
You can use the always handler to do that.
Also note that, you should so the loader only if the ajax is sent, so in your case only after the validations are done it should be done.
$(document).ready(function() {
$('#registration_form').on('submit', function(e) {
/// e.preventDefault();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if (email == '') {
$("#email").addClass('error');
error_flag = 1;
}
if (checkEmail < 3 || checkEmailDot < 9) {
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {
email: email
},
beforeSend: function() {
//show it only if the request is sent
$("#loading").show();
},
success: function(res) {
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if (status == 'true') {
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "green");
$("loading").hide();
} else {
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "red");
}
}
}).always(function() {
//irrespective of success/error hide it
$("#loading").hide();
});
e.preventDefault();
});
});
Have a loading image like this:
<img src="loader.gif" id="loader" />
And in the script, before the AJAX call, show it:
$("#loader").fadeIn(); // You can also use `.show()`
$.ajax({
// all your AJAX stuff.
// Inside the success function.
success: function (res) {
// all other stuff.
// hide the image
$("#loader").fadeOut(); // You can also use `.hide()`
} // End success
}); // End AJAX
Solution to your Problem
You are missing # in your call:
$("loading").hide();
//-^ Add a # here.
Change it to:
$("#loading").hide();
I'd do it this way:
function loadsth(){
$('#load_dialog').show();
$.ajax({
method: "POST",
url: "?ajax=ajax_request",
data: { data:"test"},
success:function(data) {
$('#load_dialog').hide();
}
});
});
Try using jquery's ajax function beforeSend
$.ajax({
method: "POST",
url: "/url",
data: { data:"test"},
beforeSend: function() {
//SHOW YOUR LOADER
},
success:function(data) {
//HIDE YOUR LOADER
}
});
});
I hope this has given you some idea.
try this its work for u
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
type: 'POST',
beforeSend: function(){
$("#loaderDiv").show();
},
success: function(data) {
$('#output-json-inbox').jJsonViewer(data);
$("#loaderDiv").hide();
},
error: function() {
alert("error");
}
});

Ajax Request on another's success ( jQuery )

I want to run the another ajax request on one's success.
THE CODE
$(document).ready(function(){
$('*[data-load-template]').each( function () {
var template = $(this).data('load-template');
var element = $(this);
$.ajax({
url : "templates/" + template + '.tpl',
method : "GET",
success : function (htmlData) {
$.ajax({
url : "data/" + template + '.json',
method : "GET",
success : function (jsonData) {
console.log(jsonData); // why isn't this one working???
}
});
element.html(htmlData); // this is working
}
});
});
}); // dom ready event
My question is why isn't this code working and how to make it work.

Categories

Resources