Loading AJAX calls one after the other - javascript

I have the following 3 AJAX function, and the problem is that it loads sessionAllCoursePage3 first then sessionAllCoursePage2 then sessionAllCoursePage1, I wanted to be inverse. I want to ensure that page1 is loaded first, then page 2, page 3, etc.
// Retrieve last 9 session
$.ajax({
type: "POST",
data: { run: true, providerName: $('#providerName').val() },
url: '/app/functions/sessionAllCoursePage1.php',
cache: false,
success: function(response) {
// Response is value returned from php
$('#contentPage1').html(response);
return false;
}
});
// Retrieve the next 9 session
$.ajax({
type: "POST",
data: { run: true, providerName: $('#providerName').val() },
url: '/app/functions/sessionAllCoursePage2.php',
cache: false,
success: function(response) {
// Response is value returned from php
$('#contentPage2').html(response);
return false;
}
});
// Retrieve the next 9 session
$.ajax({
type: "POST",
data: { run: true, providerName: $('#providerName').val() },
url: '/app/functions/sessionAllCoursePage3.php',
cache: false,
success: function(response) {
// Response is value returned from php
$('#contentPage3').html(response);
return false;
}
});

I'd suggest you chain them with promises:
// Retrieve last 9 session
$.ajax({
type: "POST",
data: {
run: true,
providerName: $('#providerName').val()
},
url: '/app/functions/sessionAllCoursePage1.php',
cache: false
}).then(function(response) {
$('#contentPage1').html(response);
return $.ajax({
type: "POST",
data: {
run: true,
providerName: $('#providerName').val()
},
url: '/app/functions/sessionAllCoursePage2.php',
cache: false
}).then(function(response) {
$('#contentPage2').html(response);
return $.ajax({
type: "POST",
data: {
run: true,
providerName: $('#providerName').val()
},
url: '/app/functions/sessionAllCoursePage3.php',
cache: false
});
}).then(function(response) {
$('#contentPage3').html(response);
});
Or, using a little more shared code:
function ajaxCommon(url, resultId) {
return $.ajax({
type: "POST",
url: url,
data: {
run: true,
providerName: $('#providerName').val()
},
cache: false
}).then(function(result) {
$("#" + resultId).html(result);
});
}
ajaxCommon('/app/functions/sessionAllCoursePage1.php', 'contentPage1').then(function() {
return ajaxCommon('/app/functions/sessionAllCoursePage2.php', 'contentPage2');
}).then(function() {
return ajaxCommon('/app/functions/sessionAllCoursePage3.php', 'contentPage3');
});
Or, a little more table/loop driven:
function ajaxCommon(url, resultId) {
return $.ajax({
type: "POST",
url: url,
data: {run: true, providerName: $('#providerName').val()},
cache: false
}).then(function(result) {
$("#" + resultId).html(result);
});
}
[1,2,3].reduce(function(p, item) {
return p.then(function() {
return ajaxCommon('/app/functions/sessionAllCoursePage' + item + '.php', 'contentPage' + item);
});
}, Promise.resolve());

Just place your asynchronous code inside some request callback (e.g. success). Didactically:
var firstRequestOptions = {
success: function () {
secondRequest();
}
};
var secondRequestOptions = {
success: function () {
thirdRequest();
}
};
var thirdRequestOptions = {
success: function () {
firstRequest();
}
};
var firstRequest = function () {
console.log('request 1');
$.ajax(firstRequestOptions);
};
var secondRequest = function () {
console.log('request 2');
$.ajax(secondRequestOptions);
};
var thirdRequest = function () {
console.log('request 3');
$.ajax(thirdRequestOptions);
};
Then:
firstRequest();
The log should be:
> request 1
> request 2
> request 3
> request 1
> request 2
...

You can use Array.prototype.shift(), String.prototype.match() with Regexp /\d/ to match digit character in url, .then()
function request(url) {
return $.ajax({
type: "POST",
data: {run: true, providerName: $('#providerName').val()},
url: url,
cache:false,
success: function (response) {
$('#contentPage' + url.match(/\d/)[0]).html(response);
}
});
}
var urls = ['/app/functions/sessionAllCoursePage1.php'
, '/app/functions/sessionAllCoursePage2.php'
, '/app/functions/sessionAllCoursePage3.php'];
request(urls.shift())
.then(function re() {
if (urls.length) {
request(urls.shift()).then(re)
}
})
// can use `.catch()` here at jQuery 3.0+
.fail(function(jqxhr, textStatus, errorThrown) {
// handle error
console.log(errorThrown);
});
plnkr http://plnkr.co/edit/fREO6Jzw65gq2s3jrwjp?p=preview

Related

send ajax and if there's a specific object in json response send next request to this object

i want to send ajax request to a url and the response is json its has 2 object ; first is group_id second object is next_page. i want to send next ajax request if isset next_page and request url will be next_page value if there isn't next_page stop ajax requesting.
this is my javascript code but not working :
$("#getUsersId").on('submit', function(e){
e.preventDefault();
var Keyword = $('#Keyword').val();
var fbAcc = $("#fbAccs").val();
$.ajax({
type: 'POST',
url: 'exGoupsReq.php',
data:{Keyword: Keyword,fb_acc: fbAcc},
dataType: 'json',
beforeSend: function(){
$('.submitBtn').attr("disabled","disabled");
$('#addFbAcc').css("opacity",".5");
},
success: function(response){
$('.successMSG').html('');
if(response[0].next_page){
console.log(response[0].next_page);
// if is set next_page then send ajax request to next_page
$.ajax({
type: 'POST',
url: 'exGoupsReq.php?next='+response[0].next_page,
data:{Keyword: Keyword,fb_acc: fbAcc},
dataType: 'json',
beforeSend: function(){
},
success: function(response2){
if(response[0].next_page){
$.ajax({
type: 'POST',
url: 'exGoupsReq.php?next='+response2[0].next_page,
data:{Keyword: Keyword,fb_acc: fbAcc},
dataType: 'json',
beforeSend: function(){
},
success: function(response){
}
});
}
}
});
}else{
$('.successMSG').html(
Swal.fire({
icon: 'danger',
title: response.message,
showConfirmButton: false,
timer: 2000,
timerProgressBar: true
}).then(function(isConfirm) {
if (isConfirm) {
} else {
//if no clicked => do something else
}
})
);
}
$('#addFbAcc').css("opacity","");
$(".submitBtn").removeAttr("disabled");
}
});
});
and this is the json response:
[{"group_id":"3227753957460161","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"634745371303934","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"623523731538627","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"874339386716003","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"327802997885129","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"1213445152028414","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"310298904216864","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"2630210850348811","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"234662357739095","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"591588044857727","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"3348702175450922","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"101162043569757","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"},{"group_id":"2287318904779687","next_page":"/smm/nextpage.php?id=jkldt5u437VpRx57AZF_SwJok0Qj5Nkcma8LUb_AKz1agfMs_5YFb1Gf2cI2_6t8fSrE_fqZ-cbex-CIJf4meZjFWkBU87OnJrxUP6wWdGkV4kOqCexzbBpjEXQVwKzg8H7XAJw2ZfHLbCvacn1Q9I6Hh4C0Z6sD_eVOaPyTMWqVZsA&pn=2&usid=34fcde099323ec03cc2630d7e4b36988&tsid&refid=46"}]
I've modified your code so that it uses a recursive function. That means that whenever there is a next page, it will fetch it and keeps doing this untill there are no more next pages to fetch.
async function scrapePage(url, data = {}) {
const response = await $.ajax({
url,
data,
type: "POST",
dataType: "json",
});
// If there is no next page, show the error.
const nextPage = response[0]?.next_page;
if (typeof nextPage === 'undefined') {
$(".successMSG").html(
Swal.fire({
icon: "danger",
title: "No more pages",
showConfirmButton: false,
timer: 2000,
timerProgressBar: true,
}).then(function (isConfirm) {
if (isConfirm) {
} else {
//if no clicked => do something else
}
})
);
return;
}
// Otherwise scrape the next page.
await scrapePage(nextPage, data);
}
$("#getUsersId").on("submit", async function (e) {
e.preventDefault();
var keyword = $("#Keyword").val();
var fbAcc = $("#fbAccs").val();
const data = {
Keyword: keyword,
fb_acc: fbAcc
};
$(".submitBtn").attr("disabled", "disabled");
await scrapePage("exGoupsReq.php", data);
$(".submitBtn").removeAttr("disabled");
});
.submitBtn:disabled {
opacity: 0.5;
}

How to avoid repeating the same $.ajax() call

I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work

ReferenceError: response is not defined on autocomplete jquery ajax call in singleton design pattern

I am trying to implement jQuery autocomplete in my solution but I got an error ReferenceError: response is not defined
Here is my code
(function ($) {
$.SupportArticleObj = function (p) {
var SupportArticle = {
config: {
isPostBack: false,
async: false,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: { data: '' },
dataType: 'json',
baseURL: "Modules/SupportArticle/Services/SupportArticleWebService.asmx/",
url: "",
method: "",
ajaxCallMode: 0,
PortalID: PortalID,
UserModuleID: UserModuleID,
SecureToken: SecureToken,
UserName: UserName
},
init: function () {
$("#searchSupport").autocomplete({
source: function (request, response) {
searchTerm = request.term;
SupportArticle.getSearchData(searchTerm);
}
});
},
getSearchData: function (searchTearm) {
SupportArticle.config.method = "SearchSupportArticle";
SupportArticle.config.url = SupportArticle.config.baseURL + SupportArticle.config.method;
SupportArticle.config.data = JSON2.stringify({
searchTerm: searchTerm,
portalID: SupportArticle.config.PortalID,
userModuleID: SupportArticle.config.UserModuleID,
userName: SupportArticle.config.UserName,
secureToken: SupportArticle.config.SecureToken
});
SupportArticle.ajaxCall(SupportArticle.config);
},
ajaxSuccess: function (data) {
response(data);
},
ajaxFailure: function () {
jAlert('Somethings went wrong', 'Support Article');
},
ajaxCall: function (config) {
$.ajax({
type: SupportArticle.config.type,
contentType: SupportArticle.config.contentType,
cache: SupportArticle.config.cache,
url: SupportArticle.config.url,
data: SupportArticle.config.data,
dataType: SupportArticle.config.dataType,
success: SupportArticle.ajaxSuccess,
error: SupportArticle.ajaxFailure,
async: SupportArticle.config.async
});
}
};
SupportArticle.init();
};
$.fn.callSupportArticle = function (p) {
$.SupportArticleObj(p);
};
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
What I am trying to do here is, I am calling a webservice which will search the records on database and return as a list and I want to bind that list on textbox as a autocomplete. But the problem is while running the solution in browser I got an error ReferenceError: response is not defined.
I was trying http://www.c-sharpcorner.com/UploadFile/da55bf/Asp-Net-autocomplete-textbox-using-jquery-json-and-ajax/ as reference.
How can I solve the issue of ReferenceError: response is not defined
Write your script like below:
AutoDemoDataBase: function () {
$("#lytA_ctl29_txtSearchName").autocomplete({
source: function (request, response) {
var param = JSON.stringify({
userModuleID: UserModuleID,
portalID: autoComplete.config.portalId,
prefix: $("#lytA_ctl29_txtSearchName").val(),
userName: autoComplete.config.UserName,
secureToken: SageFrameSecureToken
});
$.ajax({
type: autoComplete.config.type,
contentType: autoComplete.config.contentType,
cache: autoComplete.config.cache,
url: autoComplete.config.baseURL + "GetNames",
data: param,
dataType: autoComplete.config.dataType,
async: autoComplete.config.async,
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (response) {
jAlert(response.responseText);
},
failure: function (response) {
jAlert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfId").val(i.item.val);
$('#test').text(i.item.val);
},
minLength: 1
});
}
Your ajax success function is out of response scope.

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

ajax call not working with in ajax

I using the mvc controller with ajax. I perfom the task using the jquery confirm box. when i click the "ok" button its needs to the call another ajax and its link to the another controller but its not working
Sample code:
function button_click() {
$.ajax({
type: 'POST',
url: 'url',
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { call(data); }
else { alert(data.data); }
}
});
}
function call(data)
{
var ans = confirm(data)
if(ans)
{
$.ajax({
type: 'POST',
url: '#(Url.Action("StudentList", new { Area = "Mec", Controller = "HOD" }))',, // this url not goes to the controller
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { alert(data.data); }
else { }
}
});
} else { }
}
i have tried your code but it worked for me.the difference is that
you need to pass data in correct format. data:data or data:{ data:data } but not data:{data}
function button_click() {
$.ajax({
type: 'POST',
url: 'Demo/Demo_action',
data: { data: "what you want to pass" },
//dataType: 'json',
//contentType: 'application/json',
success: function (data) {
if (data == "hello") {
call(data);
}
}
});
}
function call(data) {
var ans = confirm(data)
if (ans) {
$.ajax({
type: 'POST',
url: '#(Url.Action("Demo_action2", new { Area = "Mec", Controller = "Home" }))',
//url: 'Home/Demo_action2', // this url not goes to the controller
data: { data: data },
dataType: 'json',
success: function (data) {
alert(data);
}
});
}
else
{ }
}

Categories