I have created an example of what I am trying to accomplish:
I have an index page with a form + input elements (example.php).
When submitted I call a php page via jQuery that processes the form data and outputs result in div on index page (proces.php)
From within this php process page loaded in the div I have a button that when clicked I want to save $_POST data + other values from that page into MySQL.
I simply just cannot figure out how to "re-use" $_POST data and new values from example.php file and process.php file so I can save it from proces page when clicking button on proces.php page.
This is the example: http://mazey.dk/example.php
When form on index page is submitted the proces.php is called and here all POST data is parsed. This data I want to save when clicking Save button in proces.php file.
I hope someone can guide me in the right direction.
Thanks
***** UPDATE *****
Let me break down the code I have:
On example.php page I have a POST form with an action and a jQuery/AJAX script that prevents form from submitting in a normal way, instead it sends POST to form action URL. Result is then shown inside the with .previews class.
<script>
$(document).ready(function(){
$('.selectform').ajaxForm( {
target: ".previews",
//success: function(res) {
//$( "#currentOrders" ).load(window.location.href + " #currentOrders" );
//}
});
});
</script>
<form action="proces.php" class="selectform" method="post">
<input name="test" type="hidden" value="123">
<div class="form-group col-md-9">
<input name="inputtest" type="text">
</div>
<div class="form-group col-md-9">
<div class="">
<button class="btn btn-primary btn-lg" type="submit"><i aria-hidden="true" class="fa fa-calculator"></i> Calculate</button> <button class="btn btn-default btn-outline btn-lg" type="reset">Reset</button>
</div>
</div>
</form>
<div class="col-md-6 col-lg-6 col-xl-6 col-xxl-6">
<div class="previews"></div>
</div>
Inside proces.php file (that displays in the .previews ) I have a button. This button I want to trigger a "save-action" so when clicked I can save POST values + other variables that will be defined in proces.php into the MySQL DB. I have no problem in handling functionality to MySQL, but I need to figure out how to call POST data + variables upon clicking the button.
Proces.php file:
<input type="submit" name="save" value="SAVE" class="btn btn-lg btn-default">
<?
print_r($_POST);
$newTest = "Check";
$data = 234;
// TEMPERATURE CONTROLLER
$controller = explode("|",$_POST[controller]);
$controllerCostEach = $controller[1];
$controllerName = $controller[2];
$controllerCost = $controller[1];
$qtyController = $controller[0];
$controllerAssemblyCost = $controller[3];
$totalControllerAssemblyCost = $controllerAssemblyCost * $qtyController;
$controllerCost = $qtyController * $controllerCost;
//SUBMIT BUTTON CLICKED
//E.g if(save).clicked{
echo "HERE I can save original $_POST data + other variables from $_POST values from index file and this proces.php file via standard mysqli_query";
//}
//SUBMIT
?>
I hope with this explanation that someone can help me :-)
Related
For some reason, my form won't post, any ideas as to why(I already know that everything else on my server is operational)? Code below:
PHP
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
}
?>
https://pastebin.com/hHeMD4Mq
HTML/AJAX JS
<form id ="form">
<p>Name:</p>
<input name="field1" type="text" id ="name" />
<h3> </h3>
<p>Message:</p>
<textarea name="field2" type="text" id ="message"></textarea><br/>
<button onclick="pos();">reply</button>
</form>
</td>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function pos(){
var values=$("form").serialize();
$.post('form.php', values, function(response) {
console.log("Response: "+response);
});}
</script>
https://pastebin.com/eAVE8EGS
demo on my site:
jakesandbox.com/dnd/
(any info not provided above will be provided upon request in the comments)
The problem is your button is actually submitting the form (Which is essentially reloading the page, as it's submitting to itself). You need to do one of 2 things:
Change your button to a type="button" to prevent it from submitting (A button inside of a form element automatically becomes a submit button):
<button type="button" onclick="pos();">reply</button>
Prevent the click action from taking place (Thus preventing the submit):
<button type="button" onclick="pos(event);">reply</button>
<script type="text/javascript">
function pos(e){
e.preventDefault();
var values=$("form").serialize();
$.post('form.php', values, function(response) {
console.log("Response: "+response);
});}
</script>
-OR-
<button type="button" onclick="pos(); return false;">reply</button>
It turns out your form is actually sent normally with GET request (you can probably see the page reload). It occurs when a button inside a form has no specified type (default being submit).
A button of type "submit" inside a form submits the form while a button of type "button" doesn't.
Just add the attribute type="button" to your button and your problem should be solved.
<button type="button" onclick="pos();">reply</button>
On your php end to debug if the data actually came
<?php
header('Content-Type: application/json');
echo json_encode($_POST);
Then on your js
$.post('form.php', values, function(response) {
console.log(response); // return json
});}
I need to show status after the onClick event of a button. But I want the shown button to be on another page. Is this possible?
For example, one button on my Investigation page shows the patient status for a user. If I click that button, the investigation status should be Pending and a user list should display in front of that particular patient.
Try this using jquery
Html
<button id="first-button" type="button" class="btn"> first button </button>
<button id="second-button" type="button" class="btn hide"> Pending </button>
Script
$("#first-button").click(function(){
ev.preventDefault();
$('#second-button').removeClass('hide');
$('#first-button').addClass('hide');
});
OR
In php
<?php
if($pedding)
{
echo '<button id="pending" type="button" class="btn">Pending</button>';
}
else
{
echo '<button id="status" type="button" class="btn">Status</button>';
}
?>
As a workaround for not being able to have nested forms, I've written a system that uses Javascript to update an outside form's hidden input values and then submit the form. It is working just fine on one page in my site, but for some reason it isn't on another page. In the browser's JS console, I see the correct ID for the form I want submitted, but the server-side keeps showing a different form's data.
Here are relevant code snippets:
So the button's onclick action calls the JS function updateAndSubmitForm () to submit the actual form I want submitted for this button ("formAddStage") and NOT for the surrounding form "form-update-plan".
<form id="form-update-plan" class="form-horizontal" action="/secure/treatment-components/EditTreatmentPlan" method="POST">
<input type="hidden" name="requestedAction" value="plan-edit-update">
...
<button role="button" class="btn btn-default btn-xs" title="Add a stage to this treatment plan."
onclick='updateAndSubmitForm("formAddStage", ${treatmentPlan.treatmentPlanID }, 0, 0)'>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
...
</form>
Here is the form "formAddStage" which is at the botton of the page outside of the form that contains the button:
<form id="formAddStage" action="/secure/treatment-components/CreateStage" method="POST">
<input type="hidden" name="requestedAction" value="add-stage-to-treatment-plan">
<input type="hidden" name="path" value="${path }">
<input type="hidden" id="taskIDDynamic" name="taskID" value="" >
<input type="hidden" id="stageIDDynamic" name="stageID" value="" >
<input type="hidden" id="treatmentPlanIDDynamic" name="treatmentPlanID" value="${treatmentPlan.treatmentPlanID }">
<input type="hidden" name="clientUUID" value="${clientUUID }" >
</form>
And here is the JavaScript which gets the form by the ID supplied, gets and sets the values of the hidden fields in that form with the supplied values, then submits.
function updateAndSubmitForm(formID, treatmentPlanID, stageID, taskID){
var form = document.getElementById(formID);
var inputTaskID = form.elements["taskIDDynamic"];
inputTaskID.value = taskID;
var inputStageID = form.elements["stageIDDynamic"];
inputStageID.value = stageID;
var inputTreatmentPlanID = form.elements["treatmentPlanIDDynamic"];
inputTreatmentPlanID.value = treatmentPlanID;
var requestedAction = form.elements["requestedAction"];
console.log("Updating and submitting form " + form.id + " - requestedAction: " + requestedAction.value);
//alert("Updating and submitting form " + formID + " - requestedAction: " + requestedAction.value);
form.submit();
};
So, in summary, clicking the button should call the JS function updateAndSubmitForm() which then gets the form designated in the method's argument "formID" and then take the remaining arguments to update the values of the form and then submit it.
What ends up happening is that my browser console reports the proper information (form id = "formAddStage" and requestedAction = "add-stage-to-treatment-plan") but the server side reports getting information from the form (id="form-update-plan") that is surrounding the button (e.g. request.getParameter("requestedAction") returns "plan-edit-update" instead of "add-stage-to-treatment-plan".
Any ideas about why form.submit() in the JS function does not seem to submit the proper form or why the server is getting a different form?
The button element within the "form-update-plan" form does not have a type specified, it will therefore be defaulting to a type of submit and submitting the "form-update-plan" form.
Try this:
<button type="button"
I have a form action which generates the report. I want to add a message pop up like Please wait the report is loading
How can I do this in js.
<form action="step50/generateReport" method="GET" id="form_generate">
<input style="margin-top: 20px;" type="submit" id="btnGenerate" value="Generate"/>
</form>
I am trying this:
function popupProcessStatus(){
$.fancybox({href:'#display_status_inline', closeBtn: true, helpers:{overlay: {closeClick:false}}});
}
<div id="display_status_inline" style="display: none">
<br>
<p>Please wait until the report is generated.</p>
</div>
But not sure where to call this function so as to display this when the btn is clicked and go off when the report is generated.
just call the function on submit:
var form = document.getElementById("form_generate");
form.addEventListener("submit",popupProcessStatus,false);
I am new to Jquery and struggling to retrieve date values from my 'span' element in my jquery code and want to post it along with my form using java script.The reason i need to use this approach is that I am trying to use date range picker provided at http://www.dangrossman.info/2012/08/20/a-date-range-picker-for-twitter-bootstrap/
I have no idea how can i embed my span element value to my form and post it other page along with other form data.
Javscript
<script type="text/javascript">
document.getElementById("btnsubmit").addEventListener("click", function () {
var s;
s=jQuery.data($('aname'),s);
alert(s);
document.form.submit();
});
</script>
FORM:
-
<b class="caret"></b>
<span><?php echo date("F j, Y", strtotime('-30 day')); ?> - <?php echo date("F j, Y"); ?> </span>
</div>
<button id="btnsubmit" onclick="document.getElementById('frmdate').submit();">submit</button>
</form>
All i want to retrieve value of date from span element and post it along with form to retrieve it on next page to filter records from database based on this value.I would appreciate if anybody could help me in this regard.Thanks
As i suggested in the fiddle:
<form action="#">
<b class="caret"></b>
<span>14-10-2014</span>
<input type="hidden" name="tt" value="10-10-2014" />
<input id="tt2"/>
<input type="submit"/>
submit
<form>
And for the java script:
$(document).on('click', '#submit', function(event) {
event.preventDefault();
alert($("input[name='tt']").val()+" - Method 1");
$("#tt2").val($("span").text());
});
$(document).on('submit', 'form', function(event) {
event.preventDefault();
alert($("input[name='tt']").val() + " - Method 2");
$("#tt2").val($("span").text());
});
Don't forget to add the Jquery script.
(In the edit i've included the copy from the span)
Best regards
I think you haven't followed your tutorial properly.
Here is some code from the tutorial, and you will notice it puts the data into an INPUT field which will then be automatically sent as the form data, no added jQuery needed.
<form id="frmdate">
<div class="form-group">
<label for="reservation">Reservation dates:</label>
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" name="reservation" id="reservation" />
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#reservation').daterangepicker();
});
</script>
Also in your code you've mixed jQuery and standard javascript badly.
For one you're listening for a click of the button rather than the submit of the form, this means your code will never execute if a enter hits Enter key and it submits the form without clicking the button. Moreover this is bad practice for that reasons alone (and many other reasons)
Here is a cleaned up version of your code:
<form id="frmdate">
...
<b class="caret"></b>
<span id="aname"><?php echo date("F j, Y", strtotime('-30 day')); ?> - <?php echo date("F j, Y"); ?></span>
<button id="btnsubmit" type="sumbit">Submit</button>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#frmdate').submit(function(){
// Do some code here.
});
});
</script>