Can not fill automatically form with mechanize on ruby - ruby-on-rails

I am trying to test mechanize gem. I would like to subscribe to a website using the form. I selected all the elements correctly ( I guess) but the submit button, does not submit the form. When the form is submitted a mail is instantly received. I am a new to the gem, and I am testing registering to a website with a single mandatory field. I am using the webservice for spam mail to check if it works, so every mail field could substitute with anything before #moncourrier.fr.nf and later check if a mail is received on yopmail website, but I got nothing. Do you have any idea why is not working?
require 'rubygems'
require 'mechanize'
require'pry'
agent = Mechanize.new
agent.get('http://blackburnecreek.com/newsletter-registration') do |page|
form=agent.page.forms[1]
button=form.button_with(:value => "Subscribe")
agent.page.forms[1]["EMAIL"]= "testmechanizegem#moncourrier.fr.nf"
agent.submit(form, button)
end

Your form is not getting submitted, because the actual form uses jquery which submits the form with some extra params. They are unbinding the submit event of form and are performing a ajax request to submit the form instead with an extra param id.
You can confirm so by looking at the request being initiated in network tab of your browser it contains following params:
Also the page runs following javascript which adds the extra id param to the request:
function mce_init_form(){
jQuery(document).ready( function(jQuery) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = jQuery("#mc-embedded-subscribe-form").validate(options);
jQuery("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://blackburnecreek.us8.list-manage.com/subscribe/post-json?u=68692d660a16c9b7e4be6f51e&id=f19ba31349&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
See the url: part in above function. So when you're submitting it via mechanize you're performing an invalid request(no param id).
I guess mechanize doesn't support execution of javascript. I would recommend you to use capybara which uses web drivers like poltergiest that facilitates support for js execution.

Related

Catch and pass hangout url to my rails app

I have a button to start a google hangout, everything works great, now I need to get the url using the
gapi.hangout.getHangoutUrl();
but I since this is a JS on my server, I know is possible to pass this to my app. But I don't know how (AJAX or anything else). I need this, because other user could join to this hangout.
Any suggestion with code would be appreciate
Within your hangout script....
Include jQuery - it's useful for X-browser support.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Get the Hangout URL:
var hoUrl = gapi.hangout.getHangoutUrl();
Get/Post the hangout URL to your server:
var uri = encodeURI(server + '?hoUrl=' + hoUrl);
$.ajax(uri,
{
async: true,
beforeSend: function(request) {
// Any beforesend code goes here, e.g. adding headers.
},
data: data,
error: function(jqhr, status, error){
// Error handling goes here.
},
type: verb,
success: callback
});
Handle the AJAX GET request and do your magic with the hoUrl parameter.
To clarify further:
A URL is formed before the AJAX get request to include a GET parameter, hoUrl, that has the hangout URL in it. Your server just needs to use whatever CGI/parameter parser to retrieve the 'hoUrl' parameter and then do whatever backend magic you want to do with it. Hope that helps to clarify.

Posting form between 2 rails applications including files

I am trying to post a form from one rails app to another hosted on different domains and including files.
I attempted:
$(document).on("click", ".application-form .submission input", function(e){
e.preventDefault();
var form = $(".application-form form");
var data = new FormData(form);
var url = "http://example.com/action";
$.ajax({
url: url,
type: 'POST',
success: function(){
alert('success');
},
error: function(){
alert('error');
},
data: data,
cache: false,
contentType: false,
processData: false
});
});
But the remote server doesn't receive any data, params merely contains the controller name and action.
I also have tried using remotipart and setting up my form with form_for(#application, url: "http://example.com/action", html: {multipart: true}, remote: true) and if I include a file, the server receives [object Object] instead of correct param names and values. If I do not include a file, then the params are sent and received correctly, but I need to include files with the upload.
What is going on to cause [object Object] to replace all my form data when I include a file? Using remotipart 1.2.1. And I've seen this and it does not apply.
There are a lot of issues with attempting what you are:
Cross Domain Requests (CORS)
Form
Uploading
CORS
Your first issue is you have to ensure you're able to pass the data between the two domains. CORS is a standard protocol, whereby you can only send requests to pre-approved domains
Basically, you need some way to whitelist the possible connecting domains, and with Rails, you'll be best to use the RACK-CORS gem
I would begin by ensuring this is set up on your "receiving" domain
Form
Secondly, you need to compile the correct form data when you submit
I would use the .serialize() function:
$(document).on("click", ".application-form .submission input", function(e){
e.preventDefault();
var form = $(".application-form form");
var data = form.serialize();
var url = "http://example.com/action";
$.ajax({
url: url,
type: 'POST',
success: function(){
alert('success');
},
error: function(){
alert('error');
},
data: data,
cache: false,
contentType: false,
processData: false
});
});
This will probably explain the lack of params being sent to your other domain
Upload
Uploading files creates a totally new issue, as it takes a lot to get the file-upload process to work through ajax
There are plugins such as JQuery-FileUpload-Rails allow you to upload files through ajax. From my understanding, this works by providing custom middleware to handle the file upload over ajax. I'm not totally sure how it works, but I know it does, as we've used t multiple times
In general, you cannot directly upload files from a form via AJAX. You have to 'fake' it using either a hidden iframe, Flash, or something similar (might be different in the newest browsers). The jQuery Form plugin does a good job of simplifying this, and there are lots of other plugins as well to help with this.

MVC Web Api not getting called from javascript ajax

I have a Durandal/Hot Towel test app I'm trying to wire up. I have the below ajax call but I'm getting a 404 error.
GET http/.../api/Pizza/GetPizzasByOrderId?%22a8926610-a713-494c-bb15-46f6487a01c7%22 404 (Not Found)
I can manually change the url to:
http/.../api/GetPizzasByOrderId?orderId=a8926610-a713-494c-bb15-46f6487a01c7
It works. But I would like to know why the other call isn't working or more so, why is the ajax messing the parameter up in the URL and not as data like it does with complex objects. I have a get and a save that is working just fine. The get has zero params and the save is passing a complex object in.
C# Web Api Controller:
public class PizzaController : ApiController
{
[HttpGet]
public IEnumerable<Pizza> GetPizzasByOrderId(Guid orderId)
{
return DATA.GetPizzasByOrderId(orderId);
}
}
JAVASCRIPT:
var dataCall = $.ajax(config.getPizzasByOrderIdUrl, {
data: ko.toJSON(orderId),
type: "get",
contentType: "application/json"
});
Should I just change my JavaScript code to the below and be done with it or is there a better way to talk to the Api?
var getPizzasByOrderId = function (orderId) {
return Q.when($.getJSON(config.getPizzasByOrderIdUrl + "?orderId=" + orderId));
};
You could either use the code as you have it in that last code block, or you could pass in an object in place of your orderId as in the code block below. Either way, the difference is that the orderId parameter is being named.
var dataCall = $.ajax({
url: config.getPizzasByOrderIdUrl,
type: "GET",
data: {orderId : orderId},
});
In regard to why $.ajax() works fine for your POST, you can check this out pretty easily by running these two bits of code and viewing the requests that go across the wire. I recommend using google chrome.
Load a page that has jQuery loaded
Open the developer tools and go to the console
Enter the following code snippet
$.ajax("", {
data: {orderId: 123},
type: "get",
contentType: "application/json"
});
Switch to the network tab and click on the one that ends in ?orderId=123
Notice that it does have the data appended as query string parameters
In the snippet above, replace the "get" with "post"
After you hit enter, you should see another request on the network tab of the developer tools.
Notice that when changing nothing but the request type, the data is moved from the query string to the body. As noted in the comments, WebApi will pull from the body of the request and use the model binder to populate the complex object.

ajax request in rails 2 not working

function ajaxRequest(){
$.ajax({
type: 'GET',
url: 'client/orders/send_mail_to_notaries',
data: { subject: "hi" }
});
return false;
}
It doesn't pass any params in controller.Can any one trigger this out?
Following the question that you have asked today morning page.replace_html method in rails 2 i guess you are using prototype.
Can you check if jQuery is included? Unless jQuery is included this ajax request will not work.
I just tried the method you're using and it worked for me. Perhaps there's a problem with the router/controller?
When debugging ajax it's very handy to use the Chrome developer toolbar. Bring it up, run the javascript and see what happens.
To see the response from the server you can then flip to the Network tab to see what the response is.

Unable to post files using ajax post

We use ASP.Net Mvc 4.0.
My objecctive is to save a form with both normal input fields as well as file input fields.
I should be able to add extra data while posting.
I should be able to do perform few actions on 'Ajax Post's Success.
We used ajax post to post the form data as we could accomplish above 2, but failed in serializing and posting of files to server.
Whenever we post using ajax post, always Request.Files.Count == 0, when i check in my controller's Post Action.
ajax post i have used is:
function PostData(formId, eventSource, eventName, eventArgs, controlId) {
var $dialogForm = $("#" + formId + "Form");
fdata = $dialogForm.serialize();
fdata = fdata + '&eventSource=' + eventSource + "&eventName=" + eventName + '&eventArgs=' + eventArgs;
$.ajax({
url: $dialogForm.attr("action"),
type: $dialogForm.attr("method"),
cache: false,
data: fdata,
success: function (result) {
ProcessEvent(result);
}
});
}
Please provide me a solution for this!
well you cannot upload files when you go with the concept of ajax. But there are tweaks which are used to upload file and form data using ajax. Whenever a file type is encountered in a form the form data along with file can be copied to an iframe and the iframe can be submitted which give you a feel that file has been uploaded along with other form data using ajax.
There are various plugin available in jquery which ease this task for you.
One of my favourite is ajax form
http://malsup.com/jquery/form/#file-upload
You can use this one..

Resources