javascript - How to supply value to jquery ajax variable via a FORM? -
how can following modified forminput textarea form box accepts user input, rather hard coded now?
once form submitted, populate forminput in following code:
data: json.stringify({json:*forminput*}),
in textarea box, data pasted in in javascript below.
<html> <head> <title></title> </head> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("#postit").on("click", function () { var forminput = [{ "field1":"100", "field2":"2000", "field3":"400", }, { "field1":"110", "field2":"2200", "field3":"520" }]; $.ajax({ type: "post", contenttype: "application/json; charset=utf-8", url: "http://localhost/capturedata", data: json.stringify({json:forminput}), datatype: 'json', success: function (data) { } }); }); }); </script> <a href="#" id="postit">submit</a> </body> </html>
the whole idea doesn't make sense because user might enter value not valid json. in question said "data pasted in in javascript below" - if isn't? or if user enters is valid json isn't remotely format you're expecting? user might enter {"this":"is valid json"}
, accepted , submitted not server expecting.
having said that, take requirement literally implement adding following somewhere on page:
<textarea id="forminput"></textarea>
and in js function value with:
var forminput = $("#forminput").val();
...which give value string. if wanted use object use forminput
variable shown in question it'd need be:
var forminput = $.parsejson( $("#forminput").val() );
so address point user entering invalid values, this:
try { var forminput = $.parsejson( $("#forminput").val() ); // use forminput } catch (e) { alert("invalid input: " + e.message); }
...but catch general invalid json errors, won't catch cases user has entered valid json of wrong format needs.
Comments
Post a Comment