Rectangle 27 2

<webview> supports a restricted set of standard DOM events out of the box. For your "close window" interception, the aptly named close event is probably the best fit.

If you want to establish a kind of communication channel between a webview guest and your app in the general case, as in your second use case with accessing Storage API, you have a couple of options:

How can a Chrome Packaged App interact with a webview (listen to event...

webview google-chrome-app
Rectangle 27 2

I agree with Richard Peck's answer. However, I would just like to point out that catering for a guest user (not logged in) is not needed. An initializer is invoked on instantiation of a new object (i.e an object's constructor).

Thus, the above Ability class could be as follows:

#app/models/ability.rb
class Ability
 include CanCan::Ability

 def initialize(user)

  if user.has_role? :admin
    can :manage, :all
  else
    can :manage, Post, user_id: user.id #-> CRUD own posts only
    can :read, :all #-> read everything
  end
 end
end

Ruby On Rails Rolify + CanCanCan + Devise allow user to edit only thei...

ruby-on-rails devise cancancan rolify
Rectangle 27 1

First of all you can't create an event through a link because the API required a http post action and with the link you will do only a get. Alternative, you can create an ICS invite and send as attachment to your guests. See the example bellow:

function sendInvites() {
  var startDate = new Date(2013,11,26, 10,0);
  var endDate = new Date(2013, 11, 26, 10,30);
  var guestMail = "mymail@mymail.com";


  var event = CalendarApp.createEvent(eventTitle, startDate, endDate);
  event.setTitle("Event Title");
  event.setDescription("My description");
  event.setLocation("My Location");


  //OR
  //var event = CalendarApp.getEventSeriesById("event id");


var ics = "BEGIN:VCALENDAR\r\nPRODID:-//Google Inc//Google Calendar     70.9054//EN\r\nVERSION:2.0\r\nCALSCALE:GREGORIAN\r\nMETHOD:REQUEST\r\nBEGIN:VEVENT\r\n";
ics+= "DTSTART:"+Utilities.formatDate(startDate, "GMT", "yyyyMMdd'T'HHmmss'Z'")
    +"\r\nDTEND:"+Utilities.formatDate(endDate, "GMT", "yyyyMMdd'T'HHmmss'Z'")+"\r\n";
ics+= "UID:"+event.getId()+"\r\n";
ics+= "SUMMARY:"+event.getTitle()+"\r\nLOCATION:"+event.getLocation()+"\r\nDESCRIPTION:\r\n";
ics+= "SEQUENCE:0\r\nSTATUS:CONFIRMED\r\nTRANSP:OPAQUE\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";


MailApp.sendEmail(guestMail, "invite", "invite body",  {attachments: [Utilities.newBlob(ics, "text/calendar")]});
}

That's very helpful, thank you. However I don't want to create an event and then send an attachment - the email itself lists a number of possible times to reserve a room/time, and the recipient has to select one in order to create the event. If I created all the events beforehand, it'd be as if they'd already reserved all the possible openings. I did notice that the insert method is POST, not GET. As such I tried embedded an html form in the email, with the POST parameters included as hidden elements. That's when I ran into authorization issues. Is there solution with an embedded form?

I guess that you will face some problems like storing the token value. Why don't you create a form inside apps script and put their link in the mail?

Hmm, I'm not quite sure I'm following you. I did generate all the email content within an apps script, and then the email they get just shows a button to click. But you're right, it's the token I'm trying to get around. Is a token strictly necessary with a public calendar?

Embedding a RESTful url in email to add a Google Calendar event - Stac...

google-apps-script google-api google-calendar google-apps google-oauth
Rectangle 27 2

1) With a Model Popup When you click on the Add Guest button, Call your Action method which returns the Guest for m in a model dialog ( jQuery UI dialog is one option to use here). Save the data using an ajax post call. One the success event, append the new guest data to the main forms list of guests or reload that part only using jquery load

2) Inpage Adding When you click on the Add Guest button, In the main form itself, Show the form ( you can dynamically create input box and save button from javascript in a variety of ways). save the data using a jQuery ajax post. Send the data as a json.As long as the parameter names matches with the property name of your ViewModel, your action method can accept the data

<a href="#" id="addNew"> Add Guest</a>

<div id="divForm" style="display:none">
    <input type="text" id="txtName" />
    <input type="text" id="txtEmail" />
    <input type="button" id="btnSaveGuest" value="Save"/>
</div>
<ul>

<div id="divGuests"></div>
$(function(){
  //Show the hidden form
  $("#addNew").click(function(){
      $("#divForm").fadeIn(300);
  }); 

   //Save the new guest details
   $("#btnSaveGuest").click(function() {
     var name=$("#txtName").val();
     var email=$("#txtEmail").val();
     $.ajax({
        url: '@Url.Action("SaveGuest","Guest")',
        data: {Name: name, EmailAddress :email},
       success: function(data) {

        if(data=="true")
        {
          //Saved successfully.May be append to list of Guest
          $("#divGuests").append("<p>"+name+"</p>");
        }
        else
        {
          //Error. Show msg to user
        }
       }
     });
   });
});
[HttpPost]
public ActionResult SaveGuest(Guest objGuest)
{
  try
  {
  // read the objGuest property values and Save to db

   return "true";
  }
  catch(Exception e)
  {
     //Log error
     return "false";
  }
}

Here is a sample app : http://jsfiddle.net/Qzk3F/16/ (some values are hardcoded in the example)

Model with child collections in ASP.NET MVC 3 - Stack Overflow

asp.net asp.net-mvc asp.net-mvc-3
Rectangle 27 584

The following line needs to be added to the $http object that is passed:

headers: {'Content-Type': 'application/x-www-form-urlencoded'}

And the data passed should be converted to a URL-encoded string:

> $.param({fkey: "key"})
'fkey=key'

So you have something like:

$http({
    method: 'POST',
    url: url,
    data: $.param({fkey: "key"}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

Is there a way for the json > url encoding of the data to happen automatically or to specify this happening for every POST or PUT method?

+1 @mjibson, For me even passing the headers was not working, until i saw your answer containing this: var xsrf = $.param({fkey: "key"}); Thats stupid, why can't angular do it internally?

headers: {Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

Instead of using jQuery's param function, just set the params property on the $http request and it will do what the jQuery.param method does as long as the Content-Type header is 'application/x-www-form-urlencoded' - stackoverflow.com/questions/18967307/

@spig Yes, it will do what jQuery.param does, but, if you use the params property your properties will be encoded as part of the request URL instead of in the body - even if you have specified the application/x-www-form-urlencoded header.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 583

The following line needs to be added to the $http object that is passed:

headers: {'Content-Type': 'application/x-www-form-urlencoded'}

And the data passed should be converted to a URL-encoded string:

> $.param({fkey: "key"})
'fkey=key'

So you have something like:

$http({
    method: 'POST',
    url: url,
    data: $.param({fkey: "key"}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

Is there a way for the json > url encoding of the data to happen automatically or to specify this happening for every POST or PUT method?

+1 @mjibson, For me even passing the headers was not working, until i saw your answer containing this: var xsrf = $.param({fkey: "key"}); Thats stupid, why can't angular do it internally?

headers: {Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

Instead of using jQuery's param function, just set the params property on the $http request and it will do what the jQuery.param method does as long as the Content-Type header is 'application/x-www-form-urlencoded' - stackoverflow.com/questions/18967307/

@spig Yes, it will do what jQuery.param does, but, if you use the params property your properties will be encoded as part of the request URL instead of in the body - even if you have specified the application/x-www-form-urlencoded header.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 189

If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: xsrf
}).success(function () {});

This method works for me in angular 1.2.x, and I think it is the best answer because it is elegant, it works in core angular and does not depend on any external libraries like jQuery.

I came across a problem when using this method inside of a $resource action. The form data was also including functions for $get, $save, etc. The solution was to alter the for statement a little to use angular.forEach instead.

Note that in contrast to $.param() this method does not work recursively on arrays/objects.

I'd check that obj[p] is not null or undefined. Otherwise you'll end up sending "null" or "undefined" string as the value.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 189

If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: xsrf
}).success(function () {});

This method works for me in angular 1.2.x, and I think it is the best answer because it is elegant, it works in core angular and does not depend on any external libraries like jQuery.

I came across a problem when using this method inside of a $resource action. The form data was also including functions for $get, $save, etc. The solution was to alter the for statement a little to use angular.forEach instead.

Note that in contrast to $.param() this method does not work recursively on arrays/objects.

I'd check that obj[p] is not null or undefined. Otherwise you'll end up sending "null" or "undefined" string as the value.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 584

The following line needs to be added to the $http object that is passed:

headers: {'Content-Type': 'application/x-www-form-urlencoded'}

And the data passed should be converted to a URL-encoded string:

> $.param({fkey: "key"})
'fkey=key'

So you have something like:

$http({
    method: 'POST',
    url: url,
    data: $.param({fkey: "key"}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

Is there a way for the json > url encoding of the data to happen automatically or to specify this happening for every POST or PUT method?

+1 @mjibson, For me even passing the headers was not working, until i saw your answer containing this: var xsrf = $.param({fkey: "key"}); Thats stupid, why can't angular do it internally?

headers: {Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

Instead of using jQuery's param function, just set the params property on the $http request and it will do what the jQuery.param method does as long as the Content-Type header is 'application/x-www-form-urlencoded' - stackoverflow.com/questions/18967307/

@spig Yes, it will do what jQuery.param does, but, if you use the params property your properties will be encoded as part of the request URL instead of in the body - even if you have specified the application/x-www-form-urlencoded header.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 91

The continued confusion surrounding this issue inspired me to write a blog post about it. The solution I propose in this post is better than your current top rated solution because it does not restrict you to parametrizing your data object for $http service calls; i.e. with my solution you can simply continue to pass actual data objects to $http.post(), etc. and still achieve the desired result.

Also, the top rated answer relies on the inclusion of full jQuery in the page for the $.param() function, whereas my solution is jQuery agnostic, pure AngularJS ready.

+1 for the detailed blog, but the fact that there is a need for this is horrible...

Yes, maybe horrible on two levels: 1) that AngularJS decided to upend a de facto (though admittedly misguided) standard, and 2) that PHP (and who knows whatever other server-side languages) somehow doesn't automatically detect application/json input. :P

Would it be possible that angularjs automatically adapts to the content type and encode accordingly? Is it foreseen?

I (like many others) came across this that my backend ASP.NET didn't 'natively' support this. If you don't want to change AngularJS' behavior (which I didn't, because my API return JSON, why not have it accept JSON too, it's more flexible than form data) you can read from the Request.InputStream and then handle it any way you want it. (I chose to deserialize it to dynamic for ease of use.)

No, it wouldn't be able to know what the server accepts for any particular endpoint. It would be better for server languages to accept application/json input since that is such a prevalent format now, but in my opinion it is much easier and more reliable for AngularJS to send x-www-form-urlencoded out of the box. I would be surprised if they changed that at this point, though.

Downvoted because this isn't a self-contained answer. Good answers don't just link somewhere else. From How to Answer: "Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 91

The continued confusion surrounding this issue inspired me to write a blog post about it. The solution I propose in this post is better than your current top rated solution because it does not restrict you to parametrizing your data object for $http service calls; i.e. with my solution you can simply continue to pass actual data objects to $http.post(), etc. and still achieve the desired result.

Also, the top rated answer relies on the inclusion of full jQuery in the page for the $.param() function, whereas my solution is jQuery agnostic, pure AngularJS ready.

+1 for the detailed blog, but the fact that there is a need for this is horrible...

Yes, maybe horrible on two levels: 1) that AngularJS decided to upend a de facto (though admittedly misguided) standard, and 2) that PHP (and who knows whatever other server-side languages) somehow doesn't automatically detect application/json input. :P

Would it be possible that angularjs automatically adapts to the content type and encode accordingly? Is it foreseen?

I (like many others) came across this that my backend ASP.NET didn't 'natively' support this. If you don't want to change AngularJS' behavior (which I didn't, because my API return JSON, why not have it accept JSON too, it's more flexible than form data) you can read from the Request.InputStream and then handle it any way you want it. (I chose to deserialize it to dynamic for ease of use.)

Downvoted because this isn't a self-contained answer. Good answers don't just link somewhere else. From How to Answer: "Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 80

I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:

.config(['$httpProvider', function ($httpProvider) {
  // Intercept POST requests, convert to standard form encoding
  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
    var key, result = [];

    if (typeof data === "string")
      return data;

    for (key in data) {
      if (data.hasOwnProperty(key))
        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
    }
    return result.join("&");
  });
}]);

Also took care to use unshift() so the other transformations remain undisturbed. Good work.

Works like a charm - even if appended to a resource definition.

perfect! worked fine for me! sad angular is not natively supporting this.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 80

I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:

.config(['$httpProvider', function ($httpProvider) {
  // Intercept POST requests, convert to standard form encoding
  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
    var key, result = [];

    if (typeof data === "string")
      return data;

    for (key in data) {
      if (data.hasOwnProperty(key))
        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
    }
    return result.join("&");
  });
}]);

Also took care to use unshift() so the other transformations remain undisturbed. Good work.

perfect! worked fine for me! sad angular is not natively supporting this.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 55

As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.

$http.post('http://example.com', $httpParamSerializer(formDataObj)).
    success(function(data){/* response status 200-299 */}).
    error(function(data){/* response status 400-999 */});

Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

To do this only for the current post, the headers property of the request-object needs to be modified:

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': 'application/x-www-form-urlencoded'
 },
 data: $httpParamSerializer(formDataObj)
};

$http(req);

How can we do the same on a custom $resource factory ?

Note: I upgrade an app from Angular 1.3 to 1.5. It changed the headers in the transformRequest. For some reason, the method above doesn't work for me, Angular adds double quotes around the URL-encoded string. Solved with transformRequest: $httpParamSerializer, data: formDataObj. Thanks for the solution.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 55

As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.

$http.post('http://example.com', $httpParamSerializer(formDataObj)).
    success(function(data){/* response status 200-299 */}).
    error(function(data){/* response status 400-999 */});

Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

To do this only for the current post, the headers property of the request-object needs to be modified:

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': 'application/x-www-form-urlencoded'
 },
 data: $httpParamSerializer(formDataObj)
};

$http(req);

How can we do the same on a custom $resource factory ?

Note: I upgrade an app from Angular 1.3 to 1.5. It changed the headers in the transformRequest. For some reason, the method above doesn't work for me, Angular adds double quotes around the URL-encoded string. Solved with transformRequest: $httpParamSerializer, data: formDataObj. Thanks for the solution.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 189

If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: xsrf
}).success(function () {});

This method works for me in angular 1.2.x, and I think it is the best answer because it is elegant, it works in core angular and does not depend on any external libraries like jQuery.

I came across a problem when using this method inside of a $resource action. The form data was also including functions for $get, $save, etc. The solution was to alter the for statement a little to use angular.forEach instead.

Note that in contrast to $.param() this method does not work recursively on arrays/objects.

I'd check that obj[p] is not null or undefined. Otherwise you'll end up sending "null" or "undefined" string as the value.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 33

I can't say enough good things about Nick Sieger's multipart-post library.

It adds support for multipart posting directly to Net::HTTP, removing your need to manually worry about boundaries or big libraries that may have different goals than your own.

Here is a little example on how to use it from the README:

require 'net/http/post/multipart'

url = URI.parse('http://www.example.com/upload')
File.open("./image.jpg") do |jpg|
  req = Net::HTTP::Post::Multipart.new url.path,
    "file" => UploadIO.new(jpg, "image/jpeg", "image.jpg")
  res = Net::HTTP.start(url.host, url.port) do |http|
    http.request(req)
  end
end
$ sudo gem install multipart-post

If you're connecting via SSL you need to start the connection like this:

n = Net::HTTP.new(url.host, url.port) 
n.use_ssl = true
# for debugging dev server
#n.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = n.start do |http|

That one did it for me, exactly what I was looking for and exactly what should be included without the need for a gem. Ruby is so far ahead, yet so far behind.

awesome, this comes as a God send! used this to monkeypatch the OAuth gem to support file uploads. took me only 5 minutes.

@matthias I'm trying to upload photo with OAuth gem, but failed. could you give me some example of your monkeypatch?

The patch was quite specific to my script (quick-and-dirty), but have a look at it and maybe you can some up with a more generic approach (gist.github.com/974084)

Multipart does not support request headers. So if you for example want to use the JIRA REST interface, multipart will just be a waste of valuable time.

Ruby: How to post a file via HTTP as multipart/form-data? - Stack Over...

ruby http post
Rectangle 27 91

The continued confusion surrounding this issue inspired me to write a blog post about it. The solution I propose in this post is better than your current top rated solution because it does not restrict you to parametrizing your data object for $http service calls; i.e. with my solution you can simply continue to pass actual data objects to $http.post(), etc. and still achieve the desired result.

Also, the top rated answer relies on the inclusion of full jQuery in the page for the $.param() function, whereas my solution is jQuery agnostic, pure AngularJS ready.

+1 for the detailed blog, but the fact that there is a need for this is horrible...

Yes, maybe horrible on two levels: 1) that AngularJS decided to upend a de facto (though admittedly misguided) standard, and 2) that PHP (and who knows whatever other server-side languages) somehow doesn't automatically detect application/json input. :P

Would it be possible that angularjs automatically adapts to the content type and encode accordingly? Is it foreseen?

I (like many others) came across this that my backend ASP.NET didn't 'natively' support this. If you don't want to change AngularJS' behavior (which I didn't, because my API return JSON, why not have it accept JSON too, it's more flexible than form data) you can read from the Request.InputStream and then handle it any way you want it. (I chose to deserialize it to dynamic for ease of use.)

Downvoted because this isn't a self-contained answer. Good answers don't just link somewhere else. From How to Answer: "Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 80

I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:

.config(['$httpProvider', function ($httpProvider) {
  // Intercept POST requests, convert to standard form encoding
  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
    var key, result = [];

    if (typeof data === "string")
      return data;

    for (key in data) {
      if (data.hasOwnProperty(key))
        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
    }
    return result.join("&");
  });
}]);

Also took care to use unshift() so the other transformations remain undisturbed. Good work.

perfect! worked fine for me! sad angular is not natively supporting this.

ajax - How can I post data as form data instead of a request payload? ...

ajax angularjs post angular-http
Rectangle 27 25

After you have set a static page as your home page you can add this to your functions.php and you are good to go. This will call the archive-POSTTYPE.php template correctly as well.

add_action("pre_get_posts", "custom_front_page");
function custom_front_page($wp_query){
    //Ensure this filter isn't applied to the admin area
    if(is_admin()) {
        return;
    }

    if($wp_query->get('page_id') == get_option('page_on_front')):

        $wp_query->set('post_type', 'CUSTOM POST TYPE NAME HERE');
        $wp_query->set('page_id', ''); //Empty

        //Set properties that describe the page to reflect that
        //we aren't really displaying a static page
        $wp_query->is_page = 0;
        $wp_query->is_singular = 0;
        $wp_query->is_post_type_archive = 1;
        $wp_query->is_archive = 1;

    endif;

}

This function needs if(is_admin()) return; at the very beginning, otherwise it messes with the admin area.

While this worked for me, my primary and secondary menus disappeared as result.

It's almost correctly. This code is changing all wp_queries, so it should be if ( is_home() ) instead of if ($wp_query->get.....)

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

custom-post-types functions wp-query custom-post-type-archives