Jquery execute in wrong sequence [duplicate] - ajax

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the sample as below. I always got "c" first before "a" and "b". How do I get "a","b" and "c" accordingly? I would appreciate for any advice.
b.extend({
get: function (id) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
}
});
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
}
});
}
console.log("c");
}
});

Try
put your code in success:
b.extend({
get: function (id) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
if (a === 5) {
console.log("c");
}
}
});
}
}
});
}
});

You can also use deferred:
b.extend({
get: function (id) {
var request = jQuery.ajax({
type: 'GET',
url: url,
data: pdata
}).then(function(result) {
console.log("a");
return result;
});
for (var a = 0; a < 5; a++) {
request = request.then(function(result) {
return jQuery.ajax({
type: 'GET',
url: url,
data: pdata
}).then(function(result) {
console.log("b");
return result;
});
});
}
request.then(function() {
console.log("c");
});
}
});

Do the call for C in the callback of B, and the call for B in the callback of A

jQuery is async, so some Ajax requests may finish before others.
b.extend({
get: function (id) {
var async = $.ajaxSetup()['async']; // store the current value of async to a variable
$.ajaxSetup({'async':false}); // Set async to false
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
}
});
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
}
});
}
console.log("c");
$.ajaxSetup({'async': async }); // Set async to back to original value
}
});
The only downside to this is that your page will 'hang' until the request is completed

Related

Returning error from controller to AJAX jQuery

I works with ASP.net MVC and I have get "Error" from belowe my JavaScript code:
This is my AJAX jQuery code:
$(document).ready(function () {
var dataId;
$(".item2 .small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').prop('href', url);
$.ajax({
url: '/Carpet/CheckCarpet',
type: 'POST',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success == false)
$('#dateLink').hide();
else
$('#dateLink').show();
alert("Success");
},
error: function (errorThrown) {
alert("Error");
}
});
and this is a controller code:
[HttpPost]
public ActionResult CheckCarpet(int CarpetImageid)
{
bool DecorShow = false;
DecorShow = db.Images.Where(x => x.Id == CarpetImageid).FirstOrDefault().DecorTest;
return Json(new JsonData { Success= DecorShow });
}
what's the reason? Someone knows?
I found the solution.i change url to #Url.Action("CheckCarpet", "Carpet") and fixed.
$(".small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').attr('href', url);
$.ajax({
url:'#Url.Action("CheckCarpet", "Carpet")',
type: 'Post',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.Success == false) {
$('#dateLink').hide();
$('.p2').hide();
}
else {
$('#dateLink').show();
$('.p2').show();
}
},
error: function (error) {
alert(error.d);
}
});
});

ajax call returning promis and resolve it by the calling function to its value

By now i read somewhere around 6 pages containing documentations and stackoverflow answers but I don't get the method.
My function is by now after reading all the stuff built like this:
async function getFToken(postId){
const response = await $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{
action:'get_f_token',
postId: postId,
},
success:function(response) {
}
});
return response;
}
and in my other function is like this:
function getFeedback(postId){
$(".show_company").hide();
$(".show_feedback").show();
$.ajax({
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data:{
action:'get_feedback',
postId: postId,
},
success:function(response) {
var postTitle = '';
for (i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
var test = getFToken(387);
alert(Promise.resolve(test));
};
$("#result").html(postTitle);
}
});
}
is there any chance, that this is a bigger issue because i call a async in another Ajax call trying to retrieve the value? I'm trying to get the string from the first ajax call and hand it to the second function in the ajax call to attach it to the posts i retrieve from WordPress
The alert is giving me [object Promise] but how do i get the value passed from the php script?
php-scrtipt:
//get fToken from specific feedbacks
add_action( 'wp_ajax_get_f_token', 'get_f_token' );
function get_f_token() {
if(isset($_POST['postId'])){
$postId = $_POST['postId'];
}
$fToken = get_post_meta($postId, 'fToken', true);
echo $fToken;
wp_die();
}
Don't use success callbacks when you can use async/await:
async function getFToken(postId) {
return $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'get_f_token',
postId: postId,
}
});
}
async function getFeedback(postId) {
$(".show_company").hide();
$(".show_feedback").show();
const response = await $.ajax({
// ^^^^^
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data: {
action: 'get_feedback',
postId: postId,
}
});
let postTitle = '';
for (const i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
const test = await getFToken(387);
// ^^^^^
alert(test); // no Promise.resolve, you don't want to alert a promise
}
$("#result").html(postTitle);
}

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

Call multiple ajax calls

$.ajax({
url: "",
jsonpCallback: 'item',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
var markup = "";
$.each(data.list, function(i, elem) {
dbInsert(elem['itemCode'], elem['description'], elem['price']);
});
},
error: function(request, error) {
alert(error);
}
});
I have the above type of different ajax calls with different urls. How can I run each Ajax call, one after another?
You can do something like this.
$('#button').click(function() {
$.when(
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('one is done')
}
}),
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('two is done')
}
})
).then( function(){
alert('Final Done');
});
});
fiddle
Keep track of the urls still to send, and have the success inline function of one ajax request go and call the next.
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
... do what you want with the data ...
if (urls.length > 0) runNextAjax();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
}
});
};
// Start the sequence off.
runNextAjax();
The above code acts on the data as it arrives, if you want to cache it all and act on it all at the end, store each result in an array, then process the array in a function that gets called at the end:
var dataAccumulator = [];
var displayAllData = function() {
for (int i = 0; i < dataAccumulator.length; ++i) {
var data = dataAccumulator[i];
... process the data into HTML as before ...
}
};
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
// Store the data we received
dataAccumulator.push(data);
if (urls.length > 0) runNextAjax();
else displayAllData();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
else displayAllData();
}
});
};
// Start the sequence off.
runNextAjax();

asp.net mvc 3 json does not work

This is my jquery with json
$('#btnVerificationOk').click(function () {
var verId = $('#trans_verification_id').val();
var verCode = $('#trans_verification_code').val();
$.ajax({
url: '/Profile/CompleteTransactions',
type: 'POST',
data: { },
dataType: 'json',
success: function (result) {
alert(result);
},
error: function () {
alert('ERROR ERROR !!!!!!!!!!!!');
}
});
});
And My C# method:
[Authorize]
[HttpPost]
private JsonResult CompleteTransactions()
{
return Json("Done");
}
Its always alerts 'ERROR ERROR !!!!!!!!!!!!' i tried debugging but CompleteTransactions method is not firing
And this is my second json which is bellow and works good
$('#btnTransfareOk').click(function () {
var userName = $('#transfare_username').val();
var amount = $('#transfare_amount').val();
if (userName == '' || amount == '') {
$('#transfare_error_list').html('Please fill boxes.');
} else {
$.ajax({
url: '/Profile/TranfareMoney',
type: 'POST',
data: { ToUsername: userName, Amount: amount },
dataType: 'json',
success: function (result) {
$('#transfare_error_list').html(result.text);
$('#trans_verification_id').val(result.id);
$('#transfare_username').val("");
$('#transfare_amount').val("");
},
error: function () {
$('#transfare_error_list').html('Oops... Error.');
}
});
}
});
I'm not 100% sure, but shouldn't you controller action handler be public ?

Resources