Async post fails on first try, works on second - javascript

I'd like to retrieve a value from a database, but it seems like my ajax_update2() function reads the previous data and not the current data. I've set async:false in runMon2() before calling ajax_update2(). It only works the second time.
Note: I'm using IE11.
function runMon2() {
$("#btnStop").show();
$("#btnStart").hide();
$("#msgz").html("");
$.ajax({
type: "POST",
url: "stage2.aspx/s3_monte_carlo_run_thread",
data: '{id: "' + <%= id%> + '",no_cycles:"' + $("#cycles").val() + '",covSmys:"' + $("#covSmys").val() + '",covT:"' + $("#covT").val() + '",covL:"' + $("#covL").val() + '",covD:"' + $("#covD").val() + '", D:"' + <%= D%> + '",L: "' + <%= L%> + '",T: "' + <%= T%> + '",Pa: "' + <%= Pa%> + '",UTS: "' + <%= UTS%> + '",SMYS: "' + <%= SMYS%> + '",assess_type:"' + $("#assess_type").val() + '",year: "' + <%=year%> + '" }',
dataType: 'json',
async: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
successmessage = 'RunMon2 Successfully enter data';
$("#progressbar").show();
$("#msgz").show();
setTimeout(ajax_update2(), 50000);
},
fail: function (data) {
successmessage = 'RunMon2 Operation Failed';
console.log(successmessage);
},
});
}
function ajax_update2() {
$("#btnStop").show();
$("#btnStart").hide();
console.log("ajax_update2");
$.ajax({
type: "POST",
url: "stage2.aspx/s3_monte_carlo_refresh",
data: '{id: "' + <%= id%> + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
})
.done(function (data) {
data = $.trim(data.d);
console.log(data)
if (data == "") {
$("#msgz").hide();
$("#btnStart").show();
$("#btnStop").hide();
console.log("data empty");
return;
}
var dd = data.split("!");
var temp = data.d;
if (parseFloat(dd[0]) == 100) {
$("#progressbar").hide();
$("#msgz").html(dd[1]);
$("#btnStop").hide();
$("#btnStart").show();
console.log("data complete");
return;
}
$("#progressbar").progressbar("option", "value", parseFloat(dd[0]));
$("#msgz").html(dd[1]);
setTimeout("ajax_update2()",5000);
successmessage = 'Successfully enter ajax_update2';
console.log(successmessage);
});
}

Related

Is it right to use Jquery Selectors in javascript variable and how to get cities and districts with ajax?

I am using jQuery for making management panels. Some of them are simple and some of them are more interactive. I am getting someone's name from an input type text that has id name. Which is the right way to do this?
1 - ) $("#name").val();
2 - ) let name = $("#name");
console.log(name.val());
My another question is
if you put all city list in select . These cities have also districts related to them and they are in also select. JQuery ajax works async and preferred way is also using async. If I prepare a create page for example, for adding company , I need to get first cities then districts like this
function getDistricts(cityId) {
$.ajax({
url: "/Administrator/General/GetDistricts?cityId=" + cityId,
type: "GET",
contentType: "application/json; charset=utf-8;",
cache: false,
async: true,
success: function (response) {
if (response.success === true) {
companyDistrict.empty();
for (var i = 0; i < response.data.length; i++) {
companyDistrict.append('<option value="' + response.data[i].id + '">' + response.data[i].name + '</option>');
}
}
else {
fireAlert(response.success, response.message);
}
},
error: function (error) {
fireAlert(false, error.statusText);
}
});
}
function getGetCities() {
$.ajax({
url: "/Administrator/General/GetCities",
type: "GET",
contentType: "application/json; charset=utf-8;",
cache: false,
async: true,
success: function (response) {
if (response.success === true) {
companyCity.append('<option value="' + '0' + '">' + 'İl seçiniz.' + '</option>');
for (var i = 0; i < response.data.length; i++) {
companyCity.append('<option value="' + response.data[i].id + '">' + response.data[i].name + '</option>');
}
}
else {
fireAlert(response.success, response.message);
}
},
error: function (error) {
fireAlert(false, error.statusText);
}
});
}
and on update page for company. My code is like that
function getGetCities(cityId,districtId) {
$.ajax({
url: "/Administrator/General/GetCities",
type: "GET",
contentType: "application/json; charset=utf-8;",
cache: false,
async: true,
success: function (response) {
if (response.success === true) {
companyCity.append('<option value="' + '0' + '">' + 'İl seçiniz.' + '</option>');
for (var i = 0; i < response.data.length; i++) {
companyCity.append('<option value="' + response.data[i].id + '">' + response.data[i].name + '</option>');
}
companyCity.val(cityId);
getDistricts(cityId, districtId);
}
else {
fireAlert(response.success, response.message);
}
},
error: function (error) {
fireAlert(false, error.statusText);
}
});
}
function getDistricts(cityId, districtId) {
$.ajax({
url: "/Administrator/General/GetDistricts?cityId=" + cityId,
type: "GET",
contentType: "application/json; charset=utf-8;",
cache: false,
async: true,
success: function (response) {
if (response.success === true) {
companyDistrict.empty();
for (var i = 0; i < response.data.length; i++) {
companyDistrict.append('<option value="' + response.data[i].id + '">' + response.data[i].name + '</option>');
}
companyDistrict.val(districtId);
}
else {
fireAlert(response.success, response.message);
}
},
error: function (error) {
fireAlert(false, error.statusText);
}
});
}
I am just wondering that if I use the right way. Is this way right and how can i use jquery and javascript with asp.net core effectively ?

MySQL AJAX PHP Notification Module

Can anyone help me with this code? I would like to convert this async ajax to sync ajax. How do I do it? Here is the code that is written below. The system just lags when I leave it for 20 mins without even doing anything. So, maybe the problem is within the code.
function addmsg20(type, msg, data) {
$('#display20').html(data);
}
function waitForMsg20() {
$.ajax({
type: "GET",
url: "liprintednotif.php",
async: true,
cache: false,
timeout: 50000,
success: function(data) {
var data = JSON.parse(data);
if(data.data.length > 0){
var res = data.data;
var printed = "<ul class='menu'>";
$.each(res, function(k, v){
var empext = v.employee_ext;
if(empext == null){
empext = "";
}else{
empext = v.employee_ext;
}
printed += "<li>" +
"<a href='#'>" +
"<h4>" +
" "+v.employee_fname + " " +
v.employee_mname+" "+v.employee_lname+" " +empext+ "<small>" +
v.status_desc+ "</small>" +"</h4>" +
"<p>" + v.subj_name + "</p>" +
"</a></li>";
})
printed += "</ul>";
}else{
printed = "";
}
addmsg20("new", data.count, printed);
setTimeout(
waitForMsg20,
1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg20("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg20,
15000);
}
});
};
$(document).ready(function() {
waitForMsg20();
});
I am completely new to Javascript and/or AJAX so I really need help about this.
To make the AJAX call synchronous, just set async to false:
$.ajax({
type: "GET",
url: "liprintednotif.php",
async: false,
cache: false,
timeout: 50000,
.
.
.

Incrementally load a webpage: Where can I put: $("#LoadingImage").Hide();

I am not very experienced with JavaScript. Please see the code below:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
}
}
}
window.onload = GetSQLTable
</script>
The code incrementally builds a webpage i.e. x number of HTML tables are obtained and displayed to the webpage as and when they become ready. This works.
The problem is I don't know how to remove the LoadingImage once the webpage is complete i.e. $("#LoadingImage").hide();. OnSuccess is called x number of times depending on how many tables are returned so I cannot put it in there.
One way would be to count the number of successful onSuccess() calls, and hide your loading image when they are all complete:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
var numSucceeded = 0;
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
numSucceeded++;
if (numSucceeded === totalrows) {
$("#LoadingImage").hide();
}
}
}
}
}
window.onload = GetSQLTable
</script>
Try using .when with an array of your ajax calls. Something like this (simplified to remove the irrelevant bits):
function GetSQLTable() {
//...
var calls = [];
for (var i = 0; i < res.length; i++) {
//..
calls.push($.ajax({
type: "POST",
//..
}));
}
$.when(calls).then(function(d) {
// all done!!!
});

JSONP callback error: Property 'insertFilmData' of object [object Object] is not a function

I Have 3 nested $.ajax calls using JSONP, the first $.ajax calls work in the function but the third fails to execute the call back giving me this error: Uncaught TypeError: Property 'insertFilmData' of object [object Object] is not a function
CODE:
function searchFilms(film, settings) {
if (film === '') {
console.log("enter a movie");
} else {
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/configuration?api_key=XXX',
async: false,
jsonpCallback: 'getSearchResults',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json.images) {
settings.imageData = json.images;
getSearchResults(json, settings);
}
}
});
function getSearchResults(data, settings) {
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/search/movie?api_key=XXX&query=' + film,
async: false,
jsonpCallback: 'deliverResults',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json.total_results !== 0) {
deliverResults(json, settings);
}
}
});
function deliverResults(data, settings) {
var results = data.results;
var html = "<ul id='film-search-results' data-role='listview' data-inset='true'>";
for (var i = 0; i < results.length; i++) {
var result = results[i];
var filmId = result.id;
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/movie/' + filmId + '?api_key=XXX&append_to_response=' + settings.extras,
async: false,
jsonpCallback: 'insertFilmData',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json) {
settings.html = html;
insertFilmData(json, settings);
}
}
});
function insertFilmData(data, settings) {
var poster_base_url = settings.imageData.base_url;
var poster_size = settings.imageData.poster_sizes[0];
var poster_filepath = data.poster_path;
var poster_url = poster_base_url + poster_size + "/" + poster_filepath;
var html = settings.html + "<li><img src='" + poster_url + "' alt='Poster' /><a class='ui-link-inherit'><h3 class='ui-li-heading'>" + data.title + "</h3><p class='ui-li-desc'><strong>" + data.tagline + "</strong></p><p class='ui-li-desc'>" + data.overview + "</p></a></li>";
}
}
html = html + "</ul>";
console.log(html);
$('#content-add-title').html(html);
$('#film-search-results').trigger("create");
}
}
}
}
I'm pretty new to using JSONP for cross domain calls so i'm not sure what's going wrong seeing as the first two call backs fire and it's only the last one that doesn't. any help or direction would be greatly appreciated. Thanks
It's looking for a method called insertFilmData and can't find it. Presumably it will work if you define the function to be a method of the object which is a parameter to the ajax call, ie:
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/movie/' + filmId + '?api_key=XXX&append_to_response=' + settings.extras,
async: false,
jsonpCallback: 'insertFilmData',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json) {
settings.html = html;
insertFilmData(json, settings);
}
},
insertFilmData: function(data, settings) {
var poster_base_url = settings.imageData.base_url;
var poster_size = settings.imageData.poster_sizes[0];
var poster_filepath = data.poster_path;
var poster_url = poster_base_url + poster_size + "/" + poster_filepath;
var html = settings.html + "<li><img src='" + poster_url + "' alt='Poster' /><a class='ui-link-inherit'><h3 class='ui-li-heading'>" + data.title + "</h3><p class='ui-li-desc'><strong>" + data.tagline + "</strong></p><p class='ui-li-desc'>" + data.overview + "</p></a></li>";
}
});
Alternatively, you could just keep it as it is now, but change the line jsonpCallback: 'insertFilmData', to jsonpCallback: insertFilmData,. This will mean one of the arguments to the ajax call will be the function itself, not the name of the function. (And if I understand this correctly, it doesn't matter that the function definition is below this line, because it's a named function and it's in scope.)

Problem with callback function in jquery

I am using the following functions to populate the dropmenu menu, my problem is that my click event is not firing ,and i am not able to populate the dynamic dropdown menu.
This is my Jquery function
function testXmlMenu() {
getmenu(function (results) {
$("div[id ^= 'menuItemGroup']").slideUp(500);
$.ajax(
{
type: "POST",
url: "JsonWebService.asmx/GetMenuItems",
data: '{"menuId":"' + results.data.MenuId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (items) {
$(event.target).children().remove();
var html = "<div id='menuItemGroup" + event.data.MenuId + "' style='display:none'>";
for (var j = 0; j < items.length; j++) {
html += "<div id='MenuItems'> <a href='" + items[j].NavigateUrl + "'>" +
items[j].Text + "</a></div>";
}
html += "</div>";
$(event.target).append(html);
$("#menuItemGroup" + event.data.MenuId).slideDown(500);
},
error: function (err) {
alert(err.status + " - " + err.statusText);
}
});
});
}
function getmenu(callback)
{
$.ajax({
type: "POST",
url: "JsonWebService.asmx/GetMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success:
function (results) {
$(results).find("Menu").each(function () {
var Text = $(this).find("Text").text();
var MenuId = $(this).find("MenuId").text();
alert(MenuId);
var dmenu = $("#Menudiv");
dmenu.append("<td><ul>"+Text+"</ul></td>");
$("dmenu.td").click(callback(results));
});
}
});
}
I think your jQuery selector is switched around for your click action.
It should be:
$("td.dmenu").click(callback(results));

Categories

Resources