-2

so I have code in JavaScript I am trying to rewrite in Ruby and I can't figure out how to pass these parameters and parse the response in the same way with Ruby that I do in JavaScript

The javascript code:

$.post(urlToPostTo, {
    name: nameToPost,
    captchatext: "",
    index: "0"
}).done(function (response) {
    var responseHTML = $.parseHTML(response);
    var tables = $(responseHTML).find("td");
    self.pA = $(tables[2]).text();
    self.dA = $(tables[3]).text();
    self.mR = $(tables[4]).text();
    deferred.resolve(data);
}).fail(function (error) {
    deferred.resolve(data);
});

Is there a way I can do this in Ruby (potentially with HTTParty)?

Kevin
  • 177
  • 1
  • 15
  • If you use `HTTParty` you can do something like `HTTParty.post(urlToPostTo)...` http://stackoverflow.com/questions/19461333/how-can-i-implement-this-post-request-using-httparty?noredirect=1&lq=1 – jdgray May 05 '17 at 00:13
  • @jdgray yes, I know, Im having trouble getting the parameters passed correctly though. – Kevin May 05 '17 at 00:17

1 Answers1

1

First you use HTTParty to post the body values and get a response using:

post_body = [{ "name" => nameToPost,
                     "captchatext" => "",
                     "index" => "0" }]
headers = {}
result = HTTParty.post(urlToPostTo, { :body => post_body, :headers => headers })

Next, you can use Nokogiri to parse the html and find the content in a way vary similar to jquery selectors:

html_doc = Nokogiri::HTML(result.response.body)
tables = html_doc.css("td")
tables[2]
...

Nokogiri guide: http://ruby.bastardsbook.com/chapters/html-parsing/

Raphael
  • 1,760
  • 1
  • 12
  • 21
  • Getting an error that headers has to be a hash, and I'm still not getting the response expected even when fixed though – Kevin May 05 '17 at 00:34
  • Sorry, it should be `headers = {}` – Raphael May 05 '17 at 00:38
  • Sure - this is what I was doing but it seems that I am not getting the correct response though it is working in JS.. odd. – Kevin May 05 '17 at 00:41
  • You can pass an extra parameter to help you debug the request. `HTTParty.post({ :body => post_body, :debug_output => $stdout}` – Raphael May 05 '17 at 00:44
  • Can't really tell what is wrong based on this output - seems it must be a server/response issue though, going to mark this correct despite not having figured it out as this answers the original question – Kevin May 05 '17 at 01:04
  • can you simulate the original request with javascript? use the chrome network tab to check all the headers passed. Maybe something like a session cookie is sent as well. – Raphael May 05 '17 at 01:11