Execute Ajax queries one after one with Jquery - javascript

I'm trying to execute ajax post requests one after one and stop only when the result is something like "done". But I can't figure out why it is not looping...I get a json answer but I can't do anything with success response.
My code so far:
var index = 0;
function crawler(textarea) {
index = 0;
if(url != ''){
if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(url)){
execute_queue(index);
}
}
};
function execute_queue(index)
{
url = strip_tags($('#input-website').val().trim());
folders = strip_tags($('#excluded-folders').val().trim());
$.ajax( {
url: 'xxx',
cache: false,
type : 'POST',
async: false,
data: {url:url, folders:folders, current:index},
success: function(response)
{
index++;
execute_queue(index);
}
});
};
Thanks in advance for your help.

You should check if the request failed, this is straight from the JQuery manaual:
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
More info found here, success will not be called if the URL responds with an error.
UPDATE:
I think your code should look something like this:
var index = 0;
function crawler(textarea) {
index = 0;
if(url != ''){
if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(url)){
execute_queue(index);
}
}
};
function execute_queue(index)
{
url = strip_tags($('#input-website').val().trim());
folders = strip_tags($('#excluded-folders').val().trim());
$.ajax( {
url: 'xxx',
cache: false,
type : 'POST',
data: {url:url, folders:folders, current:index},
success: function(response)
{
index++;
execute_queue(index);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + " : " + errorThrown);
}
});
};

Related

AJAX POST Request execute only first call on safari

$('#course_id').change(function() {
var courseid = $(this).val();
getuniqueid(courseid);
//alert(courseid);
});
function getuniqueid(courseid){
if (courseid == '0')
{
alert("Please select the Course.");
document.getElementById("course_id").value = "<?php echo $id ?>";
document.getElementById("course_id").focus();
return false;
}
$.ajax({
type: "POST",
url: 'createuniqueid.php',
data: {
courseid:courseid
},
datatype:'json',
cache: false,
success: function( data ) {
//alert(data);
$('#custom').val(data);
console.log("success");
}
});
}
function coupon_submit(elm){
var sender_name = document.getElementById("sender_name").value;
var sender_email_id = document.getElementById("sender_email_id").value;
var receiver_name = document.getElementById("receiver_name").value;
var receiver_email_id= document.getElementById("receiver_email_id").value;
var courseid = document.getElementById("course_id").value;
var uniqueid = document.getElementById("custom").value;
$.ajax({
type: "POST",
url: "datastring.php",
data: { sender_name: sender_name,
sender_email_id: sender_email_id,
receiver_name: receiver_name,
receiver_email_id:receiver_email_id,
courseid:courseid,
uniqueid:uniqueid
},
cache: false,
success: function( data ) {
alert(data);
console.log("success....");
},
error: function(jqXHR, textStatus, errorThrown,data) {
console.log("error. textStatus: %s errorThrown: %s", textStatus, errorThrown);
}
});
}
It works fine on chrome, IE, Firefox but not on Safari. On Safari it executes only first AJAX call.
I need to call first getuniqueid and then coupon_submit. But for debugging process I placed coupon_submit function's code in getuniqueid function, the code of datastring.php get executed. Means it executes first AJAX call only.
Appriciate any help in advance!!

I have two very similar functions but only one works

Why does the first function work and not the second one? Both of the functions are within the same script statement. When I run the second function on my webpage it doesn't even get past the ajax statement but I am not sure what the actual problem is with it as I used the same template as the first function. Also please bear in mind I am very new to the Java API.
function summonerLookUp() {
SUMMONER_NAME = $("#userName").val();
if (SUMMONER_NAME !== "") {
$.ajax({
url: 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' + SUMMONER_NAME + '?api_key=RGAPI-F6099CCD-E674-478D-B9BF-2090B52A116C',
type: 'GET',
dataType: 'json',
data: {
},
success: function (json) {
SUMMONER_NAME_NOSPACES = SUMMONER_NAME.replace(" ", "");
SUMMONER_NAME_NOSPACES = SUMMONER_NAME_NOSPACES.toLowerCase().trim();
summonerLevel = json[SUMMONER_NAME_NOSPACES].summonerLevel;
summonerID = json[SUMMONER_NAME_NOSPACES].id;
document.getElementById("sLevel").innerHTML = summonerLevel;
document.getElementById("sID").innerHTML = summonerID;
sumName = json[SUMMONER_NAME_NOSPACES].name;
sumID = json[SUMMONER_NAME_NOSPACES].id
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error getting Summoner data!");
}
});
} else {}
}
function getMasteryData() {
SUMMONER_NAME = $("#userName").val();
sumID = string(sumID);
if (SUMMONER_NAME !== "") {
$.ajax({
url: 'https://euw.api.pvp.net/championmastery/location/EUW1/player/' + sumID + '/champions?api_key=RGAPI-F6099CCD-E674-478D-B9BF-2090B52A116C',
type: 'GET',
dataType: 'json',
data: {
},
success: function (json) {
bestchampid = json[0].championId;
document.getElementById("bcID").innerHTML = bestchampid;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error getting Summoner data for the ID!");
}
});
} else {}
}
Sorry for bad formatting but I hope you can understand it.
You should remove this line from the second function
sumID = string(sumID);
as there is no default function named string. Use String() instead.

ajax not called..even alerts are not working

i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});

how to stop ajax request if another request exist

i'm trying to make infinite scrolling so when scrolling i make an ajax request to the server to get data but when scrolling a multiple ajax request is made and return the same data so how can i cancel ajax request before sending if there one already exist i tried like this
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
all my code
var lock_load = '1';
var activeAjaxConnections = 1;
var PageNumber = 2;
$(window).scroll(function () {
if ((Math.ceil($(window).scrollTop() - $(window).height()) * -1) <= getHeight() + 550) {
if (lock_load === '1') {
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
alert(errorThrown);
n }
});
}
}
});
but it give an error xhr is undefined pleas any help and many thanks in advance.
Try flags
Before making ajax call set flag to true and after ajax call is made set flag to false, finally on completion of ajax request again set flag to ture
var ready = true;
$(window).scroll(function(){
if(ready == true){
ready = false;
$.ajax({
url: "/pagination",
cache: false,
success: function (response){
//response
}
}).always(function () {
ready = true; //Reset the flag here
});
}
});
use the below code, use a simple flag variable that will be set to false by the defualt, that is to say that ajax call is not occuring once if condition is met then it will set to true to say that ajax call has started, once the success: or error: call back fires the variable will be set to false so that another ajax call can be made.
startedAjax = false;
if (lock_load === '1') {
startedAjax = true;
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
startedAjax = false //set is false
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
startedAjax = false;
alert(errorThrown);
}
});
}
}
});

jQuery $.ajax(), pass success data into separate function

I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.
Here is what I was thinking would work, but it is not:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: callback
});
}
Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:
testFunc('my string data', function(data){
alert(data);
});
I am wanting this to be the same as:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
}
Works fine for me:
<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
}
var test = function(str, cb) {
var data = 'Input values';
$.ajax({
type: 'post',
url: 'http://www.mydomain.com/ajaxscript',
data: data,
success: cb
});
}
test('Hello, world', callback);
</script>
You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}
this is how I do it
function run_ajax(obj) {
$.ajax({
type:"POST",
url: prefix,
data: obj.pdata,
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
if(obj.func){
obj.func(data);
}
}
});
}
alert_func(data){
//do what you want with data
}
var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);
In the first code block, you're never using the str parameter. Did you mean to say the following?
testFunc = function(str, callback) {
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: str,
success: callback
});
}
I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)
Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:
function GetProcedureById(procedureId)
{
var includeMaster = true;
pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pString,
datatype: "json",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
success: function(msg)
{
LoadProcedure(msg);
},
failure: function(msg)
{
// $("#sometextplace").text("Procedure did not load");
}
});
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
if (jdata.length < 10)
{
$("select#cptIcdProcedureSelect").attr('size', jdata.length);
}
else
{
$("select#cptIcdProcedureSelect").attr('size', '10');
};
var options = '';
for (var i = 0; i < jdata.length; i++)
{
options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
};
$("select#cptIcdProcedureSelect").html(options);
};

Categories

Resources