I have a javascript function which is load help menu list (dropdown).
First function: GetPageKeyword()
function GetPageKeyword() {
var url = window.location.href.replace(window.location.origin, '').replace('/#', '').replace('#', '').replace('//', '/');
url = url.split("?")[0];
url = GetURL(url);
if (url.lastIndexOf('/') == (url.length - 1))
url = url.slice(0, -1);
if (url.indexOf('/') == 0)
url = url.substring(1, url.length);
$.ajax({
url: "/api/PageKeywords/GetLabelsByUrl",
type: 'Get',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
data: { url: url },
success: function (data) {
var res = data.data;
var htmlAppend = '<a id="hlpMenuLink" class="dropdown-toggle" data-toggle="dropdown"><i style="font-size: 17px;" class="fa fa-question-circle"></i></a>';
if (res.length > 0) {
$.getJSON("https://test.com/search.json?label_names=" + res[0].labels,
function (data) {
if (data.results.length > 0) {
htmlAppend += '<ul id="menuHelpUl" class="dropdown-menu pull-right">';
for (var i = 0; i < data.results.length; i++) {
htmlAppend += "<li>" + data.results[i].name + "</li>";
}
htmlAppend += "</ul>";
}
$('#helpMenu').html(htmlAppend);
});
}
$('#helpMenu').html(htmlAppend);
setTimeout(function () { GetArticulateDetails(); }, 1100);
},
error: function (jqXhr, textStatus, errorThrown) {
var err = jqXhr;
}
});
}
But now I need to add more item to help menu.
In the second function I tried to add the new item to ul id="menuHelpUl" which I build in the first function.
Second function: GetArticulateDetails()
function GetArticulateDetails() {
var url = window.location.href.replace(window.location.origin, '').replace('/#', '').replace('#', '').replace('//', '/');
url = url.split("?")[0];
url = GetURL(url);
if (url.lastIndexOf('/') == (url.length - 1))
url = url.slice(0, -1);
if (url.indexOf('/') == 0)
url = url.substring(1, url.length);
$.ajax({
url: "/api/PageKeywords/GetArticulateLabelByUrl",
type: 'Get',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
data: { url: url },
success: function (data) {
var res = data.data;
var htmlAppend = '<hr/>';
if (res.length > 0) {
for (var i = 0; i < res.length; i++) {
htmlAppend += "<li>" + res[i].name + "</li>";
}
}
$('#menuHelpUl').append(htmlAppend);
},
error: function (jqXhr, textStatus, errorThrown) {
var err = jqXhr;
console.log(err);
}
});
}
In first function GetPageKeyword at last on success response, i am calling the second function which is
setTimeout(function () { GetArticulateDetails(); }, 1100);
Here I am having problem some case the second function is not working because it may be it can not find id of #helpMenu.
code : function : GetArticulateDetails :-- $('#helpMenu').html(htmlAppend);
So there how I call my second funtion after compleate first function.
Try to call your second function right in the end of your ajax success callback:
$.ajax({
/* settings */
success: function (data) {
var res = data.data;
var htmlAppend = '<a id="hlpMenuLink" class="dropdown-toggle" data-toggle="dropdown"><i style="font-size: 17px;" class="fa fa-question-circle"></i></a>';
if (res.length > 0) {
$.getJSON("https://test.com/search.json?label_names=" + res[0].labels,
function (data) {
if (data.results.length > 0) {
htmlAppend += '<ul id="menuHelpUl" class="dropdown-menu pull-right">';
for (var i = 0; i < data.results.length; i++) {
htmlAppend += "<li>" + data.results[i].name + "</li>";
}
htmlAppend += "</ul>";
}
$('#helpMenu').html(htmlAppend);
GetArticulateDetails(); // here !
});
}
$('#helpMenu').html(htmlAppend);
}
});
Also, maybe it would be necessary to protect this call by
if (data.results.length > 0) {
GetArticulateDetails();
}
declare the menuHelpUl as a ui element like this:
var menuHelpUl = $('<ul id="menuHelpUl" class="dropdown-menu pull-right">');
and append li elements to it in loop
var li = $("<li>" + data.results[i].name + "</li>");
menuHelpUl .append(li);
now pass the menuHelpUl to GetArticulateDetails in ajax success:
GetArticulateDetails(menuHelpUl);
and use it in ajax success
menuHelpUl.append(htmlAppend);
In your first method the call
$('#helpMenu').html(htmlAppend)
Should be inside the handler for getJson(...)
Currently it is called before that method completes but relies on data generated by that async callback.
(I'd give you an explicit code change but difficult to edit on mobile)
Edit - actually the above line is duplicated. The one outside the handler can be removed. Perhaps there are duplicate Ids?
You can also call the second method from within the getJson handler after the Html has been updated.
menuHelpUl will only exist if the call in getJson returns some data. If it does not, there will be no element.
Try this solution using promises in javascript:
function GetPageKeyword() {
return new Promise((resolve, reject)=>{
//your code here
resolve();
});
}
function GetArticulateDetails() {
return new Promise((resolve, reject)=>{
//your code here
resolve();
});
}
Call it like this:
GetPageKeyword().then((result)=>{
GetArticulateDetails();
}).catch((error)=>{
//handle error
});
here is the edited first function :
function GetPageKeyword() {
return new Promise((resolve,reject)=>{
var url = window.location.href.replace(window.location.origin, '').replace('/#', '').replace('#', '').replace('//', '/');
url = url.split("?")[0];
url = GetURL(url);
if (url.lastIndexOf('/') == (url.length - 1))
url = url.slice(0, -1);
if (url.indexOf('/') == 0)
url = url.substring(1, url.length);
$.ajax({
url: "/api/PageKeywords/GetLabelsByUrl",
type: 'Get',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
data: { url: url },
success: function (data) {
var res = data.data;
var htmlAppend = '<a id="hlpMenuLink" class="dropdown-toggle" data-toggle="dropdown"><i style="font-size: 17px;" class="fa fa-question-circle"></i></a>';
if (res.length > 0) {
$.getJSON("https://test.com/search.json?label_names=" + res[0].labels,
function (data) {
if (data.results.length > 0) {
htmlAppend += '<ul id="menuHelpUl" class="dropdown-menu pull-right">';
for (var i = 0; i < data.results.length; i++) {
htmlAppend += "<li>" + data.results[i].name + "</li>";
}
htmlAppend += "</ul>";
$('#helpMenu').html(htmlAppend);
resolve()
}else{
$('#helpMenu').html(htmlAppend);
resolve()
}
});
}else{
$('#helpMenu').html(htmlAppend);
resolve()
}
},
error: function (jqXhr, textStatus, errorThrown) {
var err = jqXhr;
reject()
}
});
})
}
You can use jquery.when
$.when(GetPageKeyword()).then(GetArticulateDetails());
from the code it seems like $('#helpMenu') is found to be null or undefined.
try to check the null or undefind status of $('#helpMenu')
**if($('#helpMenu') == null || $('#helpMenu') == undefined)**
and then perform the append html operation.
Related
I have a project dropdown.A user can multiselect projects.
I want to pass the values selected from multiselection in dropdown as filter parameters in ajax url.
The code is as follows:
function CheckIfPresent(callback)
{
var proj = [];
var urlprograms;
if ($("#projNameDropdown :selected").text() != 'Select all projects') {
$('#projNameDropdown :selected').each(function (i, sel) {
proj[i++] = $(sel).val();
if (proj.length == 1)
urlprograms = "(Project_Name/Project_Name eq '" + proj[0] + "')";
});
if (proj.length > 1) {
for (i = 1; i < proj.length; i++) {
urlprograms += " or (Project_Name/Project_Name eq '" + proj[i] + "')";
}
}
}
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists('')/items?$select=*,Project_Name/Project_Name&$expand=Project_Name&$filter=" + urlprograms + "'",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (dataActive) {
}
error: function (dataActive) {
console.log(dataActive);
}
});
}
I am not able to reach the success method and get error.What is that I am doing wrong?
I have a simple series of functions :
convertXML();
function convertXML(){
var xmlObj = xmlToJson(xml.responseXML)
.query.results.WMS_Capabilities;
console.log("convertXML");
(function checkReturn(){
if(typeof xmlObj != 'undefined'){
return (function(){ return createData(xmlObj)})();
}
else {
setTimeout(checkReturn, 50);
}
})();
}
function createData(xmlObj){
for (var i = 0; i < xmlObj.Capability.Layer.Layer.length; i++){
var row={};
row = xmlObj.Capability.Layer.Layer[i];
WMSLayers.push(row);
};
console.log("createdata",WMSLayers)
return (function(){return finish()})();
}
function finish(){
console.log(n == Server.length-1)
if (n == Server.length-1){
//n is defined as an argument
//this code is a part of a bigger function
//same for Server variable
createTable();
};
}
The problem is that that the convertXML function sometimes returns the callback function createData with the xmlObj variable undefined. So I have to check if the variable is defined to call the callback function.
My question is isn't a function suppose to return when all its variables are finished loading data?
UPDATE
This is how I make the request:
var req = {
"type" :"GET",
"dataType":"XML",
"data" : null,
"url" : url
};
//make the request (ajax.js)
ajax(req,ajaxSuccess,ajaxError);
function ajax(prop,onsuccess,onerror){
// data = data || null;
// var url = "wps"; // the script where you handle the form input.
$.ajax({
type: prop.type,
dataType: prop.dataType,
data: prop.data,
url: prop.url,
success: function (data, textStatus, xhr) {
console.log(xhr)
onsuccess(xhr);
},
error:function (data ,textStatus, xhr) {
onerror(xhr);
}
});
// e.preventDefault();
}
function ajaxSuccess(xhr){
$("#messages").append(
'<span style="color:blue">' +
getFullTime() +
'</span> Response HTTP status <b>' +
xhr.status +
' [' + xhr.statusText + ']' +
'</b> from:' +
' <a style="color:grey;text-decoration:none;" href="' +
url+
'" target="_blank">'+
Server[i].link +
Request["getCapabilities"]+
'</a><br>'
);
//create the wms
createWMS(xhr, Server[i],i);//this is where the convertXML,createData and finish functions are located
};
You can use the complete function of $.get(). Note, n does not appear to be defined within finish function.
function convertXML(xml, textStatus, jqxhr) {
var xmlObj = xmlToJson(jqxhr.responseXML)
.query.results.WMS_Capabilities;
console.log("convertXML");
if (typeof xmlObj != 'undefined') {
createData(xmlObj);
}
}
function createData(xmlObj){
for (var i = 0; i < xmlObj.Capability.Layer.Layer.length; i++){
var row = xmlObj.Capability.Layer.Layer[i];
WMSLayers.push(row);
};
console.log("createdata",WMSLayers)
finish();
}
$.get("/path/to/resource", convertXML, "xml")
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
});
Following is the code: I am writing a function to update the color attribute in json file. I am able to update the Object but can't write it back to the file(Modify the file). I need to update json data file when user gives input via form.
function updatecolor(id, color) {
$.ajax({
type: "GET",
dataType: "json",
url: "Data.json",
cache: false,
beforeSend: function() {
$('#table').html('loading please wait...');
},
success: function(jsondata) {
console.log(jsondata);
count = jsondata.length;
for (i = 0; i < jsondata.length; i++) {
if (jsondata[i].id == id)
jsondata[i].color = color;
}
window.alert(JSON.stringify(jsondata));
}
});
}
function popupform() {
$('#formpop').show();
}
function my() {
$.ajax({
type: "GET",
dataType: "json",
url: "Data.json",
cache: false,
beforeSend: function() {
$('#table').html('loading please wait...');
},
success: function(jsondata) {
console.log(jsondata);
count = jsondata.length;
var str = '';
var str2 = '';
var str3 = '';
//str += '<ul>';
$.each(jsondata, function(idx, obj) {
var match = obj.Color;
if (match == "Blue") {
str += 'ID :' + obj.id + ' Color : ' + obj.Color + '<br> ';
}
});
$.each(jsondata, function(idx, obj) {
var match = obj.Color;
if (match == "Red") {
str2 += 'ID :' + obj.id + ' Color : ' + obj.Color + '<br> ';
}
});
$.each(jsondata, function(idx, obj) {
var match = obj.Color;
if (match == "Green") {
str3 += 'ID :' + obj.id + ' Color : ' + obj.Color + '<br> ';
}
});
//str += '</ul>';
$('#abc').html(str);
$('#abc2').html(str2);
$('#abc3').html(str3);
}
});
}
Edit - Adding the server code here from the comment section:
var http = require("http");
var fs = require("fs");
function send404Response(response){
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("Error 404 - Page not found");
response.end();
}
function onRequest(request, response) {
if( request.method == 'GET' && request.url == '/' ){
response.writeHead(200, {"Content-Type": "text/html"}); //Open file as readable stream, pipe stream to response object
fs.createReadStream("./index.html").pipe(response);
}else{
send404Response(response);
}
}
http.createServer(onRequest).listen(8888);
https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
Node.js includes a function for writing data to a file. Use fs.writeFile() to write to the file you want. Note that it will replace the file if the file already exists.
There is also a fs.write() function that looks like you can append to the end of an existing function.
I am trying to paginate rows of a table inside my servlet using hibernate.But once I click on the desire index of the page it always gives me only the first set of row of the table.So I put System.out.print() at every major sections and finally found out that the request.getParameter("pgIndex") is always returns null.
My servlet code:
int pageIndex = 0;
int totalNumberOfRecords = 0;
int numberOfRecordsPerPage = 5;
String sPageIndex = request.getParameter("pgIndex");
//whether pgIndex=1 or pgIndex=2 in the url, always returns null as the output.
System.out.println("pg - " + sPageIndex);
pageIndex = sPageIndex == null ? 1 : Integer.parseInt(sPageIndex);
int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;
List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class)
.setFirstResult(s)
.setMaxResults(numberOfRecordsPerPage)
.list();
for (ProductHasSize pro : phs) {... some html content here...}
Criteria criteriaCount = ses.createCriteria(ProductHasSize.class);
criteriaCount.setProjection(Projections.rowCount());
totalNumberOfRecords = (int) (long) (Long) criteriaCount.uniqueResult();
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
for (int j = 1; j <= noOfPages; j++) {
String myurl = "products.jsp?pgIndex=" + j;
String active = j == pageIndex ? "active" : "";
s2 = s2 + "<li class='" + active + "'>" + j + "</li>";
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"d1\":\"" + s1 + "\",\"d2\":\"" + s2 + "\"}]");
products.jsp
<div class="row">
<div class="col-md-12">
<ul class="pagination" id="pagId"></ul>
</div>
</div>
JavaScript
$(document).ready(function () {
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
UPDATE :
$(document).on("click", "#pagId a", function (event) {
//tried with adding another function . But still returns null.
event.preventDefault();
var para = $(this).attr('href').match(/\d+/);
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
data: {pgIndex: para},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
Thanks in advance.
In sending JSON data, you will not simply receive it as request parameter. Instead, just add "normal" parameter:
Sending as HTTP POST
$.ajax({
url: 'AdimnProductFilterAction',
type: 'POST',
data: {
'pgIndex': para
},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
Or as HTTP GET
$.ajax({
url: 'AdimnProductFilterAction?pgIndex='+para,
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
To add parameter into your servlet call.
I have a javascript function which is looping on my data basically I call another function inside of loop but it only execute once on last index here is my code and this function I wants to execute on every time.
basically inside loop I call ajax that is run fine on each index of loop but issue is to call db.transaction function which is only execute on last index
db.transaction(populateDB, errorCB);
function renderList(tx, results) {
len = results.rows.length;
console.log("rows" + results.rows.length);
for (var i = 0; i < len; i++) {
(function (i) {
var nid = results.rows.item(i).nId;
$.ajax({
type: 'post',
url: 'http://localhost:50972/LibraryService.asmx/GetTitleSections',
dataType: 'json',
data: "{'MainSectionId':'" + nid + "'}",
contentType: 'application/json; charset=utf-8',
async: false ,
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
},
error: function (error) {
console.log(error);
}
});
db.transaction(TblTitleSection, errorCB);
})
(i);
// htmlstring += '<li>' + results.rows.item(i).strTitle + '</li>';
// $('#resultList').append("<li>" + results.rows.item(i).strTitle + "</li>");
$('#'+i).append( results.rows.item(i).strTitle );
// $('#tblMainSection').append("<tr><td>" + results.rows.item(i).strTitle + "</td></tr>");
}
// $('#resultList').html(htmlstring);
}
Perhaps you loop continues while running your ajax call. You could try putting the increment (i++) in your success function to force the loop to halt till the function is finished. Syntax seems to be okay.
replace:
for (var i = 0; i < len; i++) {
With:
for (var i = 0; i < len;){
And
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
}
With:
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
i++;
}
See if that works :)