I would like to send over some custom data to the Paypal Checkout using the 'custom' hidden form field. When not using SimpleCart.js, this is as easy as appending this to the html form:
<input type="hidden" name="custom" value="My Custom data">
Any idea how I can achieve the same thing with simplecart?
Looking through the source I can see where the form is created/submitted.
generateAndSendForm: function (opts)
{
var form = simpleCart.$create("form");
form.attr('style', 'display:none;');
form.attr('action', opts.action);
form.attr('method', opts.method);
simpleCart.each(opts.data, function (val, x, name)
{
form.append(
simpleCart.$create("input").attr("type","hidden").attr("name",name).val(val)
);
});
simpleCart.$("body").append(form);
form.el.submit();
form.remove();
}
So, I could just modify this code to make it work, but I'm sure there there must be a better way. Anyone have any ideas?
Adding anything extra in simple cart requires adding a simple class...
For example,
<input type="hidden" name="custom" value="My Custom data" class="item_customdataname">
Notice my class and nomenclature. "item_customdataname".
However, due to the nature of simplecart, I'd reccomend the following;
<span style="display: none;" class="item_customdataname">My Custom data</span>
Not to say using a hidden input wouldn't work...
E
old thread, but may be interesting for somebody else.
you are looking at the wrong method:
generateAndSendForm:
is used to generate a form that will (most likely) POST data to your backend
what you want to be looking at is:
simpleCart.extendCheckout({
PayPal: function (opts) {
[...]
and you may want to add:
if (opts.custom) {
data.custom = opts.custom;
}
somewhere after the equivalent for notifications:
if (opts.notify) {
data.notify_url = opts.notify;
}
I have not tested it personally but it should do exactly what you need
Related
I have a project in which I have to be able make a multiple input if needed. I'm really new to JavaScript and the insert method that I'm familiar with is only POST method which I parsed it from Form. My question is how do I do to use query in my script?
This is my code and the query is needed between Do...While at the bottom:
<div id="form" class="hidden">
Nama : <input type="text" name="nama"><br/>
Kuantitas : <input type="text" name="kuantitas"><br/>
Kategori : <select name="idKategori">
<?php
while ($rowKategori = mysqli_fetch_object($resultKategori)) {
echo "<option value='".$rowKategori->id."'>".$rowKategori->nama."</option>";
}
?>
</select>
<input type="hidden" name="hidden" value="bahan">
<input type="button" id="remove" value="Remove">
</div>
<form>
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
$(document).ready(function() {
var form_index = 0;
$("#add").click(function() {
form_index++;
$(this).parent().before($("#form").clone().attr("id", "form" + form_index));
$("#form" + form_index).css("display", "inline");
$("#form" + form_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + form_index);
$(this).attr("id", $(this).attr("id") + form_index);
});
$("#remove" + form_index).click(function() {
$(this).closest("div").remove();
});
});
$("#insert").click(function() {
var i = 0;
do {
i++;
} while (i != 5);
});
im really bad at english , so let me explain it as simple as i can.
i wanted to make a form field with submit button, like the usual.
the difference is i wanted to make a clone button so i could add
more form field with single submit button.
the code that i write is something that i learn from another page and im not familiar with it.
i dont know how to get vallue from the cloned page, and i dont know how to handle the value itself in the script as i really noob at javascript
what i wanted to do is how do you get value from all cloned form field while i click the submit button? the method i familiran with is POST method, but i thinking about writedown all my query on the javascript since the POST method could not do the looping for all the formfield, thats why i make the loop on the javascript
and im sorry with my english, im not really good at it
Ok here you go, here is a fiddle of it.
https://jsfiddle.net/2ngjqxge/3/
HTML/PHP
<div id="form_block_wrapper" class="hidden"> <!-- added an outside wrapper -->
<div class="form_block" class="hidden">
Nama : <input type="text" name="nama[]"><br/>
Kuantitas : <input type="text" name="kuantitas[]"><br/>
Kategori : <select name="idKategori[]">
<?php while ($rowKategori = mysqli_fetch_object($resultKategori)): ?>
<option value="<?php echo $rowKategori->id; ?>">
<?php echo $rowKategori->nama; ?>
</option>
<?php endWhile; ?>
</select>
<input type="hidden" name="hidden[]" value="bahan">
<input type="button" name="remove" value="Remove">
</div>
</div> <!-- close #form_block_wrapper -->
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
Please note, I changed a number of things. Most importantly all the names of the inputs that would get submitted i added [], so nama becomes nama[] etc. Now if you were to submit this as a form, on the server side you would get arrays instead of single elements. Single elements would get overwritten by the next dynamically created "form_block" so this is what we would need to process them. The data you would expect on submission of the form would be like this ( assuming we had 3 "form_blocks" ):
$_POST['nama'] = [
0 => 'nama from first form block',
1 => 'nama from second form block',
2 => 'nama from third form block',
];
$_POST['kuantitas'] = [
0 => 'kuantitas from first form block',
1 => 'kuantitas from second form block',
2 => 'kuantitas from third form block',
];
//etc...
Next, I removed any ID's as we know ids in HTML elements must be unique, so there is no point messing with them when we are creating and destroying dynamic content. We could append an index as you originally did, but the selectors are simple enough so we don't really need to do this. And it's worth it to keep things simple, why over complicate it.
I also used the "alternative" PHP syntax for the while block. while(..): with a colon instead of while(..){ with a bracket. It just looks better to me when mixed with HTML to have the <?php endWhile; ?> insteadd of <?php } ?>. It doesn't matter much here as this is small. But after adding buches of PHP, you would have all these hanging } brackets everywhere. It's easier to keep track of the close of code blocks when they are like endIf; endWhile; etc. I also kept the HTML as HTML and not a big string that has to be echoed out, again because it looks better to me that way. It also makes dealing with the quotes " easier then having to concatenate PHP '<tag attr="'.$php.'">'.
These things you can do either way, just I'm a bit particular and a perfectionist when it comes to formatting and readability. Sort of set in my ways.
Javascript (jQuery)
(function($){
$(document).ready(function() {
//get and cache Outer HTML for .form_block
var selectHtml = $('.form_block:eq(0)')[0].outerHTML;
$("#add").click(function() {
$('#form_block_wrapper').append(selectHtml);
});
//use .on for events on dynamic content ( event delegation )
$("#form_block_wrapper").on('click', 'input[name="remove"]', function() {
$(this).closest(".form_block").remove();
});
$("#insert").click(function() {
//I have no idea what you want to do here?
//Are you trying to insert something into the page
//or Are you trying to insert the data into the DB, ie submit it to the server.
//you can serialze all the data https://api.jquery.com/serialize/
//$('#form_block_wrapper').serialize();
//you can get the selected options and get their value
var d = [];
$('select[name="idKategori[]"]').each( function(){
d.push($(this).val());
});
alert(d.join(','));
});
}); //document.ready
})(jQuery); //assign jQuery to $ - for compatibility reasons.
The first thing to do here is not clone the select but instead take a snapshot of it's html. Stored in selectHtml. There is several reasons why this is better.
if user changes the value of these fields, when we clone we have to reset all those values.
if we remove all form blocks, there is nothing to clone and we are struck on a page without our form elements, tell we refresh.
based just on the length of my code -vs- your orignal code, it should be obvious which method is simpler to handle. Simple is easy to read and maintain, do more with less.
Another thing to note, is you were attaching the remove button's event to each button as they are created. While this is ok, we can do better by using event delegation $.on to handle this element.
I still have no Idea what you want done with Insert,
do you mean insert something into the page
do you mean submit the form and insert the data somewhere.
but hopefully this helps
I've been having a rather large amount of trouble doing what I imagine to be quite a simple task. I've looked through SO and various pieces of documentation though nothing I try seems to work, thus I thought to post here.
What I'm trying to do is to handle my html form (templated through JADE), and save all data from specific inputs (name="ListContent[]") into a singular array, with one value in the array per input. I'm needing to take this approach because the number of listContent inputs is dynamic, and I do not know how many will need to be handled.
My form looks something like this:
<form method='post'>
<input name='listTitle'></br>
<input name='listDescription'></br>
<input name='listContent[]'></br>
<input name='listContent[]'></br>
...
...
<input name='listContent[]'></br>
<input name='listContent[]'></br>
<input name='listContent[]'></br>
<button type='button' onClick='addInput('listContent');'>
<button type='submit'>
</form>
This is rendered as a form like this;
I'm able to retrieve the POSTed values of listName and listDescription as follows, though I'm at a loss for how to process the listContent and save all inputs into an array like:
"{'line 1', 'line 2', 'line 3'}"
var listName = form.data.listName; // Works
var description = form.data.listDescription; // Works
var contentRaw = form.data.listContent; // Just returns blank
Any advice would be appreciated. Thanks!
EDIT:
I'm using npm forms (https://www.npmjs.com/package/forms) to parse /process my form data. My defined form schema is as follows:
var simpleNewListForm = forms.create({
listToken: forms.fields.string({
required:true
}),
listName: forms.fields.string({
required: true
}),
listDescription: forms.fields.string({
required: true
}),
listContent: forms.fields.array(),
});
I see that you use listContents while creating the form, but listContent while accessing it after parsing it. When I tried generating the form with the same code you showed, the input name for listContents is listContents itself in the generated HTML form.
I need to implement an export to Excel function, but only for selected lines of the jtable, in a JSP environment.
My question is: what is the best way to do it? From the jtable, I pick the $('#SearchResultTable').jtable('selectedRows') and post it (using jquery $.post() ) to my servlet (that is generating the Excel file using poi). Everything good until I have to pick up the response from the servlet. Turns out I cannot save it to disk or prompt the browser to download it, since ajax is basically javascript, and thus have no access to the disk.
Is there a better way to do this? I want to be able to name and save the resulting file.
This is my call function which handles the post:
toolbar: {
items: [{
icon: 'art/excel_ico.gif',
text: 'Esporta in Excel',
display: 'download="Report.xls"',
click: function() {
return $.post("ExcelExport", {n: "Magazzino", t: $('#SelectedRowList')[0].innerHTML})
.done(function(data) {
alert("Data Loaded: " + data);
});
}
}]
},
Thank you for your help,
Fabio.
Solved.
I used a form instead of the "toolbar:" item in JTable. To whoever may be interested:
I removed the "toolbar" item from JTable init function.
Added a form to the page, like this:
<div id="formWrapper">
<form id="exportForm" action="ExcelExport" method="post">
<input type="hidden" value="" name="exportRows" id="exportRows">
<input type="hidden" value="Ordini" name="dataType" id="dataType">
<input type="submit" value="Esporta">
</form>
</div>
Styled the form using css to make it look like the button on the JTable toolbar.
In the JTable init, I added a selectionChange item, like this:
selectionChanged: function() {
var $selectedRows = $('#SearchResultTable').jtable('selectedRows');
$('input:hidden[name="exportRows"]').val("");
$selectedRows.each(function() {
var record = $(this).data('record');
$('input:hidden[name="exportRows"]').val($('input:hidden[name="exportRows"]').val()
+ record.id. ... );
});
}
So every time I change something on the JTable selection, the value of exportRows changes.
The form points to my servlet that can then send back the data as an Excel file, which I can name and save.
Hope it helps.
Fabio.
big problem here! I know the title is kinda fuzzy, but it's all day long I've got this problem and cannot figure out how to solve it.
I'll try to be the more specific in the less messy way.
Long story short, I have a Controller (LeadController) with a method (Search) for a search:
public ActionResult Search(string prov = null, string city = null)
{
//if no field is compiled, return an empty view
if (String.IsNullOrWhiteSpace(prov) && String.IsNullOrWhiteSpace(city))
return View();
var leads = from l in db.Leads
select l;
if (!String.IsNullOrWhiteSpace(prov))
{
leads = leads.Where(l => l.Prov == prov).OrderBy(l => l.RagioneSoc);
}
if (!String.IsNullOrWhiteSpace(city))
{
leads = leads.Where(l => l.Comune == city).OrderBy(l => l.RagioneSoc);
}
return View(leads);
}
Then I have the Search View (displaying the fields to fill for the search AND the result after the post action) with 2 submit forms: the first one to execute the search
#using (Html.BeginForm()){
Sigla Provincia: #Html.TextBox("prov", null, new { #style = "width: 50px;"})
Città: #Html.TextBox("city", null, new { #style = "width: 150px;" })
<input type="submit" value="Ricerca" data-icon="search" data-role="button" data-mini="true" data-inline="true" />}
and the 2nd one to generate a document from the leads result of the search action
<input type="submit" title="create doc" value="Create document" onclick="javascript:postData()" id="doc" />
This last submit should call a javascript function to encode the model:
<script type="text/javascript">
function postData() {
var urlact = '#Url.Action("createDoc")';
var model = '#Html.Raw(Json.Encode(Model))';
$.ajax({
...
...
});
}
</script>
Now, the problem is: when I call the first submit, the one which should execute the research, it performs the research but it also keeps going on, calling the postData() javascript function (even if I never "tell" him to do that). And the site stop working in var model = #Html.Raw(Json.Encode(Model))';, with an InvalidOperationException.
If someone understood my question, is there a way to avoid this behaviour and to force the 1st submit only to pass the controller the parameters to execute the search action?
Hope someone can help me,
thank you in advance for your consideration!
SOLVED
Well, the problem is gone. Apparently, I didn't know so well the View & Javascript behaviour. Long story shirt, it seems the View, loading itself, enters the js function in order to kind of cache the Model encoding, but it doesn't fully runs the function! And I had a problem within the interested Model.
I don't know if I explained myself, but the warning is: be careful for your Model consistency before doing anything else.
Thanks to anyone who helped me, before I realized I get it totally wrong!
Here is how you should handle multiple submit buttons
Below is a form with two submit buttons. Note that both these submit buttons have the same name i.e “submitButton”
#Html.BeginForm("MyAction", "MyController"); %>
<input type="submit" name="submitButton" value="Button1" />
<input type="submit" name="submitButton" value="Button2" />
}
Now over to the Controller, the Action takes in an input parameter called string stringButton and the rest is pretty self-explanatory.
public ActionResult MyAction(string submitButton) {
switch(submitButton) {
case "Button1":
// do something here
case "Button2":
// do some other thing here
default:
// add some other behaviour here
}
...
}
Hope this helps you !
UPDATE :
from your comments,
Hi, I do know this workaround, my issue is the 2nd submit doesn't have to pass through the Controller: it has to call the javascript function in the View. The 1st post to a Controller in the right way, but THEN it runs the javascript function, too.
Ok, instead of having two submit buttons, you can have one submit button and other as a normal button.
Eg: -
#Html.BeginForm("MyAction", "MyController"); %>
<input type="submit" name="submitButton" value="Button1" />
<input type="button" id="otherButton" value="Button2" />
}
and then using some simple jquery, you can make a call to the javascript funcion postData().
<script type="text/javascript">
$("#otherButton").bind("click", function () {
console.log("do your stuff here");
postData();
});
</script>
Try changing your second submit from <input type="submit" to <input type="button"
I need to constantly search files such as smss.exe at http://www.winpatrol.com/db/pluscloud/.
Is there a way I can make a customized searchbar on my custom homepage that will do this for me?
So if I type smss into the search bar it will take me to http://www.winpatrol.com/db/pluscloud/smss.html
I tried in pure HTML with GET requests and can't find a way to do it. I was thinking maybe there is a Javascript way or something.
Something like this is pure Javascript and will work, but if the user enters a non-existent page on that site, it will just lead to their not found page.
You could use server side PHP or something similar to achieve this in a better way.
Here is the JS solution with little error checking:
<form onsubmit="return redirect()">
<input id="search_form_input" type="text" name="query" />
<input type="submit" value="Search" />
</form>
<script type="text/javascript">
function redirect()
{
var query = document.getElementById('search_form_input').value;
if (query != '') {
window.location = 'http://www.winpatrol.com/db/pluscloud/' + query + '.html';
}
return false;
}
</script>
Google custom search is what you're probably looking for.