Load raw link contents into terminal - jquery-terminal

I'm using the raw property to get formatted data from urls into the terminal, like this
$(function() {
var save_state = [];
var terminal = $('#term').terminal(function(command, term) {
term.pause();
url = ...;
$.get(url, function(result) {
term.echo(result, {raw:true}).resume();
});
}, { prompt: '>>', name: 'test', outputLimit: 1000 });
});
I'm wondering, how do I get it so when links in result are clicked, they load their data into the terminal the same way command data is loaded, rather than opening a new browser tab?
Thanks!

If you're using command that include URL or URI (for instance get foo.html or get https://example.com) you can use this:
terminal.on('click', '.terminal-output > div:not(.exception) a', function() {
// if you don't use `true` it will show the command like if you type it
// instead of `get` you can use any command you have that will
// fetch the url and display it on the terminal
terminal.exec('get ' + $(this).attr('href'), true);
return false; // prevent following the link
});
if you have different logic for displaying the urls you may need to dipicate the code from interpreter inside click event handler.
terminal.on('click', '.terminal-output > div:not(.exception) a', function() {
// duplicated code from your interpreter
term.pause();
var url = $(this).attr('href');
$.get(url, function(result) {
term.echo(result, {raw:true}).resume();
});
return false;
});

Related

How to use Magiczoom Callbacks

The magiczoom documentation describes callbacks that will execute at given times, but it's unclear how to use or assign those callbacks.
For example, how would I print a console message onZoomReady?
The closest I've found is a MagicZoom.defaults.onready property, but it's unclear how to set it via javascript (my attempts aren't working as expected).
The callbacks are configured via mzOptions, for example:
var mzOptions = {
onZoomReady: function() { … } }
;
Or:
var mzOptions = {};
mzOptions.onZoomReady = function() { … };
You can do something like this:
MagicZoom.registerCallback('onUpdate',
function() {
console.log('onUpdated', arguments[0], arguments[1], arguments[2]);
});
That will log stuff in the console like this:
onUpdated (id-of-mz-wraper) (html of old element) (html of new element)
Other options that you can use are as per the documentation:
MagicZoom.registerCallback('onZoomReady', function() {
console.log('onReady', arguments[0]);
});
MagicZoom.registerCallback('onZoomIn', function() {
console.log('onZoomIn', arguments[0]);
});
MagicZoom.registerCallback('onZoomOut', function() {
console.log('onZoomOut', arguments[0]);
});

getjson does not work on production server but works on development machine

I have following javascript that is using a selection changed to fill in a select list.
$(function () {
$("#bedrijvenauto").each(function () {
var target = $(this);
var dest = target.attr("data-autocomplete-destination");
target.autocomplete({
source: target.attr("data-autocomplete-source"),
select: function (event, ui) {
alert('selected bedrijf');
event.preventDefault();
target.val(ui.item.label);
$(dest).val(ui.item.value);
$("#projectenauto").val("");
alert('selected bedrijf');
alert($('#BEDRIJF_ID').val());
$.getJSON("/Project/GetListViaJson", { bedrijf: $('#BEDRIJF_ID').val() }, function (data) {
alert('selected bedrijf');
alert(data);
$("#PROJECT_ID").empty();
$("#PROJECT_ID").append(new Option("Maak een selectie", 0));
for (var i = 0; i < data.length; ++i) {
alert(data[i].value + ' ' + data[i].label);
$("#PROJECT_ID").append(new Option(data[i].label, data[i].value));
}
});
},
focus: function (event, ui) {
event.preventDefault();
target.val(ui.item.label);
}
});
target.val($("#BEDRIJF_NAAM").val());
});
It works like a charm on my development pc. The alert are all coming out even the data is returning results. That is the difference with the development pc that does not give any results after the call to getJSON
I have the feeling I am missing a detail here.
I am not used to debugging on a webserver because I usually create GUI applications in WPF, and this is a student's work for his vacation and I now got to get it working without him being around anymore. Vacation is done :-(
But not for me.
The 404 error indicated in your comments means the url your creating is incorrect. Always make use of the #Url.Action() method to ensure they are correctly generated. In your script
var url = '#Url.Action("GetListViaJson", "Project")';
$.getJSON(url, { bedrijf: $('#BEDRIJF_ID').val() }, function (data) {
....
}
or if this is an external script, then add the var url = '#Url.Action(...)'; in the main view (razor code is not evaluated in external script files), or add it as a data- attribute to the element your handling
data-url = "#Url.Action(...)"
and get it again using var url = $(someElement).data('url');

Where are my links?

I am trying to run a basic casperjs script that logs into a website then shows me the links. However my output is not returning anything other then 'Done'
Here is my code
var casper = require('casper').create();
casper.start('http://xxxxxx/Login.aspx', function(){
//Login
this.fill('form#form1', {
'username': 'xxxxx',
'password': 'xxxxx'
}, true);
});
casper.then(function(){
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; ++i) {
//These should show something
this.echo(links[i].innerText;
this.echo(this.getHTML());
}
});
casper.run(function(){
this.echo('done').exit();
});
Like I said, the only thing I get back is "done".
You use getElementsByTagName in the CasperJS context, you can't do that here, you have to pass in the page context by using the evaluate function (see evaluate, thenEvaluate).
If you just want to print the text of a link, use that in your casper.then :
this.echo(this.fetchText('a'));
And you forgot a bracket too here : this.echo(links[i].innerText;
When you iterate in casperjs, you should use each (IIFE) : http://docs.casperjs.org/en/latest/modules/casper.html#each

jQuery wait for an AJAX request to be completed before refreshing the page

I've got the following jQuery:
$("#delete_products").click(function() {
$(":checkbox:checked").each(function() {
var pid = $(this).val();
$.get('delete_product.php',{pid: pid});
});
location.reload();
});
There is a problem with this since the page doesn't wait for the AJAX request to be completed (MULTIPLE AJAX REQUESTS), and refreshes the page immediately and makes the AJAX request to not run and fail.
How can I do that the page will only refresh when it done loading?
I've been given this code:
$("#delete_products").click(function () {
var promises = [];
$(":checkbox:checked").each(function () {
var pid = $(this).val();
promises.push($.get('delete_product.php', {
pid: pid
}));
});
$.when.apply($, promises).done(function () {
location.reload();
});
return false;
});
But this solution just doesn't work.
any suggestions?
your code seems like it should work, but i would recommend to delete all products with one call by passing array of ids.
less work for the browser, less work for the server, faster results.
UPDATED ANSWER
$("#delete_products").click(function () {
var ids = [];
$(":checkbox:checked").each(function () {
ids.push($(this).val());
});
$.post('delete.php', { 'ids': ids } }).done(function() {
alert('hells yeah!');
});
return false;
});
and as for the server side:
$commaSeperatedIds = explode(',', $_POST['ids']);
mysql_query('DELETE FROM products WHERE id IN('.mysql_real_escape_string($commaSeperatedIds).')');
Use "success" parameter of "get"
EDIT: add counter of requests.
total_requests = $(":checkbox:checked").length;
total_success = 0;
...
$.get('delete_product.php',{pid: pid}, function (data, status, xx) {
...
total_success++;
if (total_success >= total_requests) {
location.reload();
}
});
...
Possible Solution #1:
The async parameter could help. Set it to false.
Since you`re using the $.get() function, this is done with:
$.ajaxSetup({
async: false
});
 
With the $.ajax() function, you'd simply set it like:
$.ajax({
url: ...,
async: false,
success: function(data) {}
});
More info on this can be found here.
 
Possible Solution #2:
Use the .success() callback hook OR .complete() if you want to refresh the page no mather if the request failed or not.
$.get('delete_product.php',{pid: pid}).success(function(response)
{
location.reload();
});
 
Happy coding!
 
Edit:
The questioner seems to prever sUP's answer. I'd like to provide an example of how to achieve the desired functionality with jQuery:
$("#delete_products").click(function()
{
var products = [];
$(":checkbox:checked").each(function()
{
var pid = $(this).val();
products.push(pid);
});
$.post('delete_products.php', {'products': products}).done(function()
{
location.reload();
});
});
 
If you prefer to use JSON for the post data, try:
$('#delete_products').click(function()
{
var products = [];
$(':checkbox:checked').each(function()
{
products.push($(this).val());
});
// Convert the products array into JSON
products = JSON.stringify(products);
$.post('delete_products.php', {'products': products}).done(function()
{
location.reload();
});
});
In PHP you need to parse the json string as follows:
<?php
// This creates an associative array from the JSON string
$delete_products = json_decode($_POST['products'], true);
// Use explode to make a comma separated string from the array
// for use in a SQL SELECT query:
$delete_products = explode(',', $delete_products);
Info about json_decode can be found in the PHP Manual.
JSON.stringify is not supported in older browsers. Include JSON-js if you need cross browser support.
I too believe that the desired result can probably be achieved best by collecting the product IDs and then sending a single Ajax call to take care of them all.
But since the OP put the interesting question forward of how to handle multiple Ajax requests and wait for them all to be finished I have looked at the when() method again and it seems to me that the original syntax is still faulty.
According to the jQuery manual when() is a method and therefore requires to be called with one or more argument(s) in parentheses. I have not worked with promises yet and I have not tested anything but I assume that something like the following might bring at least a different result:
$("#delete_products").click(function () {
var promises = [];
$(":checkbox:checked").each(function () {
var pid = $(this).val();
promises.push($.get('delete_product.php', {
pid: pid
}));
});
$.when(promises).done(function () {
location.reload();
});
return false;
});
As I said before, I still have not quite grasped the promises mechanisms/syntax yet ...
In the original version $.when does not have any meaningful context to work on, The apply() method does provide context but only after when has done its (unseccessful) work already.

multiple xhr.get s with dojo

how do I do two xhr.gets one after the other using dojo ?
I have ....
require(["dojo/_base/xhr", "dojo/dom", "dojo/domReady!"],
function(xhr, dom) {
// Using xhr.get, as very little information is being sent
xhr.get({
// The URL of the request
url: "inc/etl2json.php?item=Execs",
// The success callback with result from server
load: function(execContent) {
dom.byId("Execs").innerHTML = execContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});
});
I would like to do another xhr.get to "inc/etl2json.php?item=Execs" and assign it to dom.byId("Elapsed").innerHTML = elapsedContent;
just call again xhr.get() inside the load function, well that if the content is supposed to change, else you could just use the same data retrieved the first time:
xhr.get({
load:function(data){
//use the first data you retrieved
xhr.get({
load: function(data2){
//do what you like with the nuew data
}
});
}
});
Although nesting is a straightforward solution it almost always leads to unreadable code, so I would do the same as #Ricardo did, but use the advantage of Dojo's Deferred (+ here) and employ chaining:
var requestUrl = "inc/etl2json.php?item=Execs";
xhr.get({ url: requestUrl})
.then(function(results) {
dom.byId("execs").innerHTML = results;
})
.then(function(results) {
return xhr.get({ url: requestUrl});
})
.then(function(results) {
dom.byId("elapsed").innerHTML = results;
})
See it in action at jsFiddle: http://jsfiddle.net/phusick/73X88/
I think you should add another xhr call for the elapsedContent. I don't see any relation between the two calls so you should make them separate. Nesting one in another is not necessary.
just add
xhr.get({
// The URL of the request
url: "inc/etl2json.php?item=Execs",
// The success callback with result from server
load: function(elapsedContent) {
dom.byId("Elapsed").innerHTML = elapsedContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});

Resources