Looping over ajax requests in a chrome extension, not working - ajax

I was trying loop over the ajax request continuously but it was doing the ajax thing only for the last loop.
while(i<3){
var query = site_url+keywords[i]+'"' ;
$.ajax({
url: query,
type: "GET",
dataType: "html"
success: function(html) {
var el = $(html).find("#tagID");
if(el.length) {
console.log("Element exists");
var cont = 1;
}
else{
console.log("Element doesnt exist");
var cont = 0;
}
}
});
console.log(cont);
i=i+1;
}

Something along those lines:
processKeyword(0);
function processKeyword(i) {
if(i < keywords.length) {
var query = site_url+keywords[i]+'"' ;
$.ajax({
url: query,
type: "GET",
dataType: "html"
success: function(html) {
var el = $(html).find("#tagID");
if(el.length) {
//found, stop processing
result(i);
} else{
//not found, process next
processKeyword(i + 1);
}
}
});
} else {
//all processed, nothing found
result(-1);
}
}
function result(i) {
//i contains keyword index if was found, -1 otherwise
}

Related

Ajax GET call in a razor page not breaking inside the method in the controller

I have the following javascript using ajax:
function MoveToWeek(weekIndex) {
if (weekIndex == 1) {
var index = #Model.WeekIndex;
index = index+1;
$.ajax({
url: '#Url.Action("RenderCalendar", "Calendar")',
data: { weekIndex: index },
type: "GET",
success: function (data) {
$("#RenderCalendarArea").html(data);
}
});
}
else if (weekIndex == -1) {
var index = #Model.WeekIndex;
index = index+-1;
$.ajax({
url: '#Url.Action("RenderCalendar", "Calendar")',
data: { weekIndex: index},
type: 'GET',
success: function (data) {
$('#RenderCalendarArea').html(data);
}
});
}
}
And the following method in my controller "CalendarController":
[HttpGet]
public ActionResult RenderCalendar(int weekIndex = 0)
{
//..snip
}
I have confirmed the ajax code runs (if I put a javascript breakpoint on the $.ajax line, it'll break there). In addition the values in the ajax method do seem to be set correctly. In the debugger the javascript method has been compiled as such:
function MoveToWeek(weekIndex) {
if (weekIndex == 1) {
var index = 0;
index = index+1;
$.ajax({
url: '/Calendar/RenderCalendar',
data: { weekIndex: index },
type: "GET",
success: function (data) {
$("#RenderCalendarArea").html(data);
}
});
}
else if (weekIndex == -1) {
var index = 0;
index = index+-1;
$.ajax({
url: '/Calendar/RenderCalendar',
data: { weekIndex: index},
type: 'GET',
success: function (data) {
$('#RenderCalendarArea').html(data);
}
});
}
}
However, when this code runs, it does not break inside the method in the controller. Can anyone see why this doesn't work?
This particular partial view didn't use the layout file... which meant it didn't import the jquery lib. That's why it didn't work. Ooops.

How to return the AJAX value in extJS?

I am calling AJAX request and getting the value as well as a response but I want to return the value and store in a variable. I tried so many ways but its not working. PFB the code snippet.
submitRequest: function(type, url) {
var maxValue = this.getMaxValue(PORTALURL.EXCEPTION.MAX_VALUE);
if(grid.getSelectionModel().getSelection().length > maxValue){
Ext.Msg.alert('Alert!', type + ' count is more than 10');
return;
}
},
getMaxValue : function(url){
Ext.Ajax.request({
url: url,
success: function(response) {
var result = Ext.decode(response.responseText);
//callback(result); Not working
// return result; Not Working
}
});
}
How I can get the value in var maxValue ?
Appreciate all your help.
Starting from Ext JS 6 you may also use promises with Ext.Ajax.request() out of the box which may help you to organise your code in a more 'straightforward' way and get rid of a so-called 'callback hell'.
submitRequest: function(type, url) {
this.getMaxValue(PORTALURL.EXCEPTION.MAX_VALUE).then(function(response) {
var maxValue = Ext.decode(response.responseText);
if (grid.getSelectionModel().getSelection().length > maxValue){
Ext.Msg.alert('Alert!', type + ' count is more than 10');
return;
}
}).done();
},
getMaxValue : function(url) {
return Ext.Ajax.request({
url: url,
...
})
}
For the further reading I would recommend you the following article https://www.sencha.com/blog/asynchronous-javascript-promises/
As an Ajax request is asynchrone you can use a callback:
submitRequest: function(type, url) {
this.getMaxValue(PORTALURL.EXCEPTION.MAX_VALUE, function(maxValue){ // <<== Your callback
if(grid.getSelectionModel().getSelection().length > maxValue){
Ext.Msg.alert('Alert!', type + ' count is more than 10');
return;
}
});
},
getMaxValue : function(url, callback){
Ext.Ajax.request({
url: url,
success: function(response) {
var result = Ext.decode(response.responseText);
callback(result);
}
});
}

ExtJS 3.4.0 Wait for Ajax Response

I need to assign the response value for return it in a Javascript function using ExtJS 3.4.0 library, the function naturally terminates without waiting for ajax response so the value of count is always zero, I need to know if I can do it this way or if there is an alternative.
Thanks
function test() {
var count = 0;
Ext.Ajax.request({
url: "/Controller/Action",
method: "POST",
success: function(response) {
count = Ext.decode(response.responseText);
}
});
if (count > 1) {
return false;
}
return true;
}
You need to add return statement in you success function :
function test() {
var count = 0;
Ext.Ajax.request({
url: "/Controller/Action",
method: "POST",
success: function(response) {
count = Ext.decode(response.responseText);
if (count > 1) {
this.other(false);
}
this.other(true);
},
scope: this
});
},
function other(param){
console.log(param);
}

Passing AJAX request in MVC3 environment

I was using MVC3 with AJAX. I was using AJAX within another AJAX. For the first AJAX request, it properly sends to the controller with data. But after returning from the AJAX request, I again posting the same data to another action. But second time the data comes null when coming to the controller. Please help me to fix this issue.
Code
$(document).ready(function () {
$('.deleteitems').live('click', function (e) {
var items = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items.push($(this).attr("Id"));
});
var json = JSON.stringify(items);
var perm = $("#Permission").val();
if (items.length != 0) {
if (perm == "True") {
$.ajax({
url: '/ItemControl/ItemControl/Catalogue_Check',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data == "S") {
DelBibsAlso();
}
else {
DelItemsonly();
}
}
});
}
else {
$("#divMes").removeClass("Success");
$("#divMes").addClass("Error");
showError("Sorry you dont have Permission!");
}
}
else {
alert("Select any Items to delete");
e.preventDefault();
}
});
});
function DelItemsonly() {
var items2 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items2.push($(this).attr("Id"));
});
var itemjson = JSON.stringify(items2);
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": itemjson, "DelBib": 0 },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
function DelBibsAlso() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
var bibjson = JSON.stringify(items1);
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": bibjson, "DelBib": cond },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
Controller Code
public ActionResult Catalogue_Check(string[] id)
{
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
var Matched_BibID = (from asd in Db.Items
where ints.Contains(asd.Id)
select asd.BibId).ToList();
foreach (var idd in ints)
{
var bibid = (from bib in Db.Items where bib.Id == idd select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
return Json("S", JsonRequestBehavior.AllowGet);
}
}
return Json("N", JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteItems(string[] id, int? DelBib)
{
//var newid = id.Split(',');
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
foreach (var a in id)
{
int sel = Convert.ToInt32(a);
Item item = Db.Items.Single(i => i.Id == sel);
int Sess = Convert.ToInt16(Session["AccId"]);
string AdminName = User.Identity.Name;
bool Exist = Db.RouteOuts.Any(itm => itm.ItemId == item.Id);
if (!Exist)
{
weed.DeleteIt(item, Sess, AdminName);
var bibid = (from bib in Db.Items where bib.Id == item.Id select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
Db.ExecuteStoreCommand("update Bibs set Status= 'D' where Id={0}", item.BibId);
Db.SaveChanges();
}
}
}
return Json("S", JsonRequestBehavior.AllowGet);
}
function Test() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
//var bibjson = JSON.stringify(items1); **** Loose this line ****
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ "id": items1, "DelBib": cond }), // **** Items are stringified before posting ****
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});enter code here
}
else {
e.preventDefault();
}

Jquery and live act wired but act ok after force refresh in IE

somthing is wrong with my code and i can't get what it is...
i have a div id = "personaltab"
i have a form in side it to login the user with username and password. if success the jquery empty the div and puts in the form of the bidding.
if the user try to bid the other ajax that assign to the button is working but for some reason skips the empty and just adding the responded ajax to the div
i have checked that in IE and chrome and it is working fine in chrome
here are my codes
$("#login").click(function() {
var id = $("input#pid").val();
var user = $("input#puser").val();
var pass = $("input#ppass").val();
var dataString = 'id='+ id + '&user='+ user + '&pass=' + pass;
if (user == "") {
alert("error");
$("input#puser").focus();
return false;
}
if (pass == "") {
alert("error");
$("input#ppass").focus();
return false;
}
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
if (msg=="False") {
alert("error");
$("#personaltab").show();
}
else {
$("#personaltab").fadeOut("normal",function(){
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").slideDown();
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
return false;
});
$("#sendbid").live("click", function(){
var startat = $("input[name=startat]").val();
var sprice = $("input[name=sprice]").val();
if (parseInt(sprice)<=parseInt(startat)) {
alert("error");
$("input[name=sprice]").focus();
return false;
}
else {
var payment = $("select[name=payment]").val();
if ($('input[name=credit]').is(':checked') ){
var credit = true;
}
var prodid = $("input[name=id]").val();
var dataString = 'id='+ prodid + '&price='+ sprice + '&payment=' + payment + '&credit=' + credit;
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
}
return false;
});
Solved:
i had inside a and for some reason the div that need to get the ajax by his id was duplicated
don't ask :-)

Resources