I'm trying to work with two XML files. I use the second highlighted answer in this thread [1] as a base script.
This is what I got:
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
var party1 = $.getValues('http://data.riksdagen.se/voteringlista/?rm=2010%2F11&bet=&punkt=parti=M&valkrets=&rost=&iid=&sz=500&utformat=xml&gruppering=bet')
var party2 = $.getValues('http://data.riksdagen.se/voteringlista/?rm=2010%2F11&bet=&punkt=&parti=S&valkrets=&rost=&iid=&sz=500&utformat=xml&gruppering=bet')
$(party1).find('votering').each(function(){
var id = $(this).find("forslagspunkt").text()
partyTwo(id)
//-------------------------------------
//HERE I RUN A FEW SIMPLE IF STATEMENTS
//------------------------------------
})
function partyTwo(id) {
$(party2).find('votering').filter(function() {
return $(this).find("forslagspunkt").text() == id;
}).each(function () {
//-------------------------------------
// AGAIN, A FEW SIMPLE IF STATEMENTS
//------------------------------------
return vote
})
}
This leaves me with two problems:
1) partyTwo(id) returns 'undefined', but works fine if I manually insert an id outside.
2) The whole script runs very slow (+5 sec to load).
Any thoughts?
[1] JQuery - Storing ajax response into global variable
Related
I am new to js.
I am trying to call the API and save the data in a variable (obj = [])
But i go thru the console, my ajax call called two times. May i know why?
This is the console on my browser that i found out it is called two time:
Below is my code:
$(function (){
var obj = [];
var selected = $("select.dr-down option:selected").click().val();
var markup = '';
getAPI();
console.log('obj = ', obj);
function getAPI() {
$.ajax({
url: 'http://www.mocky.io/v2/5d73bf3d3300003733081869',
method: 'GET',
}).done(function (data) {
data.forEach(function (data) {
obj.push(data);
});
})
}
})
I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.
My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has completed its work.
Here an example (just a sample code):
var tasks = pdBrowser.EvaluateScriptAsync(#"
(function(){
$.ajax({
type: ""POST"",
dataType: ""json"",
cache: false,
url: ""_resources/php/ajaxRequests.php"",
async: false,
data: {
action: ""insertCrossPlatform"",
type: """",
values: JSON.stringify(""foo bar"")
},
success: function(response) {
if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
{
return response;
}
else
{
//pageReload();
return ""OK"";
}
},
error: function(xhr, textStatus, errorThrown) {
return errorThrown + ""\n"" + xhr.responseText;
},
complete: function() {
return ""COMPLETE"";
}
});
})();", null);
tasks.ContinueWith(t =>
{
if (!t.IsFaulted)
{
var response = t.Result;
if (response.Success)
{
if (response.Result != null)
{
MessageBox.Show(response.Result.ToString());
}
}
else
{
MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}, TaskScheduler.Default);
Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?
Thanks in advance.
Firstly SchemeHandler is unlikely to be suitable in this scenario, you would typically implement a SchemeHandler when your providing the response.
Most people choose to bind an object, and call a method on their bound object when they wish to communicate with the parent application. See the FAQ for an example. https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#3-how-do-you-expose-a-net-class-to-javascript
With 49.0.0 you can implement ResponseFilter to gain access to the underlying response buffer, it's complex and not well documented, so if your not comfortable digging through reference C++ code then this option isn't for you. Here's a reference https://github.com/cefsharp/CefSharp/blob/cefsharp/49/CefSharp.Example/Filters/PassThruResponseFilter.cs#L17
Something that I did was create an element on the page through javascript with an ID that is the response of the ajax call. So for example, when you make an ajax call assign an ID to the ajax call.
When the ajax call returns, write an element on the page with the pre-assigned id and callback information. Then you can just use cefsharp to read the element content from the page and this will be your callback information.
var myDivElement =document.getElementById('textareaInfo');
if( myDivElement === null)
{
var input = document.createElement('textarea');
input.id = "textareaInfo";
input.value = "Test"
input.rows="4";
input.cols="50";
input.style="height:100%;width:900px;"
var dom = document.getElementsByClassName("page-body")[0];
dom.insertAdjacentElement('afterbegin', input)
}
Then later with ajax
var root = 'https://jsonplaceholder.typicode.com';
var _holder = callbackObj;
callbackObj.showMessage(""ajax"");
$.ajax({
url: root + '/posts/1',
contentType: 'application/json; charset=utf-8',
method: 'GET',
complete: function(data){
},
success: function(response) {
$(#'textareaInfo').value(response);
}
}).then(function(data) {
callbackObj.showMessage(data);
});
Then read the texarea from cefsharp in c#
chromeBrowser.GetMainFrame().EvaluateScriptAsync(function()...$(textareaInfo).value).Result
You can use PostMessage javascript method to notify .NET application:
CefSharp.PostMessage('Your data Here');
Here is .NET code example for headless browser:
var browser = new ChromiumWebBrowser("", null, RequestContext);
browser.JavascriptMessageReceived += (sender, e) =>
{
if ((string)e.Message.notificationid == "notification1")
{
// Your processing code goes here
}
};
browser.Load(destinationUrl);
browser.ExecuteScriptAsync("(function() { ... ; CefSharp.PostMessage({data: data, notificationid: 'notification1'});})()");
I have the following javascript code, to loop through a number of pages on my server (Used for digital signage).
This code is used in all pages and (at the moment) loops at a page every 3 seconds (see timeout). But, the memory usage of the browser goes up, slowly but steady. After 2 hours it went from 192mb in use to 436mb in use. Since this is on a Raspberry pi with only 512mb memory dedicated to cpu it's not very practical.
Are there any obvious memory leaks in this code? I'm not an expert myself, but since these things will be running 8-12hours a day probably I'm talking about 20reloads/min, so +/- 9600-14400 reloads a day. More if it doesn't get shutdown..
$(document).ready(function() {
versionPage = parseInt(document.getElementById("version").innerHTML);
versionServer = 0
urls = 0;
getVersion();
currentPage = getPage();
getContent();
main();
function getPage() {
page = window.location.href.split("/");
return page[page.length-1];
}
function getVersion() {
$.ajax({
url: "http://localhost/getVersion",
type: "GET",
dataType: "json",
success: function(json) {
console.log("json" + json);
versionServer = json;
if (versionServer != versionPage) {
console.log("Difference!");
}
else {
console.log("Same!");
}
},
});
}
//saves how much urls there are
function getContent() {
$.ajax({
url: "http://localhost/getContent",
type: "GET",
dataType: "json",
success: function(json) {
console.log(json);
urls = json;
},
});
}
//main function loop
function main() {
//check version every
window.setInterval(function() {
getVersion();
if(versionServer != versionPage) {
window.location.href = "http://localhost:5000/1"
}
if(urls != 1) {
nextPage =(parseInt(currentPage) % urls) + 1;
window.location.href = "http://localhost:5000/" + nextPage;
}
}, 3000);
}
});
I had to ask you this in comment but it required "50 reputation" to comment.
Have you tried putting your code in an external Javascript file, something like "signagelooper.js" and looing your pages sequentially. This way your looper functions always have one instance running. Correct me if this is what you do not want to do.
This is the continue from this : Link
My storyboard is like this. I want to autorefresh my page. Coz I create a live monitoring to manage requests from my users. When a new comment is create from user, I wanna create a notification.
So, I choose use js/jquery.
I try so hard to implement that to my ajax response like this
/* This is function to initialized old comment as return a first */
function initializedFirstComment(handleData) {
$.ajax({
url: "<?php echo base_url() . 'control_closing/getKomentarMD/' ?>",
type: 'POST',
dataType: 'json',
success: function(data) {
handleData(data);
}
});
}
For the second array is like this :
/*For the second array */
function refreshByManager(first) {
var audioElement = document.getElementById('notif-md');
audioElement.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
setTimeout(function() {
$.ajax({
url: '<?php echo base_url() . 'control_closing/getKomentarMD/' ?>',
type: 'POST',
dataType: 'json',
success: function(second) {
console.log(first); // For debug first array, and in firebug it success.
console.log(second);// For debug second array, and in firebug it success.
var difference = function(list1, list2, id, attr) {
var map = {};
// Create map.
list1.forEach(function(item) {
map[item[id]] = item;
});
// Find diff.
return list2.filter(function(item) {
var target = map[item[id]];
// Return if the item is not exist in first, or the target attr is different.
return (typeof target === 'undefined' || item[attr] !== target[attr]);
});
}
var diffs = difference(first, second, 'id_request', 'comment_bapak');
console.log(diffs);
alert(diffs[0].comment_bapak);
refreshByManager();
}
});
}, 5000);
}
So, in main document will be like this.
$(document).ready(function() {
initializedFirstComment(function(output) {
refreshByManager(output); // Check it
})
}
I dont understand, why the output is like this :
The result of debug :
console.log(diffs);
alert(diffs[0].comment_bapak); is =>
[]
TypeError: diffs[0] is undefined
I am so desperate. Any help it so appreciated.
Well, I tested the code a bit and the difference function returns an empty list if the list2 doesn't contain objects that differ from the objects of the list1.
So I would check the diffs variable first, before trying to access it.
var diffs = difference(first, second, 'id_request', 'comment_bapak');
if (diffs) {
console.log(diffs);
alert(diffs[0].comment_babak);
}
Another problem I noticed is that you're defining the difference function over and over again in the success callback function. You should move it outside from there.
I am trying to use global variables as flags and cant get it to work. I have two functions:
This function sets a flag to be false when it is done.
function buildYearsTable(btn) {
//console.log ("At build years table")
var fundCode = document.getElementById("fundCode").value
buildYearsFlag = true;
$.ajax({url: "/scholarship/scholarshipMaintenance/buildYearsTable", method: "POST",
cache: false, data: {fundCode: fundCode},
complete: function(xhr, statusCode){
console.log("inside build years table")
data = $.parseJSON(xhr.responseText)
$('#myTable tbody').html('');
data = data.sort()
data = data.reverse()
for(var i = data.length - 1; i >= 0; i--) {
moveYearOption(data[i])
addYearRow(data[i])
}
buildYearsFlag = false;
//$('#yearsTable').html(xhr.responseText)
console.log("done in build years table")
}})
}
This function is called when the first one is called, but i need it to perform its ajax call ONLY once the flag is set to false by the first function. I am not sure how to accomplish this. I was thinking a while loop (polling kind of idea) but not sure how to go about it.
function rebuildYearSelects(btn) {
//console.log ("At rebuild selects")
var fundCode = document.getElementById("fundCode").value
while (buildYearsFlag == false) {
$.ajax({url: "/scholarship/scholarshipMaintenance/rebuildYearSelects", method: "POST",
cache: false, data: {fundCode: fundCode},
complete: function(xhr, statusCode){
console.log("got inside rebuild years select")
data = $.parseJSON(xhr.responseText)
selectedYears = data.sortedSelectedYears
unselectedYears = data.sortedUnselectedYears
$('#yearsModal').replaceWith(data.html)
fixModals();
buildYearsFlag = true;
console.log("done in rebuildYearSelects")
}})
}
}
The best way to accomplish this is by using callbacks.
You just need to call the second function after the response from the first.
You should use 'done' instead of 'complete'.
function buildYearsTable(btn) {
var fundCode = document.getElementById("fundCode").value
$.ajax({url: "/scholarship/scholarshipMaintenance/buildYearsTable", method: "POST",
cache: false, data: {fundCode: fundCode},
done: function( data ){
// Your code goes here
// Call the function only after the response
rebuildYearSelects();
}})
}
Html:
onclick="buildYearsTable();"
Remove the flags and the while loop, everything should work.