I am trying to create a form that generates an html template. I have the template in a hidden div on the page and am using jQuery to create a new window with the template html, but I can't figure out how to load the contents of the form fields into the template. I know I should probably be using AJAX, but I don't know where to start.
Suppose you have this template:
<div class="template">
<p class="blah"></p>
<p class="foo"></p>
</div>
and this form:
<form>
<input name="blah" class="blah"/>
<input name="foo" class="foo"/>
</form>
so, for this example we will assume a mapping of form elements to template elements via a common class for each corresponding element:
$("form input").each(function() {
$(".template").find("." + $(this).attr("class")).html(this.value);
});
Try it here: http://jsfiddle.net/dx2E6/
One trick I've been using is using the <script type="text/html"> tag. The browser doesn't render the code, so what I do is something like this:
<script type="text/html" id="template">
<div>
<div class="some_field">{name}</div>
<h4>{heading}</h4>
<p>{text}</p>
</div>
</script>
Your form is something like this:
<form>
<input type="text" name="name" />
<input type="text" name="heading" />
<input type="text" name="text" />
</form>
Then your javascript code would be something like:
$(document).ready(function(){
var tpl = $('#template').html();
$('form input').each(function(){
tpl.replace('{'+$(this).attr('name')+'}',$(this).val());
});
$('div.some_destination').html(tpl);
});
Hope it helps. Tell me if you have more questions regarding this method.
Related
I'm using prestashop 1.7.2.1 to build a module with a front controller.
what I'm trying to do is to add the smarty{url} tag to the action property of the form. the problem is that once I submit the form all the get parameters that are provided in action property of the from are erased. this is a normal behaviour in html.
this is my code:
<form id="car-type-form" action="{url entity='module' name='tuxinmodcartype' controller='cartypeproducts'}" method="get">
<div id="company-name-input-form-group" class="form-group row">
<label for="company-name-input" class="col-sm-2 col-form-label">Company</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="company-name-input" name="company_name" placeholder="Company" aria-label="Company" required="required"/>
</div>
</div>
...
</form>
In general I can paste that smarty {url} tag to a variable. on submit to add the values of the form fields dynamically to the variable I created and use it to redirect instead of allowing the form to submit.
I just don't know if this is the best solution.
maybe there is something that I missed.
any ideas?
thank you
for now what I did is to add hidden input elements to the form based on the created url string.
I have this on the first line of my template file:
<script type="text/javascript">
var carTypeProductsUrl='{url entity='module' name='tuxinmodcartype' controller='cartypeproducts'}';
</script>
and on the submit function I added the following code:
...
if (isError) {
event.preventDefault();
} else {
$('.hidden-form-params').remove();
var params = carTypeProductsUrl.substr(carTypeProductsUrl.indexOf('?')+1).split('&');
params.forEach((paramStr)=>{
var paramsArray = paramStr.split('=');
const paramKey = paramsArray[0];
const paramvalue = paramsArray[1];
$('#car-type-form').append(`<input type="hidden" name="${paramKey}" value="${paramvalue}" class="hidden-form-params" />`);
});
}
this method feels a bit.. hacky?! :) I just want to make sure this is the way to go
I am fine getting the value of a form controls such as radio and select for example but with all of the additional non form based controls available for Bootstrap i haven't really seen many PHP examples how to use these.
So my main question is with pure PHP how would you retrieve the current selected item from a div and li based dropdown?
http://www.bootply.com/b4NKREUPkN
or a custom color picker plugin?
http://bootstrapformhelpers.com/colorpicker/#jquery-plugins
If you are submitting a form and handling the request using PHP, you will not be able to access the DOM in PHP (client vs server). If you can pull out the bits that you need using javascript, you can set the values on hidden form elements and submit.
<?php
// print out the value when the post is submitted
if (isset($_POST["extraInput"])) {
echo "hidden input is: " + $_POST["extraInput"];
}
?>
<html>
<head>
<script type="text/javascript">
function doSubmit () {
var extraValue = document.getElementById("extra").innerHTML;
var form = document.forms["myForm"];
form.elements["extraInput"].value = extraValue;
form.submit();
}
</script>
</head>
<div id="extra">Hello world</div>
<body>
<form id="myForm" action="" method="post">
<input type="hidden" name="extraInput" />
<input type="text" name="textInput" />
<button onclick="javascript:doSubmit()">Submit</button>
</form>
</body>
</html>
I have two php pages. In first php page I have two divisions, where in one division I have hyperlinked text which on click showing result in other division of same page, with the help of ajax. The code for same is below:
<body>
<div id="container">
<div id="content"> Sidebar <p> </p>
<div class="form">
<pre>
<a href=sample_disease_form.php><b>Disease</b></a><p>
<a href=sample_drug_form.php><b>Drug</b></a><p>
</pre>
</form>
</div>
</div>
<div id="sidebar">
</div>
</body>
Ajax code for this is:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('a').each(function(){
$(this).on("click",function(e) {
console.log(e);
e.preventDefault();
$('#sidebar').load($(this).attr('href'));
});
});
});
</script>
Now, I have other PHP file, one which is opening after clicking hyperlink on same page but in other division, contains form. After being clicked submit button of this form I want the result gets displayed in same division but it will come from different PHP file. How can I achieve this?
The second file's code is below:
<pre><h2> Drug </h2></pre>
<pre><p><span class="error"> * required field </span></p></pre>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<pre> Name: <input type="text" name="drug" value="<?php echo $drug;?>"><span class="error">* <?php echo $nameErr;?></span>
<input type="checkbox" name="drug[]" value="disease">Disease</br>
<input type="checkbox" name="drug[]" value="target">chemical
<input type="submit" name="submit" value="Submit"></pre>
</form>
Since I am very new to these kinds of programming stuff, expecting help.
you need to submit the page through ajax and load the result in the same div
I'm working on a simple webpage for a company and the company wants to be able to edit the content themselves from time to time. However they have no programing knowledge and therefore I want to use an embedded HTML editor, I have chosen jQuery TE.
The problem is that I only know how to use this as a form, e.g.:
<form id = "wyForm" method="post" action="test.php">
<textarea class="editor"name = "testText">Hi</textarea>
<input type="submit" class="wymupdate" />
</form>
Then I would convert the textarea to an editor with jQuery:
<script> $('.editor').jqte() </script>
This makes it possible to send the result to a .php page that updates the database. However many times I don't want to use a textfield or a form, but just a simple object that I convert to an editor in the same way. But how do I save the change in that case?
Catch the form submit event and copy the content to a hidden field.
<form id = "wyForm" method="post" action="test.php">
<div class="editor" name="testText">Hi</div>
<input type="submit" class="wymupdate" />
<input type="hidden" id="editorHiddenField" />
</form>
...
$('#wyForm').submit(function() {
$('#editorHiddenField').val($('.editor').html());
});
You may need to use an API to get the content instead (I'm not familiar with the plugin), but the concept is sound.
Edit - If you don't want to use a form at all:
<div class="editor></div>
<button id="SaveButton">Save</button>
...
$(document).ready(function() {
$('#SaveButton').click(function(e) {
e.preventDefault();
$.post('savepage.php', { data: $('.editor').html() }).done(function() { alert('saved!'); });
});
});
Have a form that is not being read by serialize() function.
<script type="text/javascript">
function submitTrans1(){
var formData = $('form1').serialize();
var options = {
method:'post',
postBody:'formData',
onCreate: function(){alert(formData)},
onSuccess: function(transport){alert("onSuccess alert \n" + transport.responseText);},
onComplete: function(){alert('complete');},
onFailure: function(){alert('Something went wrong...')}
}
new Ajax.Request('/clients/addTrans/<?=$clientID123?>/',options);
}
</script>
<?php
$datestring = "%Y-%m-%d";
$time = time();
$clid1 = $this->uri->segment(3);
?>
<form name="form1" id="form1">
<div id="addTransDiv" style="display:none">
<div class="">
<label for="transDesc" id="transDesc" value="sadf" class="preField">Description</label>
<textarea cols="40" rows="3" id="transDesc" value="" name="transDesc" class=""></textarea>
</div>
<div class="">
<label for="date" class="preField">Date</label>
<input type="date" id="transDate" name="date" value="<?=mdate($datestring, $time);?>" size="40" class=""/><br/>
</div>
<div class="">
<label for="userfile" class="preField">File</label>
<input type="file" name="transFile" id="userfile" size="20" /><br>
</div>
<input type="button" id="submitTrans" name="submitTrans" value="Submit" onclick="submitTrans1()">
</div>
</form>
Uh, I have an alert in the onSuccess parameter of the Ajax.Request that would ideally alert the variable assigned to the serialized form. However, when it alerts, it alerts nothing. I also have the processing url printing out the $_POST data just in case, but that as well returns an empty array in the responseText, so indeedidly nothing is being posted to the form.
Thx.
Edit1
it seems that the problem might be related to the fact that the form is inside a div. If I remove everything on the page except for the form and js, it works ok. But the form is in a div that is hidden by default and uses another function to be displayed. Is there some kind of magic needed to get form data via serialize if it's in a div?
Edit 2
Tried adding quotes and pound signs and all that other jazz. I am using web developer toolbar, firebug, etc... it isn't throwing any js errors and doesn't afraid of anything.
Try removing the quotes from around the variable name formData in the postBody field.
The web developer toolbar in Firefox is as useful as anything for debugging client-side javascript.
BTW, the snippet contains a few undefined items, like the JS function showTransAdd(), several PHP variables, the PHP function mdate(), and the inclusion of the prototype library.
Change this line:
var formData = $('form1').serialize();
to this:
var formData = $('#form1').serialize();
I had to change several other things to make a working copy, but I'm not sure about what all code you withheld or how your environment may differ. If that doesn't work, I can send you the full code snippet I used.
Erroneous table does the breaking.
I had the form within a table with no tr's or td's (not sure if the last part matters) and upon removing the table tags, everything is working.
The relevant js now looks like:
var formData = $('form1').serialize();
var options = {
method:'post',
postBody:formData,
[...]
I'd like to thank the Academy, and all those that helped me.