setTimeout an ajax call in jquery - javascript

Is there a way to use setTimeout in this ajax call. This is my code:
jQuery.ajax({
type : "POST",
url : dir+"all/money/myFile.php",
data : "page="+data.replace(/\&/g, '^'),
success : function(msg) {
var info = jQuery('.product_overview #allinfo').html();
var url = 'Check Preview'; jQuery('.option_additional').next().find('textarea:first').text(info+url);
},
complete: function() {
jQuery('.add-to-cart button.btn-cart').delay(500).trigger('click');
}
});
I want to do something before this ajax will be triggered that is why I'll use setTimeout or something that would delay this action.
How would I do that?
Thanks in advance :)

Haven't used jquery with setTimeout before but try
var t = window.setTimeout(function, delay);
replace function in the above code with your jquery function.

In a complete function:
complete: function () {
setTimeout(function () {
// your action here
}, 500);
}

You can use beforeSend,
Example
$(function() {
function callBeforeAjax() {
alert('and now do ajax');
}
$.ajax({
beforeSend: callBeforeAjax,
type: "POST",
url: "/",
data: "",
success: function(msg) {},
complete: function(msg) {
alert(msg);
}
});
});
Refer this

#Tols is right, it works. Try something like this: setTimeout(function(){jQuery('.add-to-cart button.btn-cart').trigger('click');}, 500);

Related

How to slow down window.location.href on AJAX request

I need to find a way to slow down the reload of page that window.location.href does.
This is needed because the animation of toggle button is not shown.
Is there a way?
Here code used:
$(".closeMan").change(function () {
if ($(this).prop("checked")) {
$.ajax({
type: "POST",
url: "./close_man.php",
success: function (result) {
window.location.href = window.location.href;
},
});
}
});
Simply use setTimeout (if you really need to slow down your application...):
$(".closeMan").change(function () {
if ($(this).prop("checked")) {
setTimeout(() => {
$.ajax({
type: "POST",
url: "./close_man.php",
success: () => {
window.location.href = window.location.href;
},
});
}, 500);
}
});
You can use a timeout, and window.location.reload():
setTimeout(function() {
window.location.reload();
}, 1000); // Time in milliseconds
Note: you cant call it like setTimeout(window.location.reload, 1000) because you will get an Illegal invocation error.
You may use settimeout to handle timing problem.
$(".closeMan").change(function () {
if ($(this).prop("checked")) {
setTimeout(function(){
$.ajax({
type: "POST",
url: "./close_man.php",
success: function (result) {
window.location.href = window.location.href;
},
});
}
}, 1000);
});

Jquery ajax not execute success

Am sending requesty by ajax to insert data in database. After success submiting my button message was not changed. On press i fire message Please wait... when success is fired set new html value Done. Records in db is success created but button text to Done was not changed.
My script:
var Friend = {
// Add new friend
add: function() {
var btn = $(".btn-add-friend");
btn.click(function() {
$(this).html("Please wait...");
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
data: {
friend: $(this).data('friend')
},
success: function(xhr, status) {
$(this).html("Done"); // Not wortk
alert("done"); // <-- Work
},
error: function(response, s, e) {
alert(response.responseText);
},
complete: function () {
//. the some from success
}
});
});
},
// Initialise
init: function() {
Friend.add();
}
};
Html:
<button type="button" id="item-<?=$person->account_id;?>" class="btn btn-xs btn-add-friend has-spinner" data-friend="<?= $person->account_id;?>"><i class="fa fa-plus-circle"></i> Add Friend</button>
When i click on button text was changet to Please wait.. but after success not changed to Done and alert is successful executed.
looks like it is not part of DOM after click! ALso i try with on() the some result i get.
this inside the ajax function callbacks is .... the ajax call, not the clicked element.
You have to replace it with it
add: function() {
var btn = $(".btn-add-friend");
btn.click(function() {
var self = $(this);
self.html("Please wait...");
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
data: {
friend: self.data('friend')
},
success: function(xhr, status) {
self.html("Done");
},
To use this, you need additional attribute. Add the following with url
context:this
So, the updated code will be
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
context:this,
data: {
friend: $(this).data('friend')
},
success: function(xhr, status) {
$(this).html("Done"); // Will work
alert("done"); // <-- Work
},
error: function(response, s, e) {
alert(response.responseText);
},
complete: function () {
//. the some from success
}
});
Inside the callback, this refers to the jqXHR object of the Ajax call, not the element. so try to assign it to a variable before ajax request, then use this variale inside success function:
//Before ajax request
var _this = $(this);
//Inside success function
_this.html("Done");
Hope this helps.

Calling Ajax request function in href

I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});

How to pass parameter from a link to jquery method

When the user clicks on the link i need the JQuery method to fire, and call a web service, which is located at /Project/Send/SendMethod. When i click on the send link the method gets fired, i know this because the alert is getting displayed. But the problem is how to call the webservice. It would be good if it's a POST method.
<a href='' id='2' class='send'> Send </a>
Jquery method
$(function () {
$('.send').click(function () {
alert(this.id);
});
});
Use jQuery $.post:
$(function () {
$('.send').click(function () {
alert(this.id);
$.post(url, {'id':this.id}, function (response) {
//do the result oriented activities
});
});
});
Use $.ajax() method and specify the url and options like this jQuery Ajax
$(function() {
$('.send').click(function (e) {
e.prevenDefault();
$.ajax({
url: "Project/Send/SendMethod",
type: "POST",
data: values,
success: function(){
alert("success");
$("#result").html('submitted successfully');
}
});
});
});
You can make use of the $.ajax() api in jQuery. Moreover, you have to preventDefault the default behavior in your link. Otherwise, you will change page instead of sending ajax requset.
$('.send').click(function (event) {
event.preventDefault();
$.ajax( {
url:"Project/Send/SendMethod",
type: "POST",
data: { "id": this.id },
success:function(data) {
alert(data);
}
});
});
If you are using jQuery 1.8+, since "success" callback is deprecated as of jQuery 1.8. You should use the "done" http://api.jquery.com/deferred.done/
$('.send').click(function (event) {
event.preventDefault();
$.ajax( {
url:"Project/Send/SendMethod",
type: "POST",
data: { "id": this.id }
}).done(function( data) {
alert(data);
});
});
I'd use jQuery's ajax() functionality (and regularly do).
The example below assumes you're going to get a JSON-formatted response. You can change this if you're going to get back a full HTML page... take a look at http://api.jquery.com/jQuery.ajax/ for more info.
$(function () {
$('.send').click(function (e) {
e.stopPropagation();
e.preventDefault();
var thisId = $(this).attr('id');
alert(thisId);
var hostAndPort = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port; // current page and protocol (http or https)
var requestUrl = hostAndPort + "/Project/Send/SendMethod/";
var str_address = requestUrl + 'id?=' + thisId;
$.ajax({
url: str_address,
contentType: 'application/json',
dataType: 'JSON',
type: 'POST',
success: function (response) {
console.log(response);
// do something...
},
error: function (e) {
// handle error
}
});
});
});

How can I run Ajax functions synchronously from Javascript?

I have the following code:
$('#DoButton').click(function (event) {
event.preventDefault();
$("input:checked").each(function () {
var id = $(this).attr("id");
$("#rdy_msg").text("Starting" + id);
doAction(id);
});
});
function doAction(id) {
var parms = { Id: id };
$.ajax({
type: "POST",
traditional: true,
url: '/adminTask/doAction',
async: false,
data: parms,
dataType: "json",
success: function (data) {
$("#rdy_msg").text("Completed: " + id);
},
error: function () {
var cdefg = data;
}
});
}
When the button is clicked it checks the form and for each checked input it calls doAction() which then calls an Ajax function. I would like to make it all synchronous with a 2 second delay between the completion of one call and the running of the next. The delay is to give the user time to see that the last action has completed.
By setting async=false will that really make the ajax function wait?
How can I add a 2 second wait after the Ajax has run and before the next call to doAction?
There is option in jQuery to set the ajax function synchronous
$.ajaxSetup({
async: false
});
To make the function to wait you can use .delay()
Try the solution of this question also.
Try to do it using recursion
$('#DoButton').click(function (event) {
event.preventDefault();
doAction( $("input:checked").toArray().reverse() );
});
function doAction(arr) {
if( arr.length == 0 ) return;
var id = arr.pop().id;
$("#rdy_msg").text("Starting" + id);
$.ajax({
type: "POST",
traditional: true,
url: '/adminTask/doAction',
async: false,
data: { Id: id },
dataType: "json",
success: function (data) {
$("#rdy_msg").text("Completed: " + id);
setTimeout(function(){ doAction(arr); }, 2000);
},
error: function () {
var cdefg = data;
$("#rdy_msg").text("Error: " + id);
setTimeout(function(){ doAction(arr); }, 2000);
}
});
}
Use setTimeout for the AJAX call doAction.

Categories

Resources