Calling ajax request after page redirect - javascript

How to call ajax request after page redirecting? I'm trying with setInterval function, but it doesn't work.
$("#list").on('click', 'tr', function () {
var data = table.row( this ).data();
var id = data[0];
var url = 'redirect.html?=id';
window.location.href = url + id;
return false;
var getRequest = setInterval (function(id) {
$.ajax({url: "/list?id=" + id,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
error: function (xhr, status) {
alert(status);
},
success: function (listsdata) {
oTable = $('#table2').DataTable({
data: listsdata,
columns: [
{ title: "Column1" },
{ title: "Column2" },
]
});
}
});
}, 3000);
});
getRequest() method cannot be executed

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;
}

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)
}
});
}

Jquery Autocomplete ajax request only if item from previous ajax request data is not matching

I am using jQuery Autocomplete.
It's making an AJAX request on every keypress which I don't want. If data from a previous AJAX request matches a search it should not make any more AJAX requests.
<script>
$('#tags').autocomplete({
source: function (request, response) {
$.ajax({
url: '/TestDDl/Index',
// data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.user, function (item) {
return {
label: data.name,
val: data.val
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoFocus: true,
keypress: function (event, ui) {
alert('Not Selected');
if (!ui.item) {
alert('Not Selected');
}
}
});
});
Here if I am typing the name of a user which is already in previous AJAX request data, it should not make an AJAX request on next the keypress.
You can declare a variable, assing user input to it, then update it in your success function. And just before making next call, check if your variable matches the next data.
Something like this:
<script>
var recent = '';
$('#tags').autocomplete({
source: function (request, response) {
if (recent == request.term) {
return;
}
recent = request.term;
$.ajax({
url: '/TestDDl/Index',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.user, function (item) {
return {
label: data.name,
val: data.val
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoFocus: true,
keypress: function (event, ui) {
alert('Not Selected');
if (!ui.item) {
alert('Not Selected');
}
}
});
</script>
<script>
window.xyz = []; //For saving history
$('#tags').autocomplete({
source: function (request, response) {
if(xyz[request]){
response(xyz[request]); // Return previously saved data
}else(
$.ajax({
url: '/TestDDl/Index',
// data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var res = $.map(data.user, function (item) {
return {
label: data.name,
val: data.val
}
});
xyz[request]=res; //set data to reuse later
response(res)
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
},
autoFocus: true,
keypress: function (event, ui) {
alert('Not Selected');
if (!ui.item) {
alert('Not Selected');
}
}
});
</script>
Your next ajax reques should be in the Success function of the first ajax request.Buid the logic there.If you find the match don't call the second ajax request else call the second ajax request and all should be in the success function of the first ajax request.

Call $.ajax malfunctioning

I am making a ajax call, but server side code is not hit. Instead control goes to javascript file included in project. Here is my code:
<script type="text/javascript">
function AddEmployee()
{
debugger;
// jQuery.support.cors = true;
$.support.cors = true;
var Product = new Object();
Product.ID = 10;
Product.Name = "kRISH";
Product.Price = "23";
Product.Category = "AS";
// console.log(JSON.stringify({ Name: "kRISH", Price: "23", Category: "AS" }));
var json_text = JSON.stringify(Product,null,2);
**$.ajax**
({
url: 'http://localhost:62310/api/products',
type: 'POST',
data: json_text,
contentType: "application/json;charset=utf-8",
success: function (data) { WriteResponse(data); },
error: function (x, y, z)
{
$('#contentProgress').popup("close");
alert(x.responseText + " " + x.status);
}
});
}
</script>
Is the url correct, why are we not using the relative url here. Can you please try this
$.ajax('http://localhost:62310/api/products', {
type: "post",
data: json_text,
dataType: "json",
cache: false,
contentType: "application/json",
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});

jQuery / Javascript - run AJAX request after X seconds

so I have this code:
$('input.myinput').each(function(){
var id = $(this).val();
var myajax = function(){
$.ajax({
url: ajax_url,
type: "GET",
data: ({
code: id
}),
beforeSend: function() { },
error: function(request){ },
success: function(data) { alert(data); }
});
setTimeout('myajax()', 10000);
}
myajax();
});
I wanted the ajax() request above to run 10 seconds after the page was loaded, so I used setTimeout, but it doesn't work :(
the ajax thingy runs right after the page loads, not 10 secs after...
what am I doing wrong?
$('input.myinput').each(function(){
var id = $(this).val();
var myajax = function() {
$.ajax({
url: ajax_url,
type: "GET",
data: ({
code: id
}),
beforeSend: function() { },
error: function(request){ },
success: function(data) { alert(data); }
});
//if you need to run again every 10 seconds
//setTimeout(myajax, 10000);
};
setTimeout(myajax, 10000);
});
I'd do a few things differently..
function myajax(id) {
$.ajax({
url: ajax_url,
type: "GET",
data: ({
code: id
}),
error: function(request){ },
success: function(data) { alert(data); }
});
setTimeout('myajax(id)', 10000); // you really want it to run AGAIN in another 10 seconds?
}
...
$(document).ready(function() {
$('input.myinput').each(function(){
var id = $(this).val();
setTimeout('myajax(' + id + ')',10000);
});
});
There's no reason to redeclare myajax as a new function for every input, when you can declare it once and pass in a new ID variable each call.

Categories