2 HTML forms with same submit - POST through values from both - php

Ok , maybe a hard one to explain. I have a form that is built using PHP Form Builder Class
Which looks like:
$form = new form("firstForm");
$form->setAttributes(array(
"width" => 600,
"noAutoFocus" => 1,
"jsIncludesPath" => "lib/php-form-builder-class/includes",
"action" => "uploader.php"
));
$form->addTextbox("Enter a Title:", 'title' , $row['title']);
$form->addTextbox("Enter a Promo Code:", "promo" , $row['promo']);
$form->addWebEditor("Description", "description", $row['description'], array("basic" => 1));
$form->addWebEditor("Terms and Conditions", "terms", $row['terms'], array("basic" => 1));
$form->addHidden("img_urls", $row['img_urls']);
$form->addHidden("destination", $row['destination']);
$form->addHidden("header", $row['headerimg']);
$form->addHidden("cmd", "submit_0");
$form->addButton();
$form->render();
I want to add some jQuery to one of the elements to allow drag and drop, so I've made another form element:
?>
<form id="firstForm" action="uploader.php" method="post" >
<ul class="sortable">
Mags Select:
<?
foreach ($profiles as $mag) {
?>
<div id="sorty"><input type="checkbox" name="units" value="<? echo $mag ?>" /><label><? echo $mag ?></label><br /></div>
<? } ?>
</ul>
</form>
How can I make the jQuery part post through its values 'units' when the PHP Form Builder Class is submitted?
Ive had a look at adding a method to the class, but wondered if there was an easier way?
EDIT:
The PHP Form Builder Class form is self contained, so wherever the jQuery form is in the page, it will always be outside the other.

You could use javascript and transfer the values from the second form INTO (hidden fields in) the first form?
Or similarly you could just build the form and copy the HTML (view source) and use that instead of the raw php, then slot your jQuery drag and drop thing into it that way.

Just change your second "firstForm" id to secondForm then do something like this:
$('#firstForm').submit(function(event) {
event.preventDefault();
var postData = $(this).add('#secondForm').serialize();
$.post($(this).attr('action'), postData, function() {
// Complete....
}
});
As your units input has multiple elements, you can change this to an array like so (take note of change from units to units[]):
<div id="sorty"> <!-- I assume this should be ouside the foreach... !-->
<? foreach ($profiles as $mag) { ?>
<input type="checkbox" name="units[]" value="<? echo $mag ?>" />
<label><? echo $mag ?></label><br/>
<? } ?>
</div>
Then you'll receive this just like an array in PHP:
foreach ($_POST['units'] as $key => $value)
{
}

Could you not have your jQuery drag-and-drop form field in the same <form> tag as all the other fields? That’s the natural way to do it.

Related

Button Form POST Not Working

I have a simple button that hides once the event is triggered
<?php
//Define attributes
echo'<input type="submit" id="toggler" name="add_friend"class=button
value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</input>';
?>
//Hide the button
<script>
var hidden = false;
function action() {
if(!hidden) {
document.getElementById('toggler').style.visibility = 'hidden';
}
}
The above works as it should no problems , However when I add form to get method=POST for the button does not hide nor does my POST make it to $_POST['add_friend']
echo ' <form method="post" >
<input type="submit" id=toggler name="add_friend" class="button"
value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</input>
</form>';
How can I make correct this so that the button hides and my POST is passed on to my isset code please .
if (isset ($_POST['add_friend'])){
//rest of my code once the button is clicked and hidden
Thanks in advance .
Your JS is most likely hiding the element. Then your form gets submitted (the POST), only for the page to refresh and the button reappear.
It seems to me that you want to hijack form submission and process the request with ajax.
The following example code shows a similar problem with the Php form processing. You could adapt to your liking (I have left out the required Javascript):
<?php
$feedback = null;
$people = array(
1 => 'Samuel',
2 => 'Fred',
3 => 'Roger',
4 => 'Mavis'
);
$friends = array(3); // i.e. Roger
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$add_friend = isset($_POST['add_friend']) ? $_POST['add_friend'] : null;
if(array_key_exists($add_friend, $people) && !in_array($add_friend, $friends)) {
array_push($friends, $add_friend); // You probably want to save state here
$feedback = 'Added ' . $people[$add_friend] . ' as friend.';
}
}
?>
<?php echo isset($feedback) ? $feedback : ''; ?>
<form method="post">
<?php foreach ($people as $key => $person) { ?>
<button name=
"add_friend" onClick=
"action();" value=
"<?php echo $key ?>"
<?php echo in_array($key, $friends) ? 'disabled' : '' ?>
>
Friend <?php echo $person ?>
</button>
<?php } ?>
</form>
Checkboxes may be a better fit than buttons here.
A couple things wrong with this. You have an extra double quote before 'method' in your form, and should also add action="#" to the <form> tag. This tells the browser to send the result of the form to the current page. It's also good practise to add a hidden field to send your data, rather than adding it to the submit button. Try this and see if it works.
if (isset($_POST['add_friend'])) {
var_dump($_POST['add_friend']);
}
echo '
<form method="post" action="#">
<input type="hidden" name="add_friend" value="'.$output1['username'].'">
<input type="submit" id="toggler" class="button" value="Add '. $output1['username'].' As A Friend ?" onClick="action();"/>
</form>
';
Bear in mind this will essentially reload the page, so if you want to make an asynchronous request (EG, send some request without loading the page again) you will need to look into a solution with AJAX.
unless you didn't supply more information or copy/paste everything, you seem to have extra quotations here:
echo ' <form "method="post" >
Wrapping the input in a form will natively submit the form as well as fire your javascript. If you want to use an ajax solution, tie into the submit event and prevent the default action. (using jquery here):
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
// serialize() will get the form data, which can be used in ajax call
console.log( $( this ).serialize() );
});

Populating select tag from selected items in php

i am totally new on PHP and I have an issue, i hope i can explain my problem exactly.
I have two HTML5 forms where one of the form is being populated by php for loop and inside the same form there is there is a submit button code as follows:
<form class="" name="upgradeChosen" role="form" method="post" action='index.php?action=upgradeChosen'>
<div class="col-md-5">
<select name="upgradeSelected" id="ID_UPGRADE_SELECTED">
<?
foreach ($arrayUpgrade as $value) {
$pro = $value->getnewProduct();
echo '<option value="'.$value->getId().'">'.$pro->getName()." "."===>". $pro->getPrice(Currency::getCurrentCurrency()).'</option>';
}
?>
</select>
</div>
<button style="margin-top: 40px" id="ID_CREATE_ESTIMATE" type="submit" class="btn btn-default"><i class="icon-rocket"></i>Create estimate</button>
</form>
Inside the another PHP file there is a function which is called function upgradeChosen and it parses the selected data from select tag. at the second form i would like to generate a list and populate the selected items from first listbox or select tag. Is this possible ?
Here is my second form code as follows:
<form class ="" name ="upgradeEstimate" role="form" method="post" action='index.php?action=Frontend_upgradeEstimate'>
</form>
and the function which is called upgradeChosen code as follows:
public function upgradeChosen (){
$idUpgradeLine = $this->getRequestAttribute("upgradeSelected");
$upgrade = new UpgradeRates($idUpgradeLine);
$product = $upgrade->getNewProduct();
}
please help me to achieve this if there is a way of doing it only with php i will be happy i do not want to use Jquery, JavaScript or AJAX at first stage if there is a way how to do it with php only.
For this you must use javascript.
You can use onchange event of your select for call a javascript function and reload your page with a post param. Then write your second select in php.
I think there aren't any other method.
Fabio Del Rosso.

Add items to array without refreshing the page?

http://alpha.ripfy.com/
As seen in the following demo, I have a YouTube video that I want to be able to play while adding items to the array in PHP. Sadly, this isn't possible from what I've tried because the page refreshes every time I add an item to the array.
Would there be any way of achieving this without the page refreshing (forcing the video to restart?)
Code:
<?php
if (isset($_POST['playlist'])) {
$playlist = $_POST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_POST['name1'])) {
$playlist[] = $_POST['name1'];
}
?>
<form method="post">
<?php
foreach($playlist as $song) {
?>
<input type="hidden" name="playlist[]" value="<?php echo $song?>">
<?php
}
?>
<input type="text" name="name1"/>
<input type="submit" name="submit1"/>
</form>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
Thanks for helping me out!
if you need that these information be storaged in database or anything on server sider don't use the convencional form post, use AJAX with JQuery.
First create a div(container)to render the list content where you need the information apears:
<div id="list_musics"></div>
Then create a page(i.e. page.ajax.php) that will treat your request. If you need you can put the information in a database or anything you want by this page. This page must return the content you want to render.
HTML:
<input type="button" id="ajaxcaller">
JQUERY:
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
$.post(page.ajax.php,text,function(data){
//Render your content in the container created on HTML
$("#list_musics").html(data);
});
});
If you just need to show what you wrote on text input instead of storage or treat the information, you may just use JQUERY to render the information in the container you created.
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
// PUT THE TEXT RIGHT AFTER THE CONTENT THAT ALREADY EXISTS IN THE CONTAINER
$("#list_musics").append(text);
});
Take a look here to see the sencond option:
https://jsfiddle.net/wqLf65ox/
Here's my answer. That fully works. In this script, the server checks the presence of a name1 request (post or get). If exists, it returns the string posted (only) and if doesn't, it returns what already was there. And the post() method posts (gets) the data and appends to the container using innerHTML+= data + "<br>";
evaluate the code, it should be self explanatory.
<?php
if (isset($_REQUEST['playlist'])) {
$playlist = $_REQUEST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_REQUEST['name1'])) {
// if exists, return plain text responce. NOT HTML
$playlist[] = $_REQUEST['name1'];
echo $_REQUEST['name1'];
}
else{
?>
<html>
<head>
<title>Demo</title>
<script src="jquery.js"></script>
</head>
<body>
<script>
text= ""
function onUpdate(){
text = document.getElementById("name1").value;
}
function handler(data){
document.getElementById('container').innerHTML += data+"<br>";
}
function post(){
onUpdate();
$.get("index.php", name1="+text, handler);
}
</script>
<input type="text" name="name1" id="name1"/>
<input type="submit" name="submit1" onclick="post()"/>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<br>
<div id="container">
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
</div>
</body>
<?php };?>
Although, it works as intended, i don't see the point of using it. just plain js should work
You have to send your form using Ajax, eg. via jQuery.post() method.
After that you have to reload your container with list or add new item there with JavaScript.
Try using the $.post and $.get JQuery methods. One method might be to $.post back to a .php page that renders a container of html, then use $.get to retrieve just that html container and insert into the DOM.

Jquery not submitting my form

Hi I want to submit my form using JQuery but I don't know why it won't work for me. here's the code:
$("#search_result_fake_div2").live("click", function () {
$("#search_result_present_list2").show("fast");
$('body').one('click',function() {
$("#search_result_present_list2").hide();
});
event.stopPropagation();
});
$(".search_result_list_item2").live("click", function () {
$("#search_result_fake2").val($(this).html());
$("#getattendees").submit();
$("#search_result_present_list2").hide();
});
and my HTML code:
<div>
<div id="search_result_fake_container">
<div id="search_result_fake_div2"></div>
<form method="GET" id="getattendees">
<input type="text" id="search_result_fake2" value="<?php if(!empty($city)){echo $city;} else{echo "Select Event";}?>" name="event_name">
</form>
</div>
<div id="search_result_present_list2">
<?php foreach ($events as $events1): ?>
<div class="search_result_list_item2" id="search_result_item_12" style="text-align:center;"><?php echo $events1['event_name']; ?></div>
<?php endforeach ?>
</div>
</div>
This is a drop down menu using div which came from my other question. One thing that I want to happen is for the form to submit once I've clicked a content from the drop down selection. I tried using onchange="javascript: document.getattendees.submit();" on my input box but nothing happens so I'm thinking of using jQuery instead but still the problem persists. I'm just a newbie on the jQuery and in fact I'm not that well versed on this one.
try this:
$('form#getattendees').trigger('submit');

Add HTML placeholder into Zend_Form

I'm using Zend_Form for an application form using this code:
class Form_ApplicationForm extends Zend_Form
{
public function init()
{
$this->setAction('/application/new')
->setMethod('post')
->setAttrib('id','application');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Your Name')
->setRequired(TRUE)
->addValidator('alpha', FALSE, array('allowWhiteSpace' => true));
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email Address')
->setRequired(TRUE)
->addValidator('EmailAddress');
$this->addElements(array($name,$email));
}
}
I'm adding a flash file uploader (swfupload) to this form which needs a HTML snippet to be in place to work, the snippet looks like this:
<div id="swfupload-control">
<p>Upload upto 5 image files(jpg, png, gif), each having maximum size of 1MB(Use Ctrl/Shift to select multiple files)</p>
<input type="button" id="button" />
<p id="queuestatus" ></p>
<ol id="log"></ol>
</div>
What is the best way of inserting this so that it sits somewhere within the <form> which i'm inserting within my controller like this:
public function newAction()
{
$form = new Form_ApplicationForm();
if($this->_request->isPost()){
$data = $_POST;
if($form->isValid($data)){
/// handle data here
}else{
$form->populate($data);
}
}
$this->view->form = $form;
}
Is there a way of adding a placeholder or similar within Zend_Form, or should this be done using a decorator or something like that?
Thanks.
You'd have to write your own Element for this, e.g. My_Form_Element_SwfUpload along with a renderer. See these tutorials:
The simplest Zend Form Decorator
How to layer Decorators
Rendering Zend Form Decorators individually
Creating composite elements
The simplest way is to do it in the view:
By echoing each element you can print its html. Here's one way to do it:
<form id="<?= $this->form->getId() ?>" action="<?= $this->form->getAction() ?>">
<? foreach ($this->form as $element): ?>
<?= $element ?>
<? if ($element->getName() == 'email'): ?>
<div id="swfupload-control">
<p>Upload upto 5 image files(jpg, png, gif), each having maximum size of 1MB(Use Ctrl/Shift to select multiple files)</p>
<input type="button" id="button" />
<p id="queuestatus" ></p>
<ol id="log"></ol>
</div>
<? endif ?>
<? endforeach ?>
</form>
What this does is it prints all the elements, and puts whatever you have to after the email field. If you add or remove a field from the form this code will continue to work (of course it will fail if you remove the email field).

Categories