HTML form with no input selector on code [duplicate] - javascript

This question already has answers here:
Creating 'form' in javascript without html form
(4 answers)
Closed 9 years ago.
Is it possible to create an HTML form with no input selectors in page and create these "input" objects via javascript and then submit it? How can I create these "items"?
Or do I have to always create any "item" to submit previously in the HTML code?
So, can I avoid to create annoying hidden inputs in order to send javascript variables? I am not really able to find any tutorial or examples about it...
Thank you very much for your help.

like this, using jquery
$('<form>', {
"id": "getInvoiceImage",
"html": '<input type="text" id="componentInvoicId" name="componentInvoicId" value="' + componentInvoiceId + '" />',
"action": window.siteRoot + 'ComponentInvoice/GetInvoiceImage/'
}).appendTo(document.body).submit();
the MUCH better way:
$.post(url, { value1: "foo", value2: "bar" } );
and if you insist on doing it with a form, here's the generalized function so you can just pass it the json data
var postRequest = function (uri, data) {
data = data || {};
var form = $('<form method="post" class="js:hidden">').attr('action', uri);
$.each(data, function(name, value) {
var input = $('<input type="hidden">')
.attr('name', name)
.attr('value', value);
form.append(input);
});
$('body').append(form);
form.submit();
};

Yes, this can be done, even completely without using a <form>.
Check out jQuery as a starter (http://api.jquery.com). For example, if you want to know the clients device width, you could add this code:
$(document).ready(function() {
$.ajax( {
url: http://yourdomain.com/yourscript.php,
dataType: 'json',
type: 'POST',
data: {
w: $(window).width,
h: $(window).height
}
});
});
This would submit the parameters w and h to your application, containing window width and height. Just as an example.

Related

parse name from user input when using jquery serialize

I am trying to grab user input from a dynamic form using jquery serialize. My form looks like this
<form id="lookUpForm">
<input name="q" id="websterInput" />
<button onclick="webster(); return false;">Search</button>
</form>
I want to take the input, and attach it to the end of websters dictionary URL to search for a word.
http://www.merriam-webster.com/dictionary/ + (user input)
When you run an alert to see what the value of 'q' is, you get
q=input
so for example if I put 'cats'
the alert would say q=cats.
I want the the string to just be what the user entered. However, you need to give the input a name to use seralize. So how can I take the user input, and strip out the 'q=' part.
EDIT
as requested here is the function I'm calling. Note. I HAVE to use serialize(); This isnt an option.
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
type: 'GET',
crossDomain: 'true',
url: "http://www.merriam-webster.com/" + stringHolder,
success: function (data) {
console.log(data);
console.log("http://www.merriam-webster.com/" + stringHolder);
},
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" + stringHolder);
}
});
};
You can just access it using val method of jQuery
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
// (...) removed some code for brevity
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" +
$('#websterInput').val()); // I suppose you want the user-input here
}
});
};
You could use serializeArray().
And then do something like this and put your string together like you want to
var array = $("#lookUpForm").serializeArray();
$(array ).each(function(){
alert(this.value);
});

Events not triggered when posting json string using jquery [duplicate]

This question already has answers here:
jQuery posting JSON
(3 answers)
Closed 8 years ago.
I'm totally new to this, so apologies if I'm not explaining this correctly.
I want to post some data in json format to a rest service. I'm trying to get this work with JQuery in a simple .cshtml (razor) page.
My json string looks like this:
{
"ListRequest":{
"Values":[
{
"Name":"SC",
"Value":"PRO001"
},
{
"Name":"PC",
"Value":"Z0R14"
}
]
}
}
I need to pass 2 values from a form into this string and then post it but I'm not sure how do I declare this in javascript and then post it to my $.post function.
My HTML looks like this:
<form action="/" id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
I thought I'd just declare a var:
var jsonText = '{"ListRequest":{ "Values":[' +
'{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
'{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
Is that the correct way to handle this??
Then I've got my 'post' code to test:
var posting = $.post( url, term);
posting.done(function (data) {
var content = $(data).find("#content");
$("#result").empty().append(content);
});
But whenever I call this, it put these 2 values as part of a query string, instead of doing an actual post where this data is not visible in the url.
http://localhost/WebTest/WebDataService.svc/GetList?txtSC=brc001&txtPC=12345
Can someone tell me how to fix this??
Thanks.
UPDATE:
Here is the full code from my test page as it still not working for me. I just noticed that the submit event is not triggered. It seems to be putting the textbox and value automatically because they are part of the form, but my event is definitely not triggered as I've just commented all the code and put a alert('test'); and it didn't show up.
Any ideas?
Thanks.
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
// Attach a submit handler to the form
$("#getListForm").submit(function (event) {
event.preventDefault();
//var jsonText = '{"ListRequest":{ "Values":[' +
// '{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
// '{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonText, url = 'http://localhost/WebTest/DataService.svc';
$.post(url + '/GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
// Send the data using post
//var posting = $.post( url, term);
//posting.done(function (data) {
// var content = $(data).find("#content");
// $("#result").empty().append(content);
//});
});
</script>
#{
ViewBag.Title = "Json Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
<div id="result"></div>
Thanks.
UPDATE:
Latest code where I've updated the term to use the jsonObj and I've put my code in the $(document).ready block as suggested:
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Attach a submit handler to the form
$("#getDocumentListForm").submit(function (event) {
event.preventDefault();
alert('test1');
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PO",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonObj, url = 'http://localhost/WebTest/DataService.svc';
alert(term);
alert(url);
$.post(url + 'GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
//Tried posting using term but no luck. Same problem.
//$.post(url + 'GetList',
//function (data, status) {
// alert("Data: " + data + "\nStatus: " + status);
//});
// Send the data using post
//var posting = $.post(url, term);
//posting.done(function (data) {
// //var content = $(data).find("#content");
// //$("#result").empty().append(content);
// alert(data)
//});
alert('test2');
});
});
</script>
#{
ViewBag.Title = "Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getDocumentListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get Document List">
</form>
<div id="result"></div>
Finale Update on this question
MAKE SURE:
NOT TO USE IE11 WITH JQUERY, WELL AT LEAST JQUERY 2.1.1! DON'T KNOW HOW WELL IT WORKS WITH OTHER VERSIONS OF IE.
ALWAYS TEST WITH OTHER BROWSERS
MAKE SURE TO SET YOUR JQUERY SRC TO THE CORRECT HTTP OR HTTPS DEPENDING ON WHAT YOU USE.
That's it.
I suppose what's going on there is that you are trying to pass an undefined variable named term instead of jsonText, so the javascript code is throwing an uncaught exception and gets ignored, and you get a normal action from your form element.
You should pass the correct data. And also, knowing about JSON.stringify can probably save you a lot of time and headaches ;). You could build your object like so:
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
};
var jsonObj = JSON.stringify(obj);
Another pitfall I can think of in your code, is that you have bound your AJAX to a click event on your submit button, or to an onsubmit event, and you are not preventDefault()ing.
Edit
Given the code you posted, you have a couple of mistakes:
Did you wrap your code into a jQuery(document).ready() block?
You commented out jsonText but still assign it to the variable term, causing an uncaught exception.
Fix these two things and your POST request will be done correctly.
On the other hand, why on Earth are you using jQuery version 1.5?

Set form data without creating DOM inputs

I have an empty form tag, and a function which generates 4000 hidden inputs which contains the data to be send by the form.
Generating the 4000 hidden inputs is pretty fast (takes about 4ms). However, the browser freezes for about 1 second when i am appending the hidden inputs in the form tag.
I have also wrapped the hidden inputs in a <div/> tag, but doesn't helps too much.
Is there any way to set the form data programmatically, without using the input DOM elements?
Something like:
$form[0].setData([{ id: 1, value: "A" }, { id: 2, value: "B" }]);
$form.submit();
Here is the function which generates the hidden inputs
function saveUIPositions() {
var $form = $("#saveUIPositionsForm");
$form.empty();
console.time("ui");
var array = [];
array.push("<div>");
var items = dataTable.dataView.getItems();
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i];
var index = dataTable.dataView.getRowById(item.Id) + 1;
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Item_Id' value='");
array.push(item.Id);
array.push("' />");
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Index' value='");
array.push(index);
array.push("' />");
}
array.push("</div>");
console.timeEnd("ui");
// here it gets very costly (and not because of array.join())
$form.append(array.join(""));
$form.submit();
};
Maybe you can send this data using ajax ? If so you will not have to generate and append your 4K hidden inputs to the DOM.
If ajax is not an option, can you give us the code generating and appending your inputs ? Maybe it can be optmized.
I wrote a small jsFiddle (open your debug console to see time informations)
to illustrate the difference between a generate then append all solution:
for(var i=0; i<4000; i++)
inputs += '<input type="hidden" value="' + i + '"/>'
$('form').append(inputs);
and generate and append each:
for(var i=0; i<4000; i++)
$form.append('<input type="hidden" value="' + i + '"/>');
You don't even really need a form element when working in just Javascript, data can be sent to your server with an ajax request.
$.ajax({
url: "myScript.php", //The script on your server that deals with the data
data: {
dataA: "a",
dataB: "b",
dataC: "c" //Your form input name and value key pairs
},
success: function(data){
alert("Form Submitted, Server Responded:"+data); //The server response
},
error: function(data){
alert("Error contacting server:"+data); //Error handler
}
});
You don't even need to reload the page when the form is submitted. Unless you want to, then just add:
location.href="http://link.com";
to the success callback.
You don't need to add the inputs to the DOM, you could create an array of the data an post the form via ajax e.g.
inputNames = 'YourInputNameHere'; // Could be an array of names
generatedData = arrrayOfData //presumably generated elsewhere
for (i=0;i<400;i++) {
formData[inputName][i] = generatedData[i]
// if you are using an array of names you want to change the above line to
// formData[inputName[i]] = generatedData[i]
}
$('body').on('submit', '#myForm', function(e) {
e.preventDefault();
postUrl = 'url/to/send/data';
// get any other use inputs that might have been taken from user ignore
// this line if there are no inputs
formData[] = $(this).serialize();
$.ajax(
{
url: postUrl,
type: 'POST',
data: formData,
dataType: 'html',
success: function( data )
{
// redirect, post message whatever
}
}
)
});
Hope this helps and makes sense.

API POST call with large model, need some guidance

I have a fairly large form (50 fields) and I need to pass it into an API call.
Doing it in the javascript file would be pretty large to serialize all the data on the form into the proper model.
Is it possible to call the controller, and use the model from that to pass it through to the api url?
Basically I want to know an easy way to take my form data and turn it into serialized data based on my model.
thanks!
EDIT: Easy meaning that I don't have to take each form input and create my model with them
My code now is basically this below, but I would need to fill out a bunch of fields (I haven't tried it any other way)
$("#submit").click(function () {
var name = $("#Name").val();
var address = $("#Address").val();
var dob = $("#DOB").val();
$.ajax({
url: "http://localhost:49493/api/Values",
type: "Post",
data: JSON.stringify([name, address, dob]),
//instead of 3 fields, I would have 50
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function () { alert('error'); }
});
});
jQuery has a function that you can use $("#myForm").serialize()
http://api.jquery.com/serialize/
$("#submit").click(function () {
var myData = $("#myForm").serialize()
$.ajax({
url: "http://localhost:49493/api/Values",
type: "Post",
data: myData,
//instead of 3 fields, I would have 50
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function () { alert('error'); }
});
});
(Although a 50 form field sounds quite large. You might want to reconsider your design, but perhaps there is a valid use case)
A javascript MV* framework can be helpful here (I'm most familiar with angular). With angular, you can define a binding between your UI elements and the underlying javascript model representation (which can be sent to your Web API with the $http service).
Here is a language agnostic way to iterate over elements and build a model. It was done quick and dirty, and there is much room for improvement (i.e. using addEventListener, attachEvent, then onclick, etc.) -- but jquery handles much of this for you, so would suggest to stick with using that. This could easily be converted over to jQuery... The javascript iterates over input elements and adds them to a model object. This object can then be sent over AJAX if desired. The example just outputs it to a div placeholder.
http://jsfiddle.net/T9MyZ/
JavaScript:
document.getElementById("submitMe").onclick = function () {
var inputs = document.getElementsByTagName("input");
var model = {};
for (var i = 0, len = inputs.length; i < len; i++) {
var elem = inputs[i];
model[elem.name] = elem.value;
}
document.getElementById("jsonText").innerHTML = JSON.stringify(model);
};
HTML:
<input type="text" name="name"><br>
<input type="text" name="address"><br>
<input type="text" name="dob"><br>
<button id="submitMe">Submit</button>
<br>
<div id="jsonText"></div>

How to submit a dynamically created form using JQuery?

Submit is not working form me, please can anyone can solve this ?
$(function(){
$('#postImg').click(function() {
var form = $("<form/>", {
action: "checkout.php",
method: "POST"
});
form.on("submit");
$.each(['tprice', 'tevents'], function(i, v) {
$("<input/>", {
type: "hidden",
name: v,
value: $("#" + v).text()
}).appendTo(form);
});
form.submit();
return false;
});
});
What you are doing here is trying to make an HTTP POST request in a really roundabout way (creating a form just for the purpose, populating it, posting, and then discarding).
It would be much easier and less confusing to directly use jQuery.post instead.
For example:
var parameters = {
'tprice': $("#tprice").text(),
'tevents': $("#tevents").text()
};
$.post("checkout.php", parameters);
Why are you trying to post a form that's not being bound into the DOM ? Maybe
$.post("checkout.php", { paramName: "value", paramName2: "value2" } );
is what you need ?

Categories