Capturing a form data 'onsubmit' in native JS

63 views
Skip to first unread message

Neha Chriss

unread,
Apr 7, 2015, 2:49:53 PM4/7/15
to casp...@googlegroups.com
Hello,

So I've seen a few requests on stackoverflow for this style of capturing form data before it's submitted to the server-side. I've tried several of the code snippets there, but none of them work in my console (chrome), and I'm not making much progress with my own code. In many cases, the recommendations aren't doing exactly what I want - that aside, I don't know *exactly* what I'm doing with raw XHR submissions. 

I hope someone can help me do this in a way that's both orthogonal to JS and casper. 

My web app requires a set of HTTP headers (like X-CSRF-TOKEN, Content-Security-Policy) that I want to replicate, but with a set of changed REQ Body data. I want casperjs to go through a regular form submission, but immediately capture the data on submit, copy the headers, and change a request body parameter. In some cases, I want to do this iteratively: change a value and submit, check response, change the value and submit again, check response status, etc.

From a code point of view, this is as far as I can relate my needs:

1. Capture my form's POST/PUT request onsubmit
2. Copy HTTP Headers, and form data to a new XHR request
3. Submit the raw request using XHR in native JS

I can write a raw request that *looks* like a form submission, but with the missing headers and session data, the server doesn't accept this. Also, I believe I'll need to do this in native JS, as Casper's sendAJAX doesn't support the PUT method, which I'll need in some of my tests. 

I've only tried to code at the console at this point, so I can get a better sense of what I'm doing before I wrap into casper. Here's a sample of a basic attempt at just capturing the form on submit. This was borrowed from stackoverflow:

function processForm(e) { if (e.preventDefault) e.preventDefault(); // trigger an action that proves processForm is run
alert('hi hi'); 
return false; }

window.onload = function() { var form = document.getElementsByClassName('.form-primary-button'); if (form.attachEvent) { form.attachEvent("submit", processForm); } else { form.addEventListener("submit", processForm); } };
The above does not work in my browser with my web app. I click on the button with the class=form-primary-button, and nothing happens. I thought maybe i was using the wrong event to attach to 'submit' and tried 'onsubmit' instead. No luck. So I'm curious how some of you might go about doing this, or if it's even possible. The goal is to mimic the form submission exactly, but with my own values exchanged for what's initially submitted in the form. I'd appreciate any help on this, I've been enjoying casper immensely the last few years and I feel like my understanding of the platform is only improving.

Best,
Neha
Reply all
Reply to author
Forward
0 new messages