How to use for loop in ajax success function? - ajax

This is my alert output result:
The above picture array is my result that is get from table using ajax request.but i don't know how to use in for loop and i have tired in for loop the value is splitted one by one like
My code
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
alert(data);
var result = data;
var arr = result;
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
}
});
});
</script>

You can modify your script like this and then do whatever Logic you want for the response
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
myGoodFunctionToHandleResponse(data);
}
});
});
function myGoodFunctionToHandleResponse(data){
for(let i in data){
console.log(data[i]);
}
}

I have forgot to put JSON.parse() this function after success function and so i didn't get the correct result so far.
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
var result = JSON.parse(data)
var mycars = result;
for (i in mycars)
{
if( mycars[i].dc == "C"){
var credit = mycars[i].Amt;
}
else{
var debit = mycars[i].Amt;
}
if(credit > debit)
{
var bal = credit - debit;
}
else{
var bal = debit - credit;
}
}
$('#bal').val(bal);
}
});
});
</script>

Related

syntaxerror missing } after property list

<script>
function changeProgram(val){
$.ajax({
type: "POST",
url: "getSemester?pro=NULL",
data: {pro: val, staff_id: $('#staff_id').val(),
success: function(data) {
var new_data = $.parseJSON(data);
if(new_data.length>0 ){
var dom ="<option value=''>SELECT</option>";
for(var index = 0; index < new_data.length; index++) {
dom += "<option value='"+new_data[index].SM_SEMESTER_CODE+"'>"+new_data[index].STOTAL+" - "+new_data[index].SM_SEMESTER_DESC+"</option>";
}
$(".semesterGroup").html(dom);
}else{
var dom ="<option value=''>SELECT</option>";
$(".semesterGroup").html(dom);
}
}
});
}
</script>
Easy fix.
Just a missing bracket on this line
data: {pro: val, staff_id: $('#staff_id').val()} <--- ,
You are missing } for data:
Here is the solution code -
function changeProgram(val){
$.ajax({
type: "POST",
url: "getSemester?pro=NULL",
data: {pro: val, staff_id: $('#staff_id').val()},
success: function(data) {
var new_data = $.parseJSON(data);
if(new_data.length>0 ){
var dom ="<option value=''>SELECT</option>";
for(var index = 0; index < new_data.length; index++) {
dom += "<option value='"+new_data[index].SM_SEMESTER_CODE+"'>"+new_data[index].STOTAL+" - "+new_data[index].SM_SEMESTER_DESC+"</option>";
}
$(".semesterGroup").html(dom);
}else{
var dom ="<option value=''>SELECT</option>";
$(".semesterGroup").html(dom);
}
}
});
}

css Property for jquery ajax success function

I'm working with MVC3, using the following jQuery AJAX call:
function Displaymaingrid () {
var Geo = $('#ddlGeo').val();
var Vertical = $('#ddlVertical').val();
var Month = $('#ddlMonth').val();
if(Vertical == "All")
{
var Flag = 1;
}
else
{
var Flag = 2;
}
$.ajax({
url: "#Url.Action("TRUnutilizedOwnershipChange", "TravelReady")",
datatype: "html",
type: "post",
data: {strGeo:Geo, strVertical:Vertical, intMonth:Month, intFlag:Flag},
error: function(){},
success: function(data){
$('.travTableContent').empty();
var text3 = data.data.lstunutilizedownershipentities;
for( var item in text3)
{
$('<tr />').html(text3[item]).appendTo('.travTableContent');
$('<td />').html(text3[item].CurrentOwnership).appendTo('.travTableContent');
$('<td />').html('' + text3[item].cnt + '').appendTo('.travTableContent');
}
}
});
}
I want to set the CSS property for success function:
$('<tr />').html(text3[item]).appendTo('.travTableContent');
I want to add the following CSS property in the above line:
("tr:odd").css("background-color", "#d0d1e2")
Where do I need to insert this line?
Add it after the "for" statement.
for( var item in text3){
$('<tr />').html(text3[item]).appendTo('.travTableContent');
$('<td />').html(text3[item].CurrentOwnership).appendTo('.travTableContent');
$('<td />').html('' + text3[item].cnt + '').appendTo('.travTableContent');
}
$("tr:odd").css("background-color", "#d0d1e2");

where I shall give the parameter in ajax get?

this is my controller action that returns json
public ActionResult MapTest(string date)
{
var locations = _db.EMP_LOCATION.Where(m => m.CURRENT_DATE.Equals(date));
return Json(locations,JsonRequestBehavior.AllowGet);
}
My scrip is here
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
Now my question is where i can give date parameter in $.ajax and how?
Just do something like:
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
data: JSON.stringify({ date: "your date" })
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
Best Regards
You can pass the value in URL like below :
var script = {
callAction: function () {
var dateVal= "Your date";
$.ajax({
url: 'Home/MapTest?date='+dateVal,
type:'GET',
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
dataType: "html",
data: { date : "03/25/2013" },
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}

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

Looping over ajax requests in a chrome extension, not working

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
}

Resources