javascript - Storing and outputting form data -
i'm creating url-shortener, having issues getting jquery form values can output shortened url text.
here form using:
<form name="urlform"> <input type="text" name="url"> <button id="submit" type="button">submit</button> <p>result: <!-- output area. --> <span id="url-output"></span> </p> </form> and here javascript using process form-data:
// receive form when "submit" button clicked $('form[name=urlform]').submit(function (event) { console.log('form submitted'); // data in form // there many ways data using jquery (you can use class or id also) var formdata = { //element[attribute=value] 'name': $('input[name=url]').val(), }; // process form $.ajax({ type: 'post', // define type of http verb want use (post our form) url: '/createshorter', // url want post data: formdata, // our data object datatype: 'json', // type of data expect server encode: true }) // using done promise callback .done(function (data) { // log data console can see console.log(data); // here handle errors , validation messages }); // stop form submitting normal way , refreshing page event.preventdefault(); }); i believe problem lies within how collecting data in formdata variable. despite looking @ documentation, , several different attempts, nothing seems output relevant values. taking bad approach?
how can parse form information need?
the snippet non-functioning (strict security), review plunker instead. plunker demonstrates use of made form, use of plain javascript xmlhttprequest(), post real test server , receiving json in response. details commented in snippet.
snippet (non-functioning)
<!doctype html> <html> <head> </head> <body> <!--use id , name, although name isn't used in instance, can useful under different circumstances--> <form id='urlform' name="urlform"> <input type="text" id='url' name="url"> <!--use input type submit button instead, automatically trigger submit event once clicked--> <input id="submit" type="submit"> <br/> <label>result: <!--using real output element allows display data value property or content methods such innerhtml or textcontent--> <output id="urloutput"></output> </label> </form> <script> // reference form var f1 = document.getelementbyid('urlform'); // reference output var o1 = document.getelementbyid('urloutput'); // when submit event triggered... f1.onsubmit = function(e) { // prevent form submitting e.preventdefault(); // reference xhr object var req = new xmlhttprequest(); // post server req.open('post', 'http://httpbin.org/post', false); // reference formdata object var formdata = new formdata(f1); req.send(formdata); o1.value = req.response; } </script> </body> </html>
Comments
Post a Comment