issue with PHP POST values as orientation changes on an iPad - php

I have a website, written in PHP, which is setup to run on desktop, mobile and iPad. Everything seems fine with desktop and mobiles. However, on the iPad I have an issue where I can save submitted POST values to the database in portrait mode, but when I try doing the same thing in landscape, I just don't get the values that were actually submitted in the form from the POST.
I have the same code for the input form in both orientations. However, when I check the data received as POST values in portrait mode, I do get the data that was actually entered into the fields in the form. My problem is that when I do the same thing in landscape mode, I don’t get the submitted value from the form. Instead, I get the data for that field from the database, when there really doesn’t seem to be any way that that data could end up as the POST value. This really doesn’t seem possible considering how my code is set up.
I will now talk you through key parts of my code in all of this.
I have two JavaScript functions in the header section of my index.php file, which are used to check orientation and also to respond to orientation changes (as shown below). These hide/show divs for each orientation in the body of the same index.php file. These do both work, as I see the page content change correctly on the iPad, as I change its orientation.
function check_orientation() // check orientation for ipad home page.
{
var div_portrait = document.getElementById('ipad_home_page_portrait');
var div_landscape = document.getElementById('ipad_home_page_landscape');
if(window.innerHeight > window.innerWidth)
{
div_landscape.style.display = 'none';
div_portrait.style.display = 'block';
}
else
{
div_portrait.style.display = 'none';
div_landscape.style.display = 'block';
}
}
window.addEventListener("orientationchange", function()
{
var div_portrait = document.getElementById('ipad_home_page_portrait');
var div_landscape = document.getElementById('ipad_home_page_landscape');
if (window.orientation == 0)
{
div_landscape.style.display = 'none';
div_portrait.style.display = 'block';
}
else
{
div_portrait.style.display = 'none';
div_landscape.style.display = 'block';
}
}
, false);
In the body of index.php, I have the following which has been simplified, to keep this from getting any longer than it already is. At the same time all the key/relevant bits of code have been included:
<body onload='check_orientation();'>
<div id='ipad_home_page_landscape'>
<?php include ('view_edit_company_ipad.php'); ?>
</div>
<div id='ipad_home_page_portrait'>
<?php include ('view_edit_company_ipad.php'); ?>
</div>
</body>
As stated above I use the same code file in both orientations (as can be seen in the 2 divs above). I get this to work by using conditional code at key points in the file for setting the widths and heights of page components.
The file ‘view_edit_company_ipad.php’ includes a form which allows the user to input data, etc. The following is one the fields from that form:
<input type='text' name='company_contact_name' value='<?php
if (isset($company_contact_name)) echo $company_contact_name; ?>' />
As I’ve already stated, I can get the data inserted into the form in portrait mode, if I check the POST value with the following code:
<?php echo $_POST[‘company_contact_name’]; ?>
However, if I do the same thing in landscape mode, I don’t get the value that was submitted in the form, even when all the code is exactly the same.
Also, I use that echo statement right at the very top of my index.php file, so there is no way that any of my code has changed that POST value. I just don’t get the data that was inserted as 'company_contact_name' from that echo statement when I’m using the iPad in landscape mode.
I realise that I've written a lot here, but I couldn't give all the required info, if I'd made it any shorter. Big thanks to anyone who reads this and even bigger thanks, if you can offer a solution of any sort.

Try var_dump() dumping the entire $_POST superglobal to see what the script receives from the browser.
I suspect the isssue is with multiple form control names within the same form. If both the divs code is within the same form and in both divs you have the input with name company_contact_name then only one of them (the one in the portrait div) is sent on form submission.
If this is the case, then check out the solution at Multiple inputs with same name through POST in php
Basically you can have an array of inputs, though you could also rename one of them.

Related

Get the data from an iframe after form post has completed performing a file upload on target for

I have a form which uses the target attribute to target an iframe when the form is posted which posts to a PHP script. This part is working fine but I need to do something based on several results that the php script will put in the iframe.
What I am thinking of doing is when the PHP script has finished posting it echo's out some hidden input fields that contain various elements, such as the state of the post, whether it succeeded and what the final result was if it was successfully posted.
However, if I did this it would put it into the iframe so then the main web page wouldn't be able to access the hidden input fields.
How would the main web page be able to access these hidden input fields so that the main web page can perform some action, I.e. make a div within the web page show a specific error message or whatever.
The other thing is, once I know how I can get the data from the hidden input field, how would I know when I can go and get the values. I was thinking that when the form is posted via a JavaScript document.forms["myform"].submit() code I could then do a while loop and check to see if another hidden input field status is set to complete and once it says complete I can then get the values from the hidden input field.
I'm not sure if the way I suggested is the right way or doing what I want to achieve or if there is a better way of doing it.
UPDATE
I've tried what #lanzz suggested but it doesn't appear to have worked. Below is what I have tried.
$("iframe#image_upload_frame").on('load', function()
{
var iframeBody = this.contentDocument.body;
var data = $(iframeBody).find("#imageDirectory");
alert("data: " + data);
});
Below is how the iframe is defined
<iframe id="image_upload_frame" name="image_upload_frame"></iframe>
and I am echoing out a hidden input field in the php script that's within the iframe.
echo '<input type="hidden" id="imageDirectory" value="'.$imageDirectory.'" />';
The echo is definetly working as when I see view the iframe source I can see the hidden input however, the alert dialog is never shown as if something isn't working. There are no errors being reported either by the google chrome dev console.
If I understand correctly - you need a value from the iframe in the parent window, once the value is loaded into the iframe. I would add javascript to the iframe calling the parent and executing a function.
In the main frame:
function incomingValue(val) {
alert(val)
}
and somewhere in the generated iframe:
<script type="text/javascript">
parent.incomingValue("Hello world");
</script>
This should work assuming both frame sources share the same domain.
You can use postMessage for cross document communication between an iframe and it's parent.
See:
http://viget.com/extend/using-javascript-postmessage-to-talk-to-iframes
http://javascript.info/tutorial/cross-window-messaging-with-postmessage
Since you're running on the same domain, your main page's Javascript will have no trouble to access the contents of the <iframe> (example uses jQuery, you could rewrite into whatever libs you plan to use):
$('iframe#the-id-of-the-iframe').on('load', function() {
var iframeWin = this.contentWindow;
var iframeBody = this.contentDocument.body;
// access global JS vars defined in the iframe:
var someIframeVariable = iframeWin.globalIframeVariable;
// or, directly access elements in the iframe:
var someIframeElement = $(iframeBody).find('#element-id-inside-iframe');
});
A while ago I wrote a piece of code to upload a picture using some javascript and two iframes. The most important thing for me was to preview the pic. Maybe it will help you:
HTML:
<div id='fakebutton' onclick='select_pic()'>Just a button to select a pic</div>
<iframe src='uploadform.php' name'pic_frame'></iframe>
<iframe src='#' name='target_frame'></iframe>
both the iframes are hidden. The targetframe has no source (or an empty page, if you want to).
uploadform.php contains a form:
<form id='upload_form' action='dosomething.php' method='post' enctype='multipart/form-data' target='target_frame' onsubmit=''>
<input id='realfoto' name='realfoto' type='file' onchange='parent.foto_upload(window.frameElement.id)'>
</form>
and then some javascript:
First of all something to trigger the filebrowser when the user clicks the fake
function select_pic(){
b=window.frames['pic_frame'];
b.document.upload_form.realfoto.click();
}
And then a part to actually upload the pic, triggered by the onchange() in the input element:
function foto_upload(o){
var b=o;
o=getElementById(o);
if(o.contentDocument ) {o = o.contentDocument;}
else if(o.contentWindow ){o = o.contentWindow;}
else{return false;}
if(test_pic(o,b)){ //test if it is really a pic
getObj('foto_tmpdir').value=o.getElementById('tmp_dir').value;
o.getElementById('doctype_nr').value=b;
o.fotoform.submit();
}
else{
return false;}
}
In dosomething.php I perform actions on the uploaded pic (rename, resize etc). And it contains a few lines of javascript:
$a = 'upload was succes';
$b = 'my_image_name';
$c = 'whatever you want to put here';
?>
<script type="text/javascript">
window.top.window.smurf(<?php echo "'$a','$b','$c'" ?>);</script>
<?php
if you create in javascripty a function named smurf(a,b,c) you can pass along whatever you want form the php-script. One of the most important things for me was that I now can pass the filename of the uploaded pic to javascript, and use it to change an image.src for a preview.
Hope you can use something of it.
Your iframe source page should has a javascript call function instead of the hidden field. The function will call the opener window (your main page) and then it do any functionality you want. As blue print look at the following:
//in iframe src.php
<?php
if ($something){
?>
<script>
function doSomethingWithOpenerWindow(){
opener.document.write('hi);
}
doSomethingWithOpenerWindow()
</script>
<?php
}
else{
?>
<script>
function doAnotherSomethingWithOpenerWindow(){
opener.document.write('hi);
}
doAnotherSomethingWithOpenerWindow()
</script>
<?php
}
?>

Validating dynamic number of form elements in PHP

I need to make a form where client information can be added by people at the administration department. On the first form page, information like client name, address and contact details can be entered, as well as whether or not the client has children.
The form gets validated by PHP. If the client does not have children, the data is saved to the database. If the client does have children, the form data gets saved in hidden form fields, and a second form page is shown, where up to 10 children and can be added.
However, on initial page view, only one text input is visible. With a javascript button, more text input fields can dynamically be added (until the limit of 10 is reached).
The problem is the validation in PHP. If one of the text inputs contains a non-valid string, the form should be re-displayed with the right number of fields, and those containing errors in a special HTML class (in the CSS i give that class a red border for usability reasons, so the user can immediately see where the error resides). However, because the adding of fields happens with Javascript, the form gets re-displayed with only one field.
Any ideas on how to address this problem are very welcome. I'm proficient in PHP, but JavaScript is very new to me, so I'm not able to make big changes to the script i found to dynamically add fields.
I've dealt with something similar in the past. There are a couple of options that come to mind.
Since you have JS code to generate new fields at the click of the button, why not expand that JS function so it can also be called with some parameters passed. If there are parameters, it will populate the fields with existing data.
Then, if the form is being re-displayed due to errors, or for editing, from PHP, pass some information to Javascript so that when the page loads, you create the fields and populate them with data.
To illustrate, I assume you have something like this:
Add Another Child
And you have the function:
function addNewFormField() {
// create new HTML element to contain the field
// create new input, append to element container
// add container to DOM
}
Change it so it is like this:
function addNewFormField(data) {
// create new HTML element to contain the field
// create new input, append to element container
// add container to DOM
if (data != undefined) {
newFormElement.value = data.value;
newContainerElement.class = 'error';
}
}
And from PHP, add some code that runs onload:
<script type="text/javascript">
window.onload = function() { // replace me with jQuery ready() or something proper
<?php foreach($childInList as $child): ?>
addNewFormField({ value: '<?php echo $child['name'] ?>' });
<?php endforeach; ?>
}
</script>
Hope that helps, its a high level example without knowing exactly how your form works but I've used similar methods in the past to re-populate JS created fields with data from the server side.
EDIT: Another method you could use would be to create the HTML elements on the PHP side and pre-populate them from there, but that could end up with duplicate code, HTML generation from JS and HTML generation of the same stuff from PHP. As long as the JS side was smart enough to recognize the initial fields added by PHP you can go with whatever is easiest to implement. Personally I'd just extend your JS code to handle optional data like illustrated above.

Sending PHP variable, via jQuery to landing page whilst skipping third party submission script?

My goal is to set a Google Conversion value from a custom field defined in WordPress. The conversion script is located on the landing page, so I need to get my custom field data from my form to the landing page. I can't use GET or POST as the form submission is handled by a third party and no data is returned to the actual landing page.
So I've tried using a PHP session, but this third party is getting in the way of just being able to use PHP, because it's keeping all the data for itself.
This is the approach I'm hoping I can get working:
The validation for the form is done using jQuery Tools.
I then need to submit the variable after validation has been successful via jQuery/AJAX to a separate php file.
Then as the landing page starts to load, I must grab that variable from mentioned PHP file and echo it in the relevant place.
I figured I don't actually need to start a session on the page with the form, as jquery is grabbing the data straight out the input, not any session data. So here's my input with conversion value:
<input type="hidden" id="conv" name="conv" value="90">
Then my form validation:
$("#course-form-modal").validator().submit(function(e) {
// when data is valid
if (!e.isDefaultPrevented()) {
// this grabs the value from my form
var con_val = $("#conv").val();
// and this sends it...
$.post(
"../../usersession.php",
{ data: con_val }
);
}
});
Then I've got the code in usersession.php... where I sent the data:
// As I'm just trying to echo what was sent to this page, via ajax, I shouldn't need to worry about starting/retrieving a SESSION yet... right?
<?php $var_value = $_POST['data']; ?>
<div id="results">
<?php echo $var_value ?>
</div>
// I CAN WORRY ABOUT THIS HALF LATER. RIGHT NOW I JUST WANT TO ECHO MY RESULTS ON USERSESSION.PHP //
Finally, I've got the code on my landing page to retrieve the data from usersession.php:
session_start();
$var_value = $_SESSION['conv'];
echo $var_value;
I'm not entirely sure all this code is right for starters, I'm more of a front end guy...
-EDIT-
Right, I'm pretty sure the code is correct at least now. For some reason it's still not working though. At the moment I'm wondering if WordPress would prevent me writing to usersessions.php from my javascript file (for reference, that file path is set absolutely in my working (not working) example)? I know WordPress will sometimes throw a 404 when you try to access a file directly.
The other potential issue could be with the third party software, vanillasoft. I've a link to their script in the action tag of my form, could that somehow bypass/kill the sending/receiving of data between the form > usersession.php > and then the landing page?
On a side note, if anyone has a great idea on how I can test if usersession.php is receiving the data then please let me know? I did have this code originally, but it returns nothing and if I link straight to the file after a send something (as in just paste the file url in to my browser) it returns a '0'...
if(isset($_POST['conv'])) {
session_start();
$_SESSION['conv'] = $_POST[''conv''];
echo "1";
} else {
echo "0";
}
Set your ID on the input. jQuery is looking for the ID, but you have only set the name.
<input type="hidden" name="conv" value="90">
Should be:
<input type="hidden" name="conv" id="conv" value="90">
EDIT:
Can't believe I didn't catch this earlier. Your problem is in the usersession.php at the following line.
$_SESSION['conv'] = $_POST[''conv''];
You have the POST quoted wrong.
It should be:
$_SESSION['conv'] = $_POST['conv'];
EDIT (re: New js edits)
In you java script your post vars should be formatted thusly:
{ name: "John", time: "2pm" }
So your line should be something like this:
$.post(
'../../usersession.php',
{
conv: $("#conv").val()
},
function(data)
{
alert("Data Loaded: " + $("#conv").val());
}
);

How to upload and read text/csv file without submitting?

I have this form and I would like to read the uploaded file and then fill out the form using this read information without refreshing the page.
For example the first word might be "Bob" and so I would want that to go in my input text "First_name." I've been trying to searching online for a way to do this using JQuery or Ajax but I can't seem to find a solution.
Can this be done using the two methods previously mentioned? If so and if not can someone point me to a link or to where I can learn how to do this? The instances I have found include where one uses JQuery to upload the file and display the size without refresh (which is not exactly what I want).
I have also found how one can use an iFrame but this again is not what I want. I suppose I could always just submit the part of the page containing the textfile related information and show the same form but with the filled out information. But I feel as if this is kind of sloppy and I want to know if there is a better way.
Thanks.
Firefox has a method to do this, the File and FileList API provide a way to get at the files selected by a file input element and have a text retrieval method.
A very basic example:
NB. Not all browsers support this code.
[I think Chrome, Firefox and Opera do at time of writing.]
HTML:
<form>
<input type="file" name="thefile" id="thefile" />
</form>
<div id="text"></div>
JS (using jQuery):
$(document).ready(function() {
$('#thefile').change(function(e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
$('#text').text(e.target.result);
};
reader.readAsText(e.target.files.item(0));
}
return false;
});
});
Demo: http://jsfiddle.net/FSc8y/2/
If the selected file was a CSV file, you could then process it directly in javascript.
.split() will be useful in that case to split lines and then fields.
the only way I know would be to submit the form to a hidden iframe. this will upload teh file without refreshing the page. you can then use any returned info using javascript. this is what they use for fake ajax style image uploads that let you preview an image before uploading. the truth is it already has been uploaded via a hidden iframe. unfortunately however iframes are not xhtml 1.0 compliant.
something like this article may help:
http://djpate.com/2009/05/24/form-submit-via-hidden-iframe-aka-fake-ajax/
The question you might ask is :
why should I use this method instead of real ajax ?
Well they’re is numereous answer to that but one good reason it that
is doesnt require any type of ajax libs and you can start using it
even if you never used ajax before.
So here it goes.
<form method=”post” action=”formProcess.php” target=”hiddenIFrame”>
<input type=”text” name=”test” /> </form>
<iframe style=”width:0px;height:0px;border:0px;” name=hiddenIFrame />
This is just a normal form but you’ll notice the target in the form
tag, this tells the form to submit in the iframe instead of the
current page.
It’s works exactly as the target attribut on the A tag.
Also the iframe is hidden from the user using
style=”width:0px;height:0px;border:0px;”
now the file formProcess.php is not different from your normal form
processing file but if you want do something on the main page you have
to use JS like that :
window.parent.whatEverYouWannaDoInParentForm();
You can also upload file with this method !
Please checkout the formphp for full example.
Cheers !
Nb : You will see the status bar acts like the page is reloading but
it’s really not.

php custom forum error

i have a form, and i want to have it be limited at 10 characters minimum. that is no problem, but what i want to do is echo the error at the top of the page, which is being included, so i cant just do:
echo '<div class="error">Error</div>';
i want to have a designated div that is empty (will be on the included header page), but when there is an error it gets filled with the error text to output. anyone know how to do this not using sessions or cookies?
This is a clear use-case for javascript. PHP is strictly a server-side language; that is, the code you write is executed on the server and not the client. Javascript, on the other hand, is run inside the user's browser. So say you create a div like so: <div id="error_msg" />. Then you can write a snippet of javascript code that looks like this:
function display_error () {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = "Error";
}
You would place this code in script tags at the top of your page inside the tags. More information on javascript form validation can be found here: http://www.w3schools.com/js/js_form_validation.asp
Hope this helps.
-tjw
Edit: if this isn't exactly what you're looking for, you might want to tag this post with 'javascript' to get more people who know about js form validation to answer the question.
<div id="error_msg" /></div>
<script>
function display_error (text) {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = text;
}
display error('Error: your text here..');
</script>

Categories