Pass data to post.php in the background form fields - javascript

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;
});
});

Related

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

Adding multiple forms and inputs with onclick events using javascript

I am currently working on an website project that my friends and I would like to publish in the future. I´m currently building the html and css side of the page and need to implement dynamic events (if that's how its called) in the page for customer input.
I have a very little understanding when it comes to javascript/jquery (I am able to get a general idea of what is happening, yet my syntax comprehension is poop) and have only a basic knowledge of html and css. Now, I am aware that my inquiry is extensive and I would really appreciate any help, or pointers in the right direction!
So far the different blocks of code that I have found and tried by googling have worked for me, but only in executing individual functions (e.g.: the toggle function works but the create.element function doesn't).
This is my current html code that I am trying to modify with Javascript:
<div class="bttiendas">
<button class="btndag">Agregar</button>
<button class="btndgu">Guardar</button>
</div>
<div class="rdatos">
<form class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>
</div>
What I am trying to accomplish with Javascript is as follows:
-To be able to create with javascript both .thf and .trf forms dynamically along with every other input/button that is inside each form with clicking the .btndag button (this is an onclick event followed by create.element if I'm not mistaken).
-For the .morehf <input button> have a hide/show toggle function for .trf and anything else inside that form.
-Toggle disabled in the .crf input text boxes with the .edithf <input button>.
-To be able to erase/remove both .thf and .trf forms (their input textboxes AND the buttons .morehf .edithf .erasehf) with the .erasehf <input button>.
-And to be able to save/submit (I am not sure which is the correct term here) any added and completely filled out forms fields (for when we want to send the changes to our database).
Again I would greatly appreciate any help you could give me, and thank you in advance for your time.
You can import jquery into your solution.
For step 1: you do not make sense. Do you mean you want to load data into your form from somewhere to edit data or something? how is this dynamic? It looks like static forms on a page.
For step 2:
<input class="morehf" onclick="toggleTrf()" type="button" value="+/-" />
<script>
function toggleTrf() {
$(".trf").toggle()
}
</script>
step 3:
<input class="edithf" onclick="disableInputs()" type="button" value="Edit" />
<script>
function disableInputs() {
if($(".crf").is(":disabled");){
//jquery 1.6+
$(".crf").prop('disabled', false);
//jquery 1.5 -
$(".crf").removeAttr('disabled');
}
else {
//jquery 1.6+
$(".crf").prop('disabled', true);
//jquery 1.5 -
$(".crf").attr('disabled','disabled');
}
}
</script>
step 4: it is not clear what you mean by erase the form but you can clear the text in the inputs
<input class="erasehf" thpe="reset" onclick="clearInputs()" value="Erase" />
<script>
function clearInputs() {
$("input").val("")
}
</script>
step 5:
<form action="some/path">
<input name="someName" type="text" text="random field" value="1" />
<button type="submit">submit</button>
</form>
That submit button will submit the form to whatever path you specify in your form action. As for saving to the database etc it is impossible to guess what technology you will use to do that.sorry about code formattin im typing on a phone.
I believe I have included everything the OP wanted. The non-jQuery approach (ES6). JSFiddle
First lets add a few helper variables:
let formSets = 0;
let createForm = function(id) {
return `<form data-id='${id}' class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form data-id='${id}' class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>`;
};
Add the onclick event for the "add" function. We have to reassign the click events to the dynamically added elements or we could have done event delegation like I did for the remove button:
document.getElementsByClassName('btndag')[0].onclick = () => {
document.getElementById('a').innerHTML += createForm(++formSets);
for (let ii = 0; ii < formSets; ii++) {
document.getElementsByClassName("morehf")[ii].onclick = () => {
document.getElementsByClassName("trf")[ii].classList.toggle('hide');
}
document.getElementsByClassName("edithf")[ii].onclick = () => {
let form = document.getElementsByClassName("trf")[ii].children;
for (let i = 0; i < form.length; i++) {
let input = form[i];
if (input.disabled == true) {
input.disabled = false;
} else {
input.disabled = true;
}
}
}
}
};
Add the remove button a little differently using event delegation which allows us to target another element based on the parents target:
document.getElementById('a').onclick = function(e) {
let t = e.target;
if (t.className == 'erasehf') {
let me = t.parentNode;
let sib = me.nextElementSibling;
me.parentNode.removeChild(me);
sib.parentNode.removeChild(sib);
}
}
Finally, submit the data. This part is a little more vague simply because I am not exactly sure how you want the data formatted. But here is how you would submit the form using AJAX:
document.getElementsByClassName('btndgu')[0].onclick = function() {
Request("/linkto/save.asp").post({
//datahere
}).then(function () {
//on success
}, function () {
//on failure
});
}
Note that this uses a helper AJAX function that I made:
let Request = function(url, opt) {
// start loader
var AJAX = function(type, url, data, success, failure, cache) {
var InitRequest = new Promise(function(accept, reject) {
var request = new XMLHttpRequest(); // initiate new XMLHttpRequest
var done = false;
var compile = function(data) { //turn the data object into a usable source for the send function
var send = [];
for (var item in data) { // compile all data in "item=data" strings
send.push(item + "=" + encodeURIComponent(data[item]));
}
send = send.join("&"); // combine data to form "item1=data1&item2=dat2&item3=data3"
return send;
};
// if we choose not send any data, then the data variable will take the place of the success variable
// because of this, we have to also shift the failure function
if (typeof data === "function") {
success = data || accept;
failure = success || reject;
data = "";
} else {
success = success || accept;
failure = failure || reject;
data = compile(data);
}
if (type.toUpperCase() == 'POST') {
request.open(type.toUpperCase(), url, true);
// this header allows POST requests to work
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
} else if (type.toUpperCase() == 'GET') {
// for GET requests, we need to put all data in the url
// we would end up with test.php?item1=data1&item2=dat2&item3=data3
request.open(type.toUpperCase(), url + "?" + data, true);
} else {
console.error('Incorrect request type submitted: "' + type + '" is not supported.');
return false;
}
// in order for laravel to properly send ajax requests
request.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onreadystatechange = function() {
if (!done) {
if (request.readyState === 4) { // when the readyState == 4, we have completed the request
if (request.status === 200 || request.status === 0 /*for ff bug*/ ) {
success(request.responseText, request);
} else { //if failed
try {
request.responseJSON = JSON.parse(request.responseText);
} catch (e) {
return false;
}
failure(request);
}
// hide the loader because the request has finished
done = true;
}
}
};
// send off the request
request.send(data);
});
return InitRequest;
};
// The "opt" variable also goes into place as the
// Cache reset
if (opt && typeof opt !== "string" && typeof opt !== "boolean") {
var DEFAULTS = {
type: "GET",
data: {},
cache: false,
success: function() {},
failure: function() {}
};
var o = $.extend(DEFAULTS, opt);
return AJAX(o.type, url, o.data, o.success, o.failure, o.cache);
} else {
return {
post: function(data, success, failure, cache) {
return AJAX("POST", url, data, success, failure, cache);
},
get: function(data, success, failure, cache) {
return AJAX("GET", url, data, success, failure, cache);
}
}
}
}
A little more information about sending data via AJAX
Data in your case should correspond with the ids:
{
0: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
},
1: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
}
}

How to distinguish which button was clicked in the html form and based on that pass different values with ajax?

I have the following html form:
<form class="center" id="myform">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
<div class="terms">
<input type="checkbox" class="required" value="None" id="terms" name="terms">I accept terms</input>
</div>
</p>
<input type="submit" id="sendfeedback" value="now" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" id="postmelater" value="send" disabled/>
</form>
And as you can see above, I have a form with two buttons. The logic behind it works like that, that when I want to put text to database with current timestamp - I choose button sendfeedback. However, there's also a possibility of adding the feedback with chosen timestamp, that is happening when user choses the date from datetimepicker and hits postmelater. Now, the ajax code for that looks like this:
$(document).ready(function () {
$('#myform').validate({// initialize the plugin
errorElement: 'div',
rules: {
email: {
required: true,
email: true
},
slogan: {
required: true,
minlength: 2
},
terms: {
required: true,
maxlength: 2
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
});
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
});
There's a validation process attached to the fields and so far - only support for the first button. How can I add a support for 2nd button, and in case when user clicks it - also pass the datetime attribute to ajax? Can I distinguish them somehow in Ajax? Thanks!
Here depends on functionality of validation plugin, when it reacts, but likely you can try to add onclick to buttons which sets some hidden variable, indicating which button was pushed. Like this:
<input type="submit" id="sendfeedback" onclick="this.form.clickedbtn.value=1" value="now" disabled/>
<input type="submit" id="postmelater" value="send" onclick="this.form.clickedbtn.value=2" disabled/>
and also add hidden input to the form like this
<input type="hidden" id="clickedbtn" name="clickedbtn">
Than in the handler add
var clickedbtn = $("#textarea").val();
...
clickedbtn: clickedbtn,
so form will look like this:
<form class="center" id="myform">
<input type="hidden" id="clickedbtn" name="clickedbtn">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
I accept terms
</p>
<input type="submit" id="sendfeedback" value="now" onclick="this.form.clickedbtn.value=1" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" onclick="this.form.clickedbtn.value=2" id="postmelater" value="send" disabled/>
</form>
And handler will look like this:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
var clickedbtn = $("#textarea").val();
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
clickedbtn: clickedbtn,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
After that in php script you can check
if ($_POST["clickedbtn"]==1) {
send now code
} else {
other code
}
Change
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
to
$('#myform').find('input, textarea').on('change', function () {
var sendfeedbackbtn = $('#sendfeedback');
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
if ($('#myform').valid()) {
sendfeedbackbtn.removeAttr('disabled');
datepicker.removeAttr('readonly');
if (isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
}
} else {
datepicker.attr('readonly', 'readonly');
sendfeedbackbtn.attr('disabled', 'disabled');
postmelaterbtn.attr('disabled', 'disabled');
}
});
So it enables the sendfeedback and the timestamp input area. And if not valid, all button and timestamp area will be disabled.
Then add
$('#myform').find('#datetimepicker').on('change', function () {
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
// Need to implement isTimeValid method.
if ($('#myform').valid() && isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
} else {
postmelaterbtn.attr('disabled', 'disabled');
}
});
So when the timestamp area is changed, check if its valid (need implement isTimeValid), and decide whether to make postmelater able to clicked or not.
And your submit handler should be:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
// Decide to send a timestamp data or not.
var timestamp = $('#datetimepicker').attr('readonly') ? null : $('#datetimepicker').val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php',
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
// So this value will be null or whatever your input
timestamp: timestamp
},
success: function(response)
{
alert(response);
}
});
}
And you can decide PHP side's behavior on whether the given timestamp is a null value or not.
As you give all these inputs an id, I directly use its id selector to get them, but you can still change to other selector at wish.
You could use js/php to set the default value of your date field to be current date. That way you would only need one submit button:
<input type="date" value="<?php echo date("Y-m-d")?>">
or
<input type="date" id="datefield">
<script>
document.getElementById("datefield").value = new Date().getFullYear()+"-"+("0"+(new Date().getMonth()+1)).slice(-2)+"-"+("0" + new Date().getDate()).slice(-2);
</script>
But if you absolutely want to have two buttons, you could do:
<input type="button" onClick="firstButton()">
<input type="button" onClick="secondButton()">
and
function firstButton(){
//do what you need to
document.getElementsByTagName("form")[0].submit();
}
...and same for button two.

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