Pass checkbox value to js upon clicking 'submit' - javascript

I have a bunch of checkboxes queried from a database via a js function at id='checkboxes'. I'm trying to pass the checked value to a js function but the console returns an undefined endpoint (i.e. ..../undefined HTTP/1.1 200 --)
HTML:
<form action="javascript:getQuestionData(this.value)" method="post">
<div id="checkboxes">
</div>
<input type='submit' value="Submit">
</input>
</form>
Javascript:
function getQuestionData(sampleValue) {
document.getElementById("question").innerHTML = ""
document.getElementById("solve").innerHTML = ""
var endPointQuestionData = '/api/v1/questions/' + sampleValue
Plotly.d3.json(endPointQuestionData, function(error, response) {
if (error) return console.warn(error);
appendInnerHTML(response)
});
};
Why is the checked value not being passed to the getQuestionData function?

Add following code in the submit button:
onclick='return getQuestionData();
function getQuestionData() {
var question = document.getElementsByName("question")[0].checked;
alert(question);
var endPointQuestionData = '/api/v1/questions/' + question
Plotly.d3.json(endPointQuestionData, function(error, response) {
if (error) return console.warn(error);
appendInnerHTML(response)
});
};
<form method="post">
<input type="checkbox" name="question" value = "Question"> Question<br>
<input type="checkbox" name="question" value = "Solve"> Solve<br>
<input type='submit' value="Submit" onclick = "getQuestionData()">
</form>

Related

Pass data to post.php in the background form fields

I have this script that works well for sending a message from a form via post. But I would like to add more information from the form to be sent via the script but can't get it working?! Do I have to have have one $.post("post.php" .. for every input? Thanks a million.
--- THIS ONE IS SENT FINE TO post.php --
<input name="usermsg" type="text" id="usermsg" />
--- WOULD LIKE TO ADD THESE TO THE SCRIPT --
<input type="hidden" name="request" value="1" />
<input type="hidden" name="sentby" value="2" />
<input type="hidden" name="sentto" value="3" />
$(document).ready(function () {
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
$.post("post.php", { text: clientmsg });
$("#usermsg").val("");
return false;
});
});
$(document).ready(function () {
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
var request = $("#request").val();
var sentby = $("#sentby").val();
var sentto = $("#sentto").val();
$.post("post.php",
{
text: clientmsg,
request: request,
sentby: sentby,
sentto: sentto,
},
function(result){
// you can do anything you want with result
});
$("#usermsg").val("");
return false;
});
});

2CheckOut - TwoCheckoutException: Bad request - parameter error

So basically i am trying to implement 2checkout in my website and i have done everything from documentation but i get this error: TwoCheckoutException: Bad request - parameter error. I tried checking and playing with private/public keys and id but when i change them it says "authoization error" so i am sure they are okay. I read about addresses and everything and i have changed them but still not working.
Here is my full code:
#{
ViewData["Title"] = "Test";
}
<script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
<h2>Test</h2>
<form id="myCCForm" action="/Home/SubmitCard" method="post">
<input name="token" type="hidden" value="" />
<div>
<label>
<span>Card Number</span>
<input id="ccNo" type="text" value="" autocomplete="off" required />
</label>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
<input id="expMonth" type="text" size="2" required />
</label>
<span> / </span>
<input id="expYear" type="text" size="4" required />
</div>
<div>
<label>
<span>CVC</span>
<input id="cvv" type="text" value="" autocomplete="off" required />
</label>
</div>
<input type="submit" value="Submit Payment" />
</form>
<script type="text/javascript">
// Called when token created successfully.
var successCallback = function (data) {
var myForm = document.getElementById('myCCForm');
// Set the token as the value for the token input
myForm.token.value = data.response.token.token;
// IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
myForm.submit();
};
// Called when token creation fails.
var errorCallback = function (data) {
if (data.errorCode === 200) {
alert("Error 200");
// This error code indicates that the ajax call failed. We recommend that you retry the token request.
} else {
alert(data.errorMsg);
}
};
var tokenRequest = function () {
// Setup token request arguments
var args = {
sellerId: "901417674",
publishableKey: "309FC596-8380-4B6F-B269-3E157A5A5D0B",
ccNo: $("#ccNo").val(),
cvv: $("#cvv").val(),
expMonth: $("#expMonth").val(),
expYear: $("#expYear").val()
};
// Make the token request
TCO.requestToken(successCallback, errorCallback, args);
};
$(function () {
// Pull in the public encryption key for our environment
TCO.loadPubKey('sandbox');
$("#myCCForm").submit(function (e) {
// Call our token request function
tokenRequest();
// Prevent form from submitting
return false;
});
});
</script>
and here is server side code:
public IActionResult SubmitCard()
{
TwoCheckout.TwoCheckoutConfig.SellerID = "901417674";
TwoCheckout.TwoCheckoutConfig.PrivateKey = "4E704021-B233-435F-A904-47B2620B9E66";
TwoCheckout.TwoCheckoutConfig.Sandbox = true;
try
{
TwoCheckout.AuthBillingAddress Billing = new TwoCheckout.AuthBillingAddress();
Billing.addrLine1 = "123 Main Street";
Billing.city = "Townsville";
Billing.zipCode = "43206";
Billing.state = "Ohio ";
Billing.country = "USA";
Billing.name = "Joe Flagster";
Billing.email = "Ex#a.com";
Billing.phoneNumber = "065";
TwoCheckout.ChargeAuthorizeServiceOptions Customer = new TwoCheckout.ChargeAuthorizeServiceOptions();
Customer.total = 1;
Customer.currency = "USD";
Customer.merchantOrderId = "12";
Customer.billingAddr = Billing;
Customer.token = Request.Form["token"];
TwoCheckout.ChargeService Charge = new TwoCheckout.ChargeService();
var result = Charge.Authorize(Customer);
return View("Success", result);
}
catch(TwoCheckout.TwoCheckoutException ex)
{
return View("Error", ex.ToString());
}
}
and here is all info from my sandbox:
You may need to update your site settings for sandbox from Site Management -> Site Settings and Turn to On for Demo Settings and check again
May it helps you

get checkbox values from form and add to JSON string using JavaScript

attempting to pull form values and put them into localStorage via JSON string. This code works for everything but checkbox values. How do i also get checkbox values? Please and thanks!
<form id="myForm">
<input type="submit" name="submit" value="submitOrder">
</form>
const userOrder = {};
function getValues(e) {
// turn form elements object into an array
var elements = Array.prototype.slice.call(e.target.elements);
// go over the array storing input name & value pairs
elements.forEach((el) => {
if(el.type !== "submit" && el.type !=="button") {
userOrder[el.name] = el.value;
}
});
// finally save to localStorage
localStorage.setItem('userOrder', JSON.stringify(userOrder));
}
document.getElementById("myForm").addEventListener("submit", getValues);
console.log(localStorage.getItem('userOrder'));
use the .checked attribute of a checkbox to tell if it is checked or not
const userOrder = {};
function getValues(e) {
e.preventDefault();
// turn form elements object into an array
//you can also use Array.from(e.target.elements)
var elements = Array.prototype.slice.call(e.target.elements);
console.log(elements);
// go over the array storing input name & value pairs
elements.forEach((el) => {
if(el.type == "checkbox") {
userOrder[el.name] = el.checked;
}
});
console.log(userOrder);
// finally save to localStorage
//localStorage.setItem('userOrder', JSON.stringify(userOrder));
}
document.getElementById("myForm").addEventListener("submit", getValues);
//console.log(localStorage.getItem('userOrder'));
<form id="myForm">
<input type="checkbox" name="checkbox-0">
<input type="checkbox" name="checkbox-1">
<input type="checkbox" name="checkbox-2">
<input type="submit" name="submit" value="submitOrder">
</form>
You can use JQuery serialize() function.
Then, you can do something like this:
function onSubmit( form ){
var data = JSON.stringify( $(form).serializeArray() ); // <-----------
console.log( data );
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form onsubmit='return onSubmit(this)'>
<input name='user' placeholder='user'><br>
<input name='password' type='password' placeholder='password'><br>
<input type='checkbox' name='remember-me'>
<br />
<button type='submit'>Try</button>
</form>

Passing form's input to Parse.com

I am playing around a bit with Parse.com and I am trying to send HTML form's content to Parse.com
I am kind of a Javascript noob so for some reason I cannot find a way to pass a variable I got from the form's input to Parse.com for processing.
Here's my code:
<div class="main">
<form action="">
<label>Insert your ingridient :</label>
<input type="text" id="text" name="name" value="" />
<input type="button" id="text_value" value="Get Value"/>
<script type="text/javascript">
$(document).ready(function() {
$('#text_value').click(function() {
var text_value = $("#text").val();{
alert(text_value);
}
});
});
Parse.initialize("myAPIKey", "myAPIKey");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
name: text_value,
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
}
});
</script>
You should wrap the code that does the saving inside a function, then call it when the user clicks the button. You have a few errors with your {} brackets as well. Indenting your code when writing it will help you avoid that.
<div class="main">
<form action="">
<label>Insert your ingridient :</label>
<input type="text" id="text" name="name" value="" />
<input type="button" id="text_value" value="Get Value"/>
<script type="text/javascript">
$(document).ready(function() {
$('#text_value').click(function() {
var text_value = $("#text").val();
save(text_value);
});
Parse.initialize("myAPIKey", "myAPIKey");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
function save(value) {
gameScore.save({name: text_value}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
}
});
};
};
</script>

How can send array as an data using ajax

Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post
Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it.
Thanks
http://jsfiddle.net/6jzwR/1/
<form id="form1" name="formone" class="myclass">
<input type="text" id="txt11" name="txt11" value="name1" />
<input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
<input type="text" id="txt21" name="txt21" value="name3" />
<input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />
(function ($) {
$(document).ready(function () {
alert("serialize data :" + $('.myclass').length);
var mydata = null;
$('#button').on('click', function (e) {
$('.myclass').each(function () {
alert("serialize data :" + $(this).serialize());
if ((mydata === null) || (mydata === undefined)) {
mydata = $(this).serializeArray();
alert("My data is null");
} else {
mydata = $.merge(mydata, $(this).serializeArray());
alert("My data final data after merger " + test);
}
});
});
});
}(jQuery));
Try this:
var array = $('input[type="text"]').map(function() {
return $(this).val();
}).get();
alert(JSON.stringify(array));
Demo.
You can put all the forms' data in an array and join them with &
var formdata = []
$('.myclass').each(function(){
formdata.push($(this).serialize());
});
var data = formdata.join('&');
http://jsfiddle.net/6jzwR/3/

Categories