Hey guys and gals,
I have a form that I would like to use AJAX to submit. For the callback function basically what I want to happen is, the form elements disappear (.hide) and are replaced by a div element (which will ready success or something of that nature). I then want the function to pause for 5 seconds and then redirect to a different URL.
The AJAX request successfully submits (as I receive an e-mail to the specified address as I should) but the callback function is not carrying out properly. Any suggestions?
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(5000);
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})
}
})
}
}
**
UPDATE #1
**
This is the only error code that I am getting when I initially load the website (I've heard these errors only pop up in the dev tools and do not affect the user?)
But then when I submit the form I get this error code
I've also updated my JavaScript to the below code, taking advice from a few people who posted, it's still not working 100% though
$(document).ready(function() {
var $form = $('form');
$form.submit(function(){
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
}
});
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000)
});
});
Joey
setTimeout usage is wrong.
See :
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000);
}
})
}
});
Further, the following should ideally be declared separately, if you want the user to click a link and go after ajax success.
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})
Related
Within the following jQuery showLoader can be set to show a loading icon while the AJAX request is made.
$.ajax({
url: baseUrl,
data: (paramData && paramData.length > 0 ? paramData + '&ajax=1' : 'ajax=1'),
type: 'get',
dataType: 'json',
cache: true,
showLoader: true,
timeout: 10000
});
I want to know if there is a proper way to customise this to some html that i have set for loading icons to make loading icons uniform across my site.
I can agree with Gopal, but be careful about handling errors. If the request fails, the loader should be hidden and user should be informed. See http://api.jquery.com/jquery.ajax/
The complete callback is better for this purpose, because it will be called anyway.
$.ajax({
type: "GET",
url: ""
beforeSend: function(){
$(".show_load_icon").show();
},
complete: function(){
$(".show_load_icon").hide();
}
});
Or you can handle the error manually.
$.ajax({
type: "GET",
url: ""
beforeSend: function(){
$(".show_load_icon").show();
},
success: function(){
$(".show_load_icon").hide();
},
error: function(){
$(".show_load_icon").hide();
alert("Error"); // inform the user about error
}
});
From jQuery 3.0 you can use .done() and .fail()
For my suggestion there is no option for default ajax
showloader
So you can go better for this way.
$.ajax({
type: "POST",
url: "someURL"
data: "someDataString",
beforeSend: function(msg){
$(".show_load_icon").show();
},
success: function(msg){
$(".show_load_icon").hide();
}
});
After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});
I have an Ajax call being made from a button press which returns me some data then goes off and creates a grid. The first time the function is called the Ajax call is made, data is returned and the grid is displayed. Happy Days.
However any subsequent call to the function, where none of the data parameters are changed, result in the Ajax call not being made to the server and the function skips straight to 'success' with the results from the successful call already populated.
Changing any of the 'postParameters' results in a successful Ajax call and the data is refreshed.
function btnClick(){
//blah blah
getGridData();
}
function getGridData() {
var postParameters =
{
SiteID: "#Model.SiteID",
DateFilterFrom: $("#datepickerFrom").val(),
DateFilterTo: $("#datepickerTo").val(),
CustomerFilter: $("#customers").val()
};
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
};
I know there must be an important Javascript concept I am missing but I just cant seem to be able to nail it.
Can anyone help put me in the right direction?
Have you tried to disable the cache with:
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
Explanations
The cache basically tries to save a call to the server by saving the return value of the calls.
It saves them using a hash of your query as a key, so if you make a second query that is identical, it will directly return the value from the cache, which is the value that was returned the first time.
If you disable it, it will ask the server for every query.
You can add cache: false to your ajax request.
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
cache:false,
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
IE might not listen to you though. For that you can add a field to the POST Parameters, where you add the current time in miliseconds, so even IE does not cache.
try to add this in ur ajax call:
$.ajax({
cache: false,
//other options...
});
This will force the recall of the ajax each time.
For more information please check the following link :
api.jquery.com/jquery.ajax
I'm trying to collect all form data and send it to my server before it gets submitted by the user.
So far I have tried a few approaches, but it doesn't work or works partially.
jQuery(document).ready(function(){
dididamdidiomdididim = false;
if(!dididamdidiomdididim){
jQuery("form").submit(function(e){
jQuery.ajax({
type: "POST",
dataType: "jsonp",
url: "http://example.com/collect.php",
data: {
data: jQuery("form").serialize(),
pixel: jQuery("#x36").attr("pixel")
}
});
});
dididamdidiomdididim = true;
}
if(!dididamdidiomdididim){
jQuery(document).bind('beforeunload', function(){
jQuery.ajax({
type: "POST",
dataType: "jsonp",
url: "http://example.com/collect.php",
data: {
data: jQuery("form").serialize(),
pixel: jQuery("#x36").attr("pixel")
}
});
});
dididamdidiomdididim = true;
}
}
});
});
dididamdidiomdididim = true;
}
});
if(!dididamdidiomdididim){
jQuery(document).ajaxComplete(function(){
jQuery.ajax({
type: "POST",
dataType: "jsonp",
url: "http://example.com/collect.php",
data: {
data: jQuery("form").serialize(),
pixel: jQuery("#x36").attr("pixel")
}
});
});
dididamdidiomdididim = true;
}
});
As you can see I have tried different JavaScript events, but for some reason it is not stable, the weird thing is, that some times the data is collected but Firebug does not show any ajax request.
I assume that your three function are 3 different attempts....
For the first one, you should use e.preventDefault or else it will cancel the ajax and reload the page.
For the second one, as AJAX is asynchronous, the page will be unloaded before it sends the ajax.
And for the last one, your ajax function will never be call as there was no ajax before.
ajaxComplete() is call after an ajax was called.
I have this code in my asp.net webform, I call a webmethod to load data from database:
function Inicializar() {
$("#wait").show();
$.ajax({ type: "POST",
url: "index.aspx/Iniciar",
data: JSON.stringify({}),
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (response) {
$("#wait").hide();
var result = response.d;
cargardatos(result );
}
});
}
I call this function in ready event:
$(document).ready(function () {
Inicializar();
});
the first time it works, the problem is that when I press F5 and reload the page data is not loaded, and if I press back working again.
I do not know if I'm doing something wrong.
Sorry for my English..Xd
Thank you. Greetings!
JavaScript is CaSe SenSitIve. So change your code to:
$(document).ready(function () {
Inicializar();
});
But this way, it doesn't even work on the first time. And do check what is wrong with your output using the Network or Console.
Disable Caching if Needed
$.ajax({ type: "POST",
url : "index.aspx/Iniciar",
cache : false,
datatype : 'json'
})
Turn off caching
function Inicializar() {
$("#wait").show();
$.ajax({ type: "POST",
url : "index.aspx/Iniciar",
cache : false,
datatype : 'json'
}).done(function (response) {
$("#wait").hide();
cargardatos(response.d);
});
}
$(document).ready(function () {
Inicializar();
});