Running a PHP file inside a DIV - javascript

I have an image upload script that works well on its own but fails when I try to run in via a PHP function that I was hoping would just keep the PHP file in the DIV
function Upload()
{
print'<div>';
include('../a/multi-image_uploader_thumbnail_creator.php');
print'</div>';
}
The PHP file runs well but once a user submits it leaves the PP function completely. The form code is:
while($i++ < $upload_image_limit){
$form_img .= '<label>Image '.$i.': </label> <input type="file" name="uplimg'.$i.'"><br />';
}
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />
</form>
';
echo $htmo;

Your include() statement is outside of PHP. You shouldn't be ?> and <?phping around it. It's a PHP function.
Also, why are you using .= if you didn't define the variable before? You can just use =.
You should consider using templates, too, but that's a bit further down the road.
Edit: Try looking at the answer to this question or this other question to send images via AJAX.

Related

Get a HTML input value out of a file which is located in a subfolder?

I'm trying out to develop a small shortcode Wordpress Plugin. Therefore, I created a main php-File and in a subfolder the HTML-File. The subfolder (classes) is located on the same level as the php-File. In the HTML-File I'm opening a Modal to enter data. By pressing the save button, a method in the php-File is called which should write date into the Wordpress-Database.
php-File (shortcode-concerts.php)
classes-Folder
HTML-File (mainLook.html)
The code snippet shows how I tried to get the values via JavaScript and document.getElementById() out of the HTML-File - which doesn't work cause it's returning null. By alerting concert.value the alert window doesn't even show up. I did find out that the DOM only works within the current document.
However, I don't know how to get the data in the php-File out of the HTML-Elements. Is there a way to do this?
The modal window in the /classes/mainLook.html File:
<div id="modal_createconcert" class="modal">
<div class="modal-content">
Concert: <input type="text" id="input_concert"/>
Date: <input type="date" id="input_date"/>
Time: <input type="time" id="input_time"/>
Place: <select id="combo_place"></select>
<button class="button" id="button_save" onclick='location.href="?button1=1"'>Save!</button>
</div>
</div>
The php-File:
<?php
function shotcode_concerts(){
include("classes/mainLook.html");
}
if($_GET['button1']){fun1();}
function fun1()
{
?>
<script type="text/javascript">
var concert = document.getElementById('input_concert');
alert(concert);
</script>
<?php
}
?>
In the HTML file, the fields aren't inside a form and the button isn't a submit...you need to do this or do a javascript that will get the values from the fields and send using POST or GET to the PHP file (POST is better).
mainLook.html
<div id="modal_createconcert" class="modal">
<div class="modal-content">
<form action="some/location/file.php" method="post">
Concert: <input type="text" name="input_concert"/>
Date: <input type="date" name="input_date"/>
Time: <input type="time" name="input_time"/>
Place: <select name="combo_place"></select>
<button class="button" type="submit" id="button_save">Save!</button>
</form>
</div>
</div>
file.php
<?php
include("classes/mainLook.html");
function fun1($var_val)
{
?>
<script type="text/javascript">
alert("<?php echo $var_val; ?>");
</script>
<?php
}
if $_SERVER['REQUEST_METHOD'] == 'POST' {
fun1($_POST['input_concert'])
}
Using this logic you can do this too by inserting a javascript in HTML file that will send the fields values to the PHP page.
I hope it helps in something.
The problem is the layout of your code, not the javascript itself. Your PHP code is executed on server side, so, it will be executed before the javascript, every time you press the button, PHP is called which causes to refresh the page and then the javascript part is called, there would not be any value on the input, which causes the alert to be blank.

Targetting button outside of a form in action.php?

I currently have 2 forms, which adds data to my database. They both work, but they each have their own submit button - and I only want one submit button to collect the data from all the forms.
I found some javascript that should set the deal;
$("#submitbutton").click(function(){
$("#form1").submit();
$("#form2").submit();
});
The button I'm targetting is outside of both forms and looks like this:
<input id="submitbutton" type="button" value="add">
I'm pretty sure the reason why it doesn't work, is because of the way my php is written. I'm targetting the submit button in each form to excecute the php.
You can see the forms and php below.
One of the forms allows you to upload a picture;
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
The action file contains this php;
<?php
if(isset($_POST['sumit']))
{
if(getimagesize($_FILES['image']['tmp_name'])== FALSE)
{
echo "Please select an image.";
}
else
{
$image= addslashes($_FILES['image']['tmp_name']);
$name= addslashes($_FILES['image']['name']);
$image= file_get_contents($image);
$image= base64_encode($image);
saveimage($name,$image);
}
}
displayimage();
function saveimage($name,$image)
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="insert into pictures (name,image) values ('$name','$image')";
$result=mysql_query($qry,$con);
if($result)
{
//echo "<br/>Image uploaded.";
}
else
{
//echo "<br/>Image not uploaded.";
}
}
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="select * from pictures";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
mysql_close($con);
}
?>
The other form lets you choose between multiple categories collected from my database;
<form id="form2" action="checkbox.php" method="post">
<label for="Category">Category</label>
<br />
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="checkbox" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
<input type="submit" name="Submit" value="Submit" class="btn btn-default"/>
</form>
And has the following php;
<?php
include("config.php");
$checkbox = $_POST['category'];
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($checkbox);$i++) {
$query = "INSERT INTO placecategory (category_id) VALUES ('".$checkbox[$i]."')";
mysql_query($query) or die(mysql_error());
}
echo "Category is inserted";
}
?>
I've tried targetting the new button I made that should excecute the javascript, but it doesn't seem to work because that button is out of the form.
Is there a way to target the button outside of the form so the php excecutes when that is clicked? Or how can I rewrite this?
Any help is appreciated!
Not sure I understand completely what you're trying to do but try this with HTML5 add form="form1" and form="form2" for your second one and let me know if this works.
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
<input type="submit" name="sumit" value="Upload" form="form1" />
Taking in account your complementary comment, then your proposed javascript sequence would work, assumed you have:
suppressed buttons such as <input type="submit"... /> from both forms
added the new button <button name="submitbutton">...</button> outside of the forms
modified the PHP parts accordingly, referencing $_POST['submitbutton'] instead of sumit and Submit respectively
You didn't report how it currently don't work, so the above steps target only the changes precisely related to the fact you replace two in-form buttons by a unique out-form one.
But something may turn wrong elsewhere. I notably noticed the non-usual way (at least for me) you get and process the image. Also you must ensure that your javascript part have really been executed.
Let me know if it doesn't work yet, than adding precise description of what turns wrong.
Edit, based on your provided comments and live preview.
Fully testing is not really possible because the server PHP part is out of reach, bue we can use Firebug to debug JS part.
So adding a breakpoint we can observe that, as soon as $("#form1").submit(); has been executed, the server returns a new page with the "Place has been added!" message.
In the other hand, without any breakpoint set, the server returns returns a new page with the "Categorie inserted!" message.
Though the OP didn't show the addingplace.php part of the current live preview, and comparing with the checkbox.php part, we can guess that:
In the reduced execution part, the first step addingplace.php did work as expected.
What we observe while whole execution merely means that all three parts have worked as expected, but each one having its returned message overwritten by the next one, but for the last one.
In other terms, when you comment "it only seems to submit the last form", this is a false impression based on what you only can see.
To ensure this is true or not you should control what is really updated or not in your database.
Let me know.
That said, it must be noted that this illustrates how the couple server-browser works in those circumstances: as already pointed by #David in a comment under the OP, to submit a form causes the browser to immediately receive a new page which overwrites the current one.
In the current example, it works because there are only few forms, and all three are submitted in a very reduced time, almost instantly: so the 3rd submit() can get executed before the 1st one's returned page comes.
So the recommended way to achieve the whole work in your example is merely to use only one form, with its unique submit button. BTW I wonder why you wanted to have this more complicated structure with three forms: what is the expected benefit?
Last point, outside of the precise issue you reported: you should pay attention to how you're coding. There is a lot of inconstencies in the HTML part, e.g.: a <html><body> part inside the already existing <body>; an exotic <br></br>; also you kept a supplemental button in the 1st form.

Get value of a submitted form without submit button

I'm trying to upload an image without submit button. My code works fine for submiting without button.
My HTML code
<form name="service_image_form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Add new image <input name="userfile" type="file" id="userfile" onchange="return subForm()" />
</form>
<script>
function subForm() {
document.service_image_form.submit();
};
</script>
But I'm little confused in retriving data at PHP.
In php I tried something like this to retrieve data.
if (isset($_POST['service_image_form']))
{
echo "working";
}
Here I'm trying to echo "working" just for confirmation. If my condition works then then I can save my image to server and db. I know its very simple but stumbed here for a while. surfed lots of links, but no idea. Please help me out with this.
I know if I had a submit button with name="submit" then I can retrive like this
if(isset($_POST['submit']))
{
upload code comes here..
}
I dont wan't submit button..
To check if a post request is made:
if($_SERVER['REQUEST_METHOD']=='POST'){
echo "working";
}
Note that uploaded files data will be in the $_FILES superglobal, not $_POST, and as mentioned by Fred, you will need to add the enctype attribute on your form
You need to add enctype attribute into your for like this
<form name="myform" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Add new image <input name="userfile" type="file" id="userfile" onchange="return subForm()" />
</form>
And in your php you get the uploaded files using the $_FILE
<?php
if ($_FILES['userfile']['error'] > 0) {
echo $_FILES['userfile']['error'];
} else {
echo 'Name: ' . $_FILES['userfile']['name'];
echo 'Temp file location in: ' . $_FILES['userfile']['tmp_name'];
}
?>
So basically you are trying to check if upload is correct, right? Well, it's not how it's done.
PHP has great manual for that http://php.net/manual/pl/features.file-upload.php
You miss:
correct form encoding, add attribute enctype="multipart/form-data" to your form tag
your file will be placed in $_FILES['userfile'] variable
you can check $_FILES['userfile']['error'] to determine if upload was successful (if so, it will be equal to constant UPLOAD_ERR_OK, 0)
After that you are good to go, you can find all the details here http://php.net/manual/pl/features.file-upload.post-method.php it's pretty straightforward.

How To Send Form Data To Two Or More PHP Files?

I have a Form in an HTML page like below that is sending my data to a page at http://www.aaaaaa.com/1st-file.php...
<form action="http://www.aaaaaa.com/1st-file.php" method="post" enctype="plain" id="theForm">
<input type="text" name="NAME" value="Some Data" />
<input type="submit" value="Send Data" />
</form>
But I want to send the same data on http://www.bbbbbb.com/2nd-file.php. My form is on HTML page and I want to send data via one click on Send Data only. So is this possible to send data on both PHP pages using pure JavaScript not JQuery? If yes then how?
Update:
My both PHP receiving files have codes something like below...
<?php
$data_from_site= $_POST['NAME'];
echo $data_from_site;
?>
Use an iframe as described here,
<input type="submit" value="Send Data" onclick='javascript: return SubmitForm()' />
<iframe name='frame_result1' width='350px' height='100px' frameborder='0'></iframe>
<iframe name='frame_result2' width='350px' height='100px' frameborder='0'></iframe>
function SubmitForm()
{
document.forms['theForm'].action='http://www.aaaaaa.com/1st-file.php';
document.forms['theForm'].target='frame_result1';
document.forms['theForm'].submit();
document.forms['theForm'].action='http://www.bbbbbb.com/2nd-file.php';
document.forms['theForm'].target='frame_result2';
document.forms['theForm'].submit();
return true;
}
Imho, if you don't want to use Jquery, the best solution for you is to send an xmlhttprequest via js. see Request to the Server
You can take advantage of cURL() and fputs() PHP functions. Here's the sample implementation. http://www.html-form-guide.com/php-form/php-form-submit.html

how to open same page onsubmit? [duplicate]

This question already has answers here:
POST form and prevent response
(2 answers)
Closed 9 years ago.
I have html form whose action is a php script. php code basically replaces the file.
HTML code:
<form name="input" action="//copy.php" method="POST" onsubmit="return alertbox();">
<input type="hidden" name="path1" value=path to image 1/>
<input type="hidden" name="path2" value='path to image 2' />
<input type="submit" name="submit" value="Copy image"/>
</form>
Php code:
if isset($_POST['submit']))
{
$image1 = $_POST['path1'];
$image2 = $_POST['path2'];
copy($image1, $image2);
}
?>
Now when I click submit, a alert box opens that "file is updated successfully" and when I click ok on it, a blank page load. How can I avoid loading the blank page? I want to stay on the same page after clicking submit with pop up msg.
SOLUTION
As I don't see "Answer your own question" option, I am posting solution here.
This link POST form and prevent response, gives you textual answer to the question. While I providing the answer by code.
So basically, it very simpl. Just put
header("HTTP/1.0 204 No Response");
in the php file and it will work successfully on all browser, without opening new page. This will avoid use of jquery.
Leave action empty.
<form method="post" action="">
Then check if posted using isset function
if(isset($_POST)){
...
}
This will keep you on the same page after submit button..
<form name="input" action="" method="POST" onsubmit="return alertbox();">
<input type="hidden" name="path1" value=path to image 1/>
<input type="hidden" name="path2" value='path to image 2' />
<input type="submit" name="submit" value="Copy image"/>
</form>
But now, your image(s) may not be loaded. Maybe it will work, maybe not. If not, you will need to resolve functions which may reside in copy.php file. Since we dont know whats in that file, its hard to answer your question correctly, but.. you may try this "blind" shot..
if(isset($_POST['submit']))
{
//include "//copy.php"; // this file probably contains functions, so lets load functions first IF needed..
$image1 = $_POST['path1'];
$image2 = $_POST['path2'];
copy($image1, $image2);
}
Have you tried changing the type on the input:
<input type="submit" name="submit" value="Copy image"/>
to
<input type="button" name="submit" id="submit" value="Copy image"/>
<input type="button" /> won't submit a form by default (check all browsers to be sure).
<input type="submit"> by default, the tag in which the submit input is, is submitted. If you still want to use this, you will have to override the input submit/button's functionality with an event.preventDefault(). In that case, you need:
$('#submit').click(function (event) {
event.preventDefault();
//Do whatever you need to
//Submit if needed: document.forms[0].submit();
});
For further details refer this link
action="<?php echo $_SERVER['PHP_SELF']; ?>

Categories