How dsiplay alert message after saving data using Jquery - javascript

Actually i got alert message display before saving data so please help me out
below my code is there
for (var i = 0; i < rows_count; i++) {
var count = 0;
$.ajax({
type: "POST", url: "Default.aspx/update_extraHoursWorked", cache: false, data: "{'empID':'" + $("#emp_id" + i).text() + "','emp_code': '" + $("#emp_code" + i).text() + "','emp_category':'" + $("#emp_category" + i).text() + "','g1': '" + $("#txtgen_Three" + i).val() + "','f1': '" + $("#txtfirst_Three" + i).val() + "','s1': '" + $("#txtsecond_Three" + i).val() + "','t1': '" + $("#txtthrid_Three" + i).val() + "','g2': '" + $("#txtgen_Four" + i).val() + "','f2': '" + $("#txtfirst_Four" + i).val() + "','s2': '" + $("#txtsecond_Four" + i).val() + "','t2': '" + $("#txtthrid_Four" + i).val() + "','g3': '" + $("#txtgen_Five" + i).val() + "','f3': '" + $("#txtfirst_Five" + i).val() + "','s3': '" + $("#txtsecond_Five" + i).val() + "','t3': '" + $("#txtthrid_Five" + i).val() + "','contracortName': '" + $('#ddlContractorNames>option:selected').text() + "'}", contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) { }, error: function (e) { alert('Error, Update att.'); }
});
} enableLastTwoDays(true);
alert('Saved Successfully');
}

You can count every success and finally alert ..
count_success= 0;
for (var i = 0; i < rows_count; i++) {
//---
//--
success: function (data) { count_success++; },
error: function (e) { alert('Error, Update att.'); }
});
} enableLastTwoDays(true);
alert(count_success +'Record Saved Successfully');
}

Try this, the alert should be within the success function, which is called if the ajax request was successful. You can also get the response data from server within this the success function. Try console.log(data) to display data in the browser console if data is returned from the server.
for (var i = 0; i < rows_count; i++) {
var count = 0;
$.ajax({
type: "POST", url: "Default.aspx/update_extraHoursWorked", cache: false, data: "{'empID':'" + $("#emp_id" + i).text() + "','emp_code': '" + $("#emp_code" + i).text() + "','emp_category':'" + $("#emp_category" + i).text() + "','g1': '" + $("#txtgen_Three" + i).val() + "','f1': '" + $("#txtfirst_Three" + i).val() + "','s1': '" + $("#txtsecond_Three" + i).val() + "','t1': '" + $("#txtthrid_Three" + i).val() + "','g2': '" + $("#txtgen_Four" + i).val() + "','f2': '" + $("#txtfirst_Four" + i).val() + "','s2': '" + $("#txtsecond_Four" + i).val() + "','t2': '" + $("#txtthrid_Four" + i).val() + "','g3': '" + $("#txtgen_Five" + i).val() + "','f3': '" + $("#txtfirst_Five" + i).val() + "','s3': '" + $("#txtsecond_Five" + i).val() + "','t3': '" + $("#txtthrid_Five" + i).val() + "','contracortName': '" + $('#ddlContractorNames>option:selected').text() + "'}", contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) { alert('Saved Successfully'); }, error: function (e) { alert('Error, Update att.'); }
});
} enableLastTwoDays(true);
}
The modified code is below, the below code is to give u an idea, ideally this code should not be used in your production site as such. Here for every row that is successfully saved the save function is called which inturn increases the count of the count_successful. After the loop is completed the count of count_successful is checked if its equal to the row count
var count_successful = 0;
for (var i = 0; i < rows_count; i++) {
var count = 0;
$.ajax({
type: "POST", url: "Default.aspx/update_extraHoursWorked", cache: false, data: "{'empID':'" + $("#emp_id" + i).text() + "','emp_code': '" + $("#emp_code" + i).text() + "','emp_category':'" + $("#emp_category" + i).text() + "','g1': '" + $("#txtgen_Three" + i).val() + "','f1': '" + $("#txtfirst_Three" + i).val() + "','s1': '" + $("#txtsecond_Three" + i).val() + "','t1': '" + $("#txtthrid_Three" + i).val() + "','g2': '" + $("#txtgen_Four" + i).val() + "','f2': '" + $("#txtfirst_Four" + i).val() + "','s2': '" + $("#txtsecond_Four" + i).val() + "','t2': '" + $("#txtthrid_Four" + i).val() + "','g3': '" + $("#txtgen_Five" + i).val() + "','f3': '" + $("#txtfirst_Five" + i).val() + "','s3': '" + $("#txtsecond_Five" + i).val() + "','t3': '" + $("#txtthrid_Five" + i).val() + "','contracortName': '" + $('#ddlContractorNames>option:selected').text() + "'}", contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) { count_successful = count_successful+1; }, error: function (e) { alert('Error, Update att.'); }
});
} enableLastTwoDays(true);
}
if(count_successful == rows_count){
alert('Saved all rows successfully');
}

Have a hidden field respective to this function and increment/change the value of it on each success. Finally if the successCount value equals the total rows count, then the alert is shown.
function someFunction() {
for (var i = 0; i < rows_count; i++) {
var count = 0;
$.ajax({
type : "POST",
url : "Default.aspx/update_extraHoursWorked",
cache : false,
data : "{}",
contentType : "application/json; charset=utf-8",
dataType : "json",
success : function(data) {
$('#successCountID').val(i); // changed i+1 to i
},
error : function(e) {
alert("Error, Update att.");
}
});
}
enableLastTwoDays(true);
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
var count = $('#successCountID').val();
if (count == rows_count) {
alert("Saved Successfully");
$('#successCountID').val(0);
}
});
}
Add a hidden field in the form
<input type="hidden" name="successCount" id="successCountID" value="0">

Related

Ajax Request problem, returns undefined 2 out of 3 times

This might be a silly question, but I'm working on a homework project. Most of it is already working, but when I try to write some html with jquery inside an ajax request, two out of three return undefined.
$.ajax({
url: "myurl",
type: "Get",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + userpass));
},
dataType: "json",
}).
done(function (data) {
$('#uebersicht').children(".item").remove();
for (var i = 0; i < data.length; i++) {
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + data[i].id + ")'>" +
data[i].datum + ", " + data[i].Stunden + " Stunden - " + data[i].Anmerkungen + "</p>");
}
});
I tried searching around, but I wasn't very lucky. Probably my searching is just off, but if someone could point me in the right direction I would be very glad.
Any help is appreciated. Thank you in advance.
You'll need to Parse the string data to json after it is received.
.done(function (data) {
var data = JSON.parse(data); // Parse it here
$('#uebersicht').children(".item").remove();
for (var i = 0; i < data.length; i++) {
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + data[i].id + ")'>" +
data[i].datum + ", " + data[i].Stunden + " Stunden - " + data[i].Anmerkungen + "</p>");
}
});
});
// Or you could use the `$.each()` function to loop through the data:
.done(function (data) {
$('#uebersicht').children(".item").remove();
$.each(data, function(item, element){
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + element.id + ")'>" +
element.datum + ", " + element.Stunden + " Stunden - " + element.Anmerkungen + "</p>");
})
});

using javascript how do i put rss feed into a list and show only 4 of them

I have the rss titles going into a dropdown box and they change when each one is clicked on but i want about 4 rss feeds showing on the page so i dont need the dropdown box.
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "rss_warriors.php",
dataType: "xml",
cache: false,
success: parse_rss
});
function parse_rss(rss_feed)
{
console.log(rss_feed);
$('#output').append('<select>');
$(rss_feed).find("item").each(function()
{
$('select').append('<option value="' +
$(this).find('title').text() + '">' +
$(this).find('title').text() + '</option>');
});
line_record(0,rss_feed);
$("select").on("change", function(evt)
{
line_record( $("select option:selected").index(),rss_feed)
});
}
function line_record(sel_index,rss_feed)
{
var local_index = sel_index;
var image_url;
var item_title;
var item_description;
var item_pubDate;
image_url = $(rss_feed).find("item").eq(local_index).find("thumbnail").last().attr("url");
item_title = $(rss_feed).find("item").eq(local_index).find("title").text();
item_description = $(rss_feed).find("item").eq(local_index).find("description").text();
item_pubDate = $(rss_feed).find("item").eq(local_index).find("pubDate").text();
$("#img_warriors").empty();
$("#txt_warriors").empty();
$("#img_warriors").append("<img src='" + image_url + "'>");
$("#txt_warriors").append("<span class='title_large'>" + item_title + "</span>");
$("#txt_warriors").append("<p>" + item_description + "</p>");
$("#txt_warriors").append("<p>" + item_pubDate + "</p>");
}
});
Not sure if it is what you mean, but what about :
$(rss_feed).find("item").each(function(i) {
if (i <=3) {
$('select').append('<option value="' +
$(this).find('title').text() + '">' +
$(this).find('title').text() + '</option>');
}
});

jquery multiselect after change removing selected values

have big problem.
have jquery multiselect plugin from here
$.ajax({
url: 'my url',
type: 'post',
data: {'data': data1, 'data2': 'data2'},
dataType: 'json',
success: function(data){
if(data.length >= 1){
$('#selector').find('option').remove();
$.each(data, function(key, value) {
if ($("#selector option[value='" + value.email + "']").length == 0){
$("#selector").append('<option value="'+ value.email +'" data-id="'+value.id+'" data-name="' + value.name + '" data-surname="' + value.surname + '">'+ value.name + ' ' + value.surname + ' ' + ' (' + value.email + ') sent (' + value.sent + ')' +'</option>').multiselect("destroy").multiselect( { sortable : false } );
}
});
}else{
$('#selector').find('option').remove();
$('#selector').append('').multiselect("destroy").multiselect( { sortable : false } );
}
}
});
and after change (call this function, whitch selecting cantacts from other list) my selected values disapears

How to return a value from javascript function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the following function from where i want to return the htm value however i am getting an undefined. I get a return value as i have checked that already.
function loadData(uid) {
$.ajax({
type: "POST",
url: '<%= page.resolveURL("~")%>Haggler.asmx/getLovedProductsSellerStoreByFbId',
//url: '<%= Page.ResolveUrl("~")%>Haggler.asmx/GetFacebookFriends',
data: '{FacebookId:' + uid + ',pageIndex:' + JSON.stringify(pageIndex) + '}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
// Page parameter to make sure we load new data
success: function (data) {
var myObject = eval('(' + data.d + ')');
//alert('getProductDescription' + JSON.stringify(myObject));
var html = '';
pageIndex++;
var htmlCategoryList = '';
var i = 0, length = myObject.length;
var _productLink = '';
var _productFullLink = '';
if (length > 0) {
pageCount = myObject[0].PageCount;
if (length > 0) {
for (; i < length; i++) {
if (myObject[i].ShippingQuantity > 0) {
_productLink = myObject[i].SellReqID + '/product/' + myObject[i].CurrentNodeName;
_productFullLink = "http://www.xarato.com/" + myObject[i].SellReqID + "/product/" + myObject[i].CurrentNodeName;
if (myObject[i].Discount == 0) {
/**
if (parts[parts.length-1] == 'loves') {
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><a href="/' + _productLink + '"><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].
html += '<li class="polaroid"><div style="position:relative;"><img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '"_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '"><div class="options"><span class="favs" id="span' + myObject[i].SellReqID + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].SellReqID + ')">like it!</span></div></div><div class="prod"><span>' + myObject[i].RequestTitle + '</span></div><div class="prodprice1"><span style="font-weight:700;">Rs. ' + Math.round(parseFloat(myObject[i].MRPrice) + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{ **/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
else {
/**if (parts[parts.length-1] == 'loves') {
var _finalPrice = parseFloat(myObject[i].MRPrice) - (parseFloat(myObject[i].Discount) * parseFloat(myObject[i].MRPrice))/100
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].Preview + '_thumb.jpg" width="200" height="' + myObject[i].Height + '"><div class="options"><span class="favs" id="span' + myObject[i].NodeId + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].NodeId + ')">like it!</span></div><div class="kjss"><span>' + myObject[i].Discount + '% Off</span></div></div><div class="prod"><span>' + myObject[i].NodeName + '</span></div><div class="prodprice1"><span style="color:#777777; text-decoration:line-through">Rs. ' + myObject[i].MRPrice + '</span> <span style="font-weight:700;">Rs. ' + Math.round(_finalPrice + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{**/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
}
}
if (clearHtml) {
// $('.bxslider').html('');
//htm = '<li>"' + html + '"</li>';
}
// var htmli = '<li>"' + html + '"</li>';
// $('.bxslider').append(htmli);
htm = '<li>' + html + '</li>';
alert(htm);
return htm;
clearHtml = false;
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 17, // Optional, the distance between grid items
itemWidth: 225 // Optional, the width of a grid item
};
}
else {
return;
}
}
else {
return;
}
},
failure: function (data) {
alert('failture');
},
error: function (data) {
alert(data.responseText);
}
});
}
This is how i am taking the data but i get an undefined value.
HtmlM += loadData(myObject.data[i].uid);
Please help me out.
Change your loadData to
function loadData(uid, delegate) {
///In ajax instead of return use
delegate(htm);
}
then call like that
loadData(myObject.data[i].uid, function(html){ HtmlM += html ;});
Ajax is asynchronous so you cant just return (yes you can do it synchronous but its not right way)

window.open open in new popup window not in new tab

This is my ajax request
$.ajax({
type: "POST",
url: "Performance.aspx/GenerateMatrix",
data: '{OrgId: ' + $('#hidOrgId').val() + ',SurveyFormId: ' + $('#divMatrixInfo .FeedbackForm').val() + ',GoalId: ' + $('#divMatrixInfo .FeedbackGoal').val() + ',StartDate: ' + "'" + StartDateTime + "'" + ',EndDate: ' + "'" + EndDateTime + "'" + ',EmployeeId: ' + "'" + $('#divMatrixInfo .FeedbackEmployee').val() + "'" + ',QuestionId: ' + "'" + $('#divMatrixInfo .FeedbackQuestion').val() + "'" + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
CloseModelOverLay('divMatrixInfo');
window.open('GenerateMatrix.aspx', '_blank');
$('#ddlPDPView').val('Goals');
$('#ddlPDPView').change();
},
failure: function (response) {
alert(response.d);
}
});
I want to open GenerateMatrix.aspx to open in new tab by this
window.open('GenerateMatrix.aspx', '_blank');
but instead it opens in new pop up window.
try this:
var newWindow = window.open('http://www.example.com','_blank');
$.ajax({
type: "POST",
url: "Performance.aspx/GenerateMatrix",
data: '{OrgId: ' + $('#hidOrgId').val() + ',SurveyFormId: ' + $('#divMatrixInfo .FeedbackForm').val() + ',GoalId: ' + $('#divMatrixInfo .FeedbackGoal').val() + ',StartDate: ' + "'" + StartDateTime + "'" + ',EndDate: ' + "'" + EndDateTime + "'" + ',EmployeeId: ' + "'" + $('#divMatrixInfo .FeedbackEmployee').val() + "'" + ',QuestionId: ' + "'" + $('#divMatrixInfo .FeedbackQuestion').val() + "'" + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
CloseModelOverLay('divMatrixInfo');
newWindow.focus();
$('#ddlPDPView').val('Goals');
$('#ddlPDPView').change();
},
failure: function (response) {
alert(response.d);
}
});

Categories