RSS

Tag Archives: jquery

POST a file, read a JSON response

Here’s a trick to send a file to a server AND read a response from it, in the same context.
I used it with a Node.js server (Express + busboy) and it worked like a charm.

When using HTML forms, you can submit stuff to a server but you can’t read a response from it.
If you need some kind of “send data” → (do something server side) → “read response” it can be painful.

I wrote a workaround to manage this kind of situation. It is pretty simple:
– prepare a form as usual
– block the original event
– build an ajax request as a POST method

Here’s the code

Advertisements
 
Leave a comment

Posted by on 2017/07/14 in dev, Uncategorized

 

Tags: , ,

I promise you a working jsdom

Working with jsdom is incredible, but most of the times you feel drowning in the callback hell
.
Here’s a template (soon on my github) that makes everything oven-ready 😉

UPDATE: added V2 that handles the NEW jsdom (see below)

And, as always, under 100 lines of code! =)

 
Leave a comment

Posted by on 2015/10/15 in dev

 

Tags: , , ,

Express.js and jsonp

Express.js has a very good jsonp handler, the key is to use it in the right way =)

The first step is to ensure the callback name. The default value is “callback” so on a res.jsonp(..) the server will look for req.query[“callback”] to build the response.
This value can be overridden with an app.set(‘jsonp callback name’,..).

app.js:

app.get('/', function(req, res) {
  var jsonp_callback = app.get('jsonp callback name');
  var jsonp = (req.query[jsonp_callback]);
  var result = [{},{},.....];
  if (jsonp) res.jsonp(result);
  else res.json(result);
});

jQuery

When asking for jsonp stuff, jQuery will handle the whole request/response stuff.
We just need to say the dataType and the callback key.

Here’s an example of the client side call:

$.ajax({
  url: "http://localhost:3000/",
  jsonp: "callback",
  dataType: "jsonp",
  success: function( response ) {
    console.log( response );
  },
  error: function(XHR, textStatus, errorThrown) {
    console.log(XHR);
    console.log(textStatus);
    console.log(errorThrown);
  }
});

AngularJS

Angular will expect the callback will be named “JSON_CALLBACK” so we have to use it this way:

$http.jsonp('http://localhost:3000?callback=JSON_CALLBACK')
  .success(function(data, status, headers, config) {
    console.log( data );
  })
  .error(function(data, status, headers, config) {
    console.log(data);
    console.log(status);
  });
 
Leave a comment

Posted by on 2015/02/04 in dev

 

Tags: , , , ,

Show me your events

“Which javascript event best fits my requirements?”

To answer the question let’s inspect the given element and get all its bound events:

var evts = ​$._data( $("#element")[0], "events" );

Easy as an easy thing!

 
Leave a comment

Posted by on 2014/06/04 in dev

 

Tags: ,

$(..).selectable_and_resizable()

The .selectable() and .resizable() jQueryUI plugins can’t live together. They’re not enemies, but everyone want the events monopoly and they go in conflict.
Here’s the trick to make them work happily together.
I build a resizable wrapper for the selectable “ul” then, on resize, I’ll resize the “ul” to fit the container.
Note: I know there’s an issue also with the .draggable() plugin but I haven’t tested it yet.

The code:

<style>
.ui-selecting { background: #FECA40; }
.ui-selected { background: #F39814; color: white; }
</style>

$(function(){
  // let's get the list and build a wrapper on it
  var ul = $("#thelist");
  var ulwrap = ul.wrap($("
")).parent(); // .wrap(..) uses a copy // some style ul.css({"border": "4px solid blue", "overflow":"hidden", "list-style-type":"none", "margin": 0, "padding": 7}); ul.find("li").css({"text-overflow":"ellipsis", "overflow":"hidden", "white-space":"nowrap"}); ulwrap.css({"border": "4px solid black"}); // attach the plugin ul.selectable(); ulwrap.resizable().on("resize", function(event, ui) { var w = ui.element.width() - (ul.outerWidth(true) - ul.width()); var h = ui.element.height() - (ul.outerHeight(true) - ul.height()); ul.width(w).height(h); }); });

The result:
jquery_resizable_n_selectable
See the black/blue borders as reference of what’s happening. The inner white border is the “padding: 7px” style (seek the “ul.css(..)” in the code).

 
Leave a comment

Posted by on 2014/03/18 in dev

 

Tags: , , ,

jap: just another player

Recently I was writing an audio streamer over http in node.js and I needed an audio player to test all the stuff.
It all started as a test page for all that stuff. It was a long time that I was looking for a good audio player cross platform … I tested many players (some of them very good!) but none fits my requirements. Maybe it’s just my fault (too many requirements or too few desire to learn to use them) =)
Here’s born the “jap“!

The funny part is that the jap heavily depends on the jQueryUI theme framework, so you can easily switch theme using their Themeroller.

Here’s the result (released under the MIT license):
https://github.com/pste/jap

Everybody loves screenshots:

Custom theme running on Firefox (Kubuntu)

customtheme_firefox_kubuntu

Theme “dot-luv” running on Chrome (Windows 7)

dot-luv_chrome_win7

Theme “eggplant” running on Rekonq (Kubuntu)

eggplant_rekonq_kubuntu

Theme “redmond” running on IE9 (Windows 7)

redmond_ie9_win7

 
Leave a comment

Posted by on 2014/02/28 in dev

 

Tags: , , , , ,

Handling jQueryUI modal dialogs inside ASP.NET UpdatePanels

Some time ago I had some problem handling a modal jQueryUI dialog inside an UpdatePanel. When the dialog was closed an
TypeError: $(…).data(…) is null
.data( widgetFullName )._focusTabbable(); jquery-ui.js (line 10343)
error was raised into the FireBug console.

Here’s the the mystery solved, as published in http://forum.jquery.com:

the $.ui.dialog.overlayInstances global variable keeps tracks of every overlay created (maybe from multiple modal dialogs). This variable is initializated during the inclusion of the jqueryui.js file and its initial value is 0.
It’s a global, so you can access it from everywhere.

An opened modal dialog creates an overlay and increments that variable; when you close (or destroy) that dialog the variable will be decremented.

What happens if the dialog is inside an UpdatePanel?
In my test the dialog was built closed (autoOpen=false). Inside the dialog there’s a postback button: it generate a partial reload of the page and only the UpdatePanel will be rendered again.

Some event somewhere calls the .dialog(“open”) and the dialog appears (overlayInstances = 1). Now if we click that postback button, the dialog will be flushed away (not destroyed nor closed!) and the UpdatePanel will be rendered with a new copy of the dialog.
The dialog (again) starts closed but now it will be opened: the .dialog(“open”) is called and overlayInstances++ will be executed.
The $.ui.dialog.overlayInstances isn’t reinitialized, and now its value is (wrongly) 2!.

One final note:
I created another test case: the same page in HTML / javascript, with a postback emulation.
I saw that everything was running clear….until I noticed that I was replacing the UpdatePanel content with a $(“#updatePanel”).html(remoteData).
The .html() funtion is SAFE!! It destroys the inner elements and detach their events. =)
Using a document.getElementById(“updatePanel”).innerHTML = remoteData I saw the overlayInstances problem again.

The fix (updated!) :

I need to keep the balance between “open” and “close” calls to avoid the extra overlay: on every postback button I need to add a js click event that close the dialog. This will forces a _destroyOverlay event that keeps aligned the overlayInstances global value.
Here’s the code:

$('form').on("submit", function () {
  // on EVERY postback the overlay counter will be decremented.
  // if the overlay exists and will be unsafely destroyed (POSTBACK) => ok (because the destructor of the overlay has not been called)
  // if the overlay exists and will be safely destroyed (before POSTBACK) => fails! Please avoid closing dialogs in POSTBACK buttons. It is safe to set the $(settings.popupState).val('0') then postback
  // if the overlay exists and will be safely destroyed (NO POST) => ok (because the "submit" will not be raised)
  // if there's no overlay => it's ok (there's a safeness test on 0)
  if ($.ui.dialog.overlayInstances > 0)
    $.ui.dialog.overlayInstances--; // emulate the dialog closure: very rude, sir
});

This was the old fix...it has some issues:
$('input[type="submit"]', $popup)
  .add('input[type="image"]', $popup)
  .click(function () {
    $popup.dialog('close');
});

If the dialog was opened it is closed before the page load. On page load it will be (re)opened.
If the dialog was closed, it is safe to call an extra close on it.
The dialog is modal, so only inner buttons can raise a postback

 
Leave a comment

Posted by on 2013/08/20 in dev

 

Tags: , , , , ,