Problem with callback function in jquery - javascript

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

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 ?

Async post fails on first try, works on second

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

CSS class in jquery

I want to apply a CSS class to a gridview. I tried to apply this style
reference link, so I try this
$(function () {
$('[ID*=search_data]').on('click', function () {
var fromdate = $('[ID*=fromdate]').val();
var todate = $('[ID*=todate]').val();
var regiondrop = $('[ID*=regiondrop] option:selected')[0].value;
var tabledata= $('[ID*=tabledata]');
var obj = {};
obj.fromdate = fromdate;
obj.todate = todate;
obj.regiondrop = regiondrop;
Getdataa(obj);
return false;
});
});
function Getdataa(obj) {
//alert('1');
$.ajax({
type: "POST",
url: "WebForm1.aspx/search_data",
data: "{'fromdate':'" + obj.fromdate + "','todate':'" + obj.todate + "','regiondrop':'" + obj.regiondrop + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
var final = JSON.parse(result.d).response;
console.log(JSON.parse(result.d).response)
$("#tabledata").empty();
if (final.length > 0) {
$("#tabledata").append(
"<tr ><th>ID</th><th>OwnerName</th></tr>");
for (var i = 0; i < final.length; i++) {
if (final[i] !== null) {
$("#tabledata").append("<tr><td>" +
final[i][0] + "</td> <td>" +
final[i][1] + "</td> <td>" +
}
}
}
else {
$("#tabledata").hide();
$("#Label4").text("No Data");
}
},
error: function (error) {
alert("error");
}
});
}
UPDATE
ok i update these lines in jquyer after $("#tabledata").empty();
$("th").addClass("GridviewScrollHeader");
$("td").addClass("GridviewScrollItem");
but when i build then there is no effect in grid view
And gridview in html
<table id="tabledata">
</table>
When i apply this then gridview is display with simple where as i want to apply this css in gridview when i apply this then gridview display without formatting..
what i try
what i want
So how i apply css ??
any solution?
ok i use this and this work for me
$("#tabledata tr:first").addClass('GridviewScrollHeader');
$("#tabledata tr").addClass('GridviewScrollItem');

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.)

jQuery: How do I pass a value into an Ajax call?

I am updating some div as follows:
for(var i = 0; i < data.length; i++) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
The value of i does not work inside the ajax call. I am trying to pass the value of i so that it can attach the element to the proper div. Can someone help me out?
Ok. This works but would really love if someone can explain it! I broke my head over this so posting it here just in case someone needs it.
for(i = 0; i < data.length; i++)
fetchItem(i)
fetchItem = function(i) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
Have you tried making i a global variable:
Change:
for(var i = 0; i < data.length; i++) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
To this:
for(i = 0; i < data.length; i++) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
Also I agree with Nick. You can do the looping first then send the array (JSON) serverside to be processed. This way the application will be much more responsive.
I think your problem has to do with scope.
You should wrap the what's in the for loop into a function
for(var i = 0; i < data.length; i++) {
doAjax(i);
}
function doAjax(i) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
The i value for the closure function of success is correctly bound only when it is not in a for loop.
That should work. Good luck.

Categories

Resources